问:
Unable to upload file to google cloud storage using post method
Below is my code. I copied the interoperable access keys.. The client and secret both from the same page. I used client key in the ClientAccess ID in the form and secret for hashing.
But i get the error saying invalid argument.

Detail error being shown as "Cannot create buckets using a POST"

Below is the python code i used.

```<code>import webapp2
import cgi
import datetime
import urllib
import base64
import hmac, hashlib
import sha

policy_document = '''{"expiration": "2016-06-16T11:11:11Z",
                    "conditions": [
                        ["starts-with", "$key", "" ],
                        {"acl": "public-read" },
                    ]
                }'''

policy = base64.b64encode(policy_document).strip()
h = hmac.new('xxx', digestmod=sha.sha)
h.update(policy)
signature = base64.b64encode(h.digest())

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('<html><body>')
        self.response.write('<form action="http://storage.googleapis.com/www.xyz.com" method="post" enctype="multipart/form-data">')
        self.response.write('<input type="text" name="key" value="">')
        self.response.write('<input type="hidden" name="bucket" value="www.xyz.com">')
        #self.response.write('<input type="hidden" name="Content-Type" value="image/jpeg">')
        self.response.write('<input type="hidden" name="GoogleAccessId" value="GOOGxxxxx">')
        self.response.write('<input type="hidden" name="acl" value="public-read">')
        self.response.write('<input type="hidden" name="success_action_redirect" value="http://www.linklip.com/storage.html">')
        self.response.write('<input type="hidden" name="policy" value="%s">' % policy )
        self.response.write('<input type="hidden" name="signature" value="%s">' % signature )
        self.response.write('<input name="file" type="file">')
        self.response.write('<input type="submit" value="Upload">')
        self.response.write('</form>')
        self.response.write('</body></html>')

app = webapp2.WSGIApplication([
    ('/', MainHandler)
    ], debug=True)
</code>```

答:
Solution for me was to add <input type="hidden" name="key" value="${filename}">.

```<code><form action="http://container-name.storage.googleapis.com" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="acl" value="public-read">
    <input type="hidden" name="Content-Type" value="application/pdf">
    <input type="hidden" name="key" value="${filename}">
    <input type="hidden" name="bucket" value="container-name">
    <input type="hidden" name="GoogleAccessId" value="XXXXXXXXX">
    <input type="hidden" name="policy" value="XXXXXXXXXXXXXXXXXXXXXXX=">
    <input type="hidden" name="signature" value="XXXXXX==">
    <input type="file" name="file" />
    <input type="submit" value="Upload">
<form>
</code>```

See Upload file using POST/PUT Object of Google Cloud Storage HTML Form.

Body:
Below is my code. I copied the interoperable access keys.. The client and secret both from the same page. I used client key in the ClientAccess ID in the form and secret for hashing.
But i get the error saying invalid argument.

Detail error being shown as "Cannot create buckets using a POST"

Below is the python code i used.

import webapp2
import cgi
import datetime
import urllib
import base64
import hmac, hashlib
import sha

policy_document = '''{"expiration": "2016-06-16T11:11:11Z",
                    "conditions": [
                        ["starts-with", "$key", "" ],
                        {"acl": "public-read" },
                    ]
                }'''

policy = base64.b64encode(policy_document).strip()
h = hmac.new('xxx', digestmod=sha.sha)
h.update(policy)
signature = base64.b64encode(h.digest())

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write('')
        self.response.write('<form action="http://storage.googleapis.com/www.xyz.com" method="post" enctype="multipart/form-data">')
        self.response.write('<input type="text" name="key" value="">')
        self.response.write('<input type="hidden" name="bucket" value="www.xyz.com">')
        #self.response.write('<input type="hidden" name="Content-Type" value="image/jpeg">')
        self.response.write('<input type="hidden" name="GoogleAccessId" value="GOOGxxxxx">')
        self.response.write('<input type="hidden" name="acl" value="public-read">')
        self.response.write('<input type="hidden" name="success_action_redirect" value="http://www.linklip.com/storage.html">')
        self.response.write('<input type="hidden" name="policy" value="%s">' % policy )
        self.response.write('<input type="hidden" name="signature" value="%s">' % signature )
        self.response.write('<input name="file" type="file">')
        self.response.write('<input type="submit" value="Upload">')
        self.response.write('</form>')
        self.response.write('')

app = webapp2.WSGIApplication([
    ('/', MainHandler)
    ], debug=True)

Body:
Solution for me was to add <input type="hidden" name="key" value="${filename}">.

<form action="http://container-name.storage.googleapis.com" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="acl" value="public-read">
    <input type="hidden" name="Content-Type" value="application/pdf">
    <input type="hidden" name="key" value="${filename}">
    <input type="hidden" name="bucket" value="container-name">
    <input type="hidden" name="GoogleAccessId" value="XXXXXXXXX">
    <input type="hidden" name="policy" value="XXXXXXXXXXXXXXXXXXXXXXX=">
    <input type="hidden" name="signature" value="XXXXXX==">
    <input type="file" name="file" />
    <input type="submit" value="Upload">
<form>

See Upload file using POST/PUT Object of Google Cloud Storage HTML Form.


来源: stackexchange

问:
Virtual memory used by a process in iOS?
I am retriving the virtual memory size like below :

```<code>-(void)virtualMemory{
   struct mach_task_basic_info info;
   mach_msg_type_number_t size = MACH_TASK_BASIC_INFO_COUNT;
   kern_return_t kerr = task_info(mach_task_self(),
                               MACH_TASK_BASIC_INFO,
                               (task_info_t)&info,
                               &size);
   if( kerr == KERN_SUCCESS ) {
       NSLog(@"Virtual Memory size (in bytes): %llu", info.virtual_size);
   } else {
       NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
   }

}
</code>```

Now this gives me Virtual Memory size as - 2784350208 which I am getting using a simulator. Is it possible to get virtual memory used by a specific process?

答:
You would need access to the task_for_pid() API.   That's generally verboten and requires an entitlement to use (see link).

While said entitlement might work in the simulator, I'm not sure it'd even work on your own device and it won't pass submission.

Getting task_for_pid() to work in El Capitan

ContentLicense: CC BY-SA 3.0

Body:
I am retriving the virtual memory size like below :

-(void)virtualMemory{
   struct mach_task_basic_info info;
   mach_msg_type_number_t size = MACH_TASK_BASIC_INFO_COUNT;
   kern_return_t kerr = task_info(mach_task_self(),
                               MACH_TASK_BASIC_INFO,
                               (task_info_t)&info,
                               &size);
   if( kerr == KERN_SUCCESS ) {
       NSLog(@"Virtual Memory size (in bytes): %llu", info.virtual_size);
   } else {
       NSLog(@"Error with task_info(): %s", mach_error_string(kerr));
   }

}

Now this gives me Virtual Memory size as - 2784350208 which I am getting using a simulator. Is it possible to get virtual memory used by a specific process?


问:
Is it legal to use memcpy with a destination structure with constant members?
For example, is the following function legal:

```<code>struct two_int {
  const int a, b;
}

void copy_two(const two_int *src, two_int *dest) {
  memcpy(dest, src, sizeof(two_int));
}
</code>```

It seems like at least some types of modifications of constant-defined values is not allowed, but it is not clear to me if this qualifies.

If the answer is "it is not allowed, in general", I'm also wondering about the special case where dest is newly allocated memory with malloc (and hence hasn't yet been assigned any value), such as:

```<code>two_int  s = {.a = 1, .b = 2};
two_int *d = malloc(sizeof(two_int));
copy_two(&s, d);
</code>```

Update: It seems like the latter question seems to answered in the affirmative (it's OK) for the case of a newly malloc'd structure, but the original, more general question still stands, I think.

答:
Use of memcpy for such purposes would have defined behavior only if the actual destination object does not have static or automatic duration.

Given the code:

```<code>struct foo { double const x; };
void outsideFunction(struct foo *p);

double test(void)
{
  struct foo s1 = {0.12345678};
  outsideFunction(&s1);
  return 0.12345678;
}
</code>```

a compiler would be entitled to optimize the function to:

```<code>double test(void)
{
  static struct foo const s1 = {0.12345678};
  outsideFunction(&s1);
  return s1.x;
}
</code>```

On many processors, the only way to load a double with an arbitrary constant is to load its value from object holding that constant, and in this case the compiler would conveniently know an object (s1.x) which must hold the constant 0.12345678.  The net effect would be that code which used memcpy to write to s1.x could corrupt other uses of the numeric constant 0.12345678.  As the saying goes, "variables won't; constants aren't".  Nasty stuff.

The problem would not exist for objects of allocated duration because memcpy requires a compiler to "forget" everything about what had previously been stored in the destination storage, including any "effective type".  The declared types of static and automatic objects exist independent of anything being stored into them, and cannot be erased by "memcpy" nor any other means, but allocated-duration objects only have an "effective type" which would get erased.

Body:
For example, is the following function legal:

struct two_int {
  const int a, b;
}

void copy_two(const two_int *src, two_int *dest) {
  memcpy(dest, src, sizeof(two_int));
}

It seems like at least some types of modifications of constant-defined values is not allowed, but it is not clear to me if this qualifies.

If the answer is "it is not allowed, in general", I'm also wondering about the special case where dest is newly allocated memory with malloc (and hence hasn't yet been assigned any value), such as:

two_int  s = {.a = 1, .b = 2};
two_int *d = malloc(sizeof(two_int));
copy_two(&s, d);

Update: It seems like the latter question seems to answered in the affirmative (it's OK) for the case of a newly malloc'd structure, but the original, more general question still stands, I think.

Body:
Use of memcpy for such purposes would have defined behavior only if the actual destination object does not have static or automatic duration.

Given the code:

struct foo { double const x; };
void outsideFunction(struct foo *p);

double test(void)
{
  struct foo s1 = {0.12345678};
  outsideFunction(&s1);
  return 0.12345678;
}

a compiler would be entitled to optimize the function to:

double test(void)
{
  static struct foo const s1 = {0.12345678};
  outsideFunction(&s1);
  return s1.x;
}

On many processors, the only way to load a double with an arbitrary constant is to load its value from object holding that constant, and in this case the compiler would conveniently know an object (s1.x) which must hold the constant 0.12345678.  The net effect would be that code which used memcpy to write to s1.x could corrupt other uses of the numeric constant 0.12345678.  As the saying goes, "variables won't; constants aren't".  Nasty stuff.

The problem would not exist for objects of allocated duration because memcpy requires a compiler to "forget" everything about what had previously been stored in the destination storage, including any "effective type".  The declared types of static and automatic objects exist independent of anything being stored into them, and cannot be erased by "memcpy" nor any other means, but allocated-duration objects only have an "effective type" which would get erased.


问:
Generating String from List in Erlang
I'm trying to generate a formatted string based on a list:

```<code>[{"Max", 18}, {"Peter", 25}]
</code>```

To a string:

```<code>"(Name: Max, Age: 18), (Name: Peter, Age: 35)"
</code>```

答:
If performance is important, you can use this solution:

```<code>format([]) -> [];
format(List) ->
  [[_|F]|R] = [ [", ","(Name: ",Name,", Age: ",integer_to_list(Age)|")"]
              || {Name, Age} <- List ],
  [F|R].
</code>```

But remember that it returns io_list() so if you want see result, use lists:flatten/1. It is way how to write very efficient string manipulations in Erlang but use it only if performance is far more important than readability and maintainability.

ContentLicense: CC BY-SA 2.5

Title: Generating String from List in Erlang

Body:
I'm trying to generate a formatted string based on a list:

[{"Max", 18}, {"Peter", 25}]

To a string:

"(Name: Max, Age: 18), (Name: Peter, Age: 35)"

Body:
If performance is important, you can use this solution:

format([]) -> [];
format(List) ->
  [[_|F]|R] = [ [", ","(Name: ",Name,", Age: ",integer_to_list(Age)|")"]
              || {Name, Age} <- List ],
  [F|R].

But remember that it returns io_list() so if you want see result, use lists:flatten/1. It is way how to write very efficient string manipulations in Erlang but use it only if performance is far more important than readability and maintainability.


问:
Google Cast SDK works only with Chromecast or can it work with any Smart TV?
I have a question about Google Cast sdk.

Does the sdk allows android phone to connect to any Smart TV (without built in Chromecast) OR it allows connection with Chromecast ONLY?

I have an app which plays video content (News, Sports etc) and i want that to be played on any Smart TV irrespective of the manufacturer. Can i do it with the cast sdk? If not, Is it possible? if yes, how?

答: Google Cast SDK only supports cast devices (that includes variations of chromecast, chromecast for audio, cast tvs, android tvs, some sound bars, etc). Smart TVs use their own framework and Google Cast SDK does not support them.</p>


问:
Create array with a normal distribution
I'm trying to create a vba array of size N, with normally distributed percentages that add 100%. This means that with an input of an integer number N, I should get as output a n-sized array with values that sum 100 and is normally distributed

How can I do this?

Thanks!!

答:
Try the below:

```<code>Sub NDArray()
a = InputBox("enter the integer")
ReDim arr(a - 1)
For i = 0 To a - 1
arr(i) = 100 / a
Next i
End Sub
</code>```

But I also agree with Scott... Try to write the code first and post your issues...

Title: Create array with a normal distribution

Body:
Try the below:

Sub NDArray()
a = InputBox("enter the integer")
ReDim arr(a - 1)
For i = 0 To a - 1
arr(i) = 100 / a
Next i
End Sub

But I also agree with Scott... Try to write the code first and post your issues...


问:
Is it possible to create a file in my S3 lambda function?
I am creating a java function for AWS Lambda that brings in a file from AWS S3 like this:

InputStream videoObjectStream = awsS3Video.getObjectContent();

I am also utilizing FFmpegFrameGrabber, which requires that I specify a file path whenever I create a new frameGrabber, i.e.: FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(filePath)

I am trying to convert the InputStream into a temporary file in my Lambda function, but it is not allowing me to create a file.  Here is my code to convert the videoObjectStream into a file:

```<code>byte[] inputBuffer = null;

        try {
            inputBuffer = IOUtils.toByteArray(videoObjectStream);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        System.out.println("The length of the byte array is " + inputBuffer.length);

        try {
            FileOutputStream videoOS = new FileOutputStream(videoDetails.get("videoFileKey"), false);
            videoOS.write(inputBuffer);
            videoOS.close();
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        File tempVideoFile = new File(videoDetails.get("videoFileKey"));

        if (tempVideoFile.exists()) {
            System.out.println("The file exists");
        } else {
            System.out.println("The file does not exist");
        }
</code>```

Then, I get the following stack trace, saying that this is a read-only file system:

```<code>java.io.FileNotFoundException: currentPath1490660005410.mp4 (Read-only file system)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:133)
    at com.amazonaws.lambda.LambdaFunctionHandler.convertVideo(LambdaFunctionHandler.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at lambdainternal.EventHandlerLoader$PojoMethodRequestHandler.handleRequest(EventHandlerLoader.java:456)
    at lambdainternal.EventHandlerLoader$PojoHandlerAsStreamHandler.handleRequest(EventHandlerLoader.java:375)
    at lambdainternal.EventHandlerLoader$2.call(EventHandlerLoader.java:1139)
    at lambdainternal.AWSLambda$2.call(AWSLambda.java:94)
    at lambdainternal.AWSLambda.startRuntime(AWSLambda.java:290)
    at lambdainternal.AWSLambda.<clinit>(AWSLambda.java:57)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at lambdainternal.LambdaRTEntry.main(LambdaRTEntry.java:94)
</code>```

Is there any way around this?  I need to manipulate the video data but cannot without making it into a file first.  Any suggestions are welcome. Thank you.

答: You have to create the file in /tmp. That's the only location you are allowed to write to in the Lambda environment.

Body:
I am creating a java function for AWS Lambda that brings in a file from AWS S3 like this:

InputStream videoObjectStream = awsS3Video.getObjectContent();

I am also utilizing FFmpegFrameGrabber, which requires that I specify a file path whenever I create a new frameGrabber, i.e.: FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(filePath)

I am trying to convert the InputStream into a temporary file in my Lambda function, but it is not allowing me to create a file.  Here is my code to convert the videoObjectStream into a file:

byte[] inputBuffer = null;

        try {
            inputBuffer = IOUtils.toByteArray(videoObjectStream);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        System.out.println("The length of the byte array is " + inputBuffer.length);

        try {
            FileOutputStream videoOS = new FileOutputStream(videoDetails.get("videoFileKey"), false);
            videoOS.write(inputBuffer);
            videoOS.close();
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        File tempVideoFile = new File(videoDetails.get("videoFileKey"));

        if (tempVideoFile.exists()) {
            System.out.println("The file exists");
        } else {
            System.out.println("The file does not exist");
        }

Then, I get the following stack trace, saying that this is a read-only file system:

java.io.FileNotFoundException: currentPath1490660005410.mp4 (Read-only file system)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:133)
    at com.amazonaws.lambda.LambdaFunctionHandler.convertVideo(LambdaFunctionHandler.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at lambdainternal.EventHandlerLoader$PojoMethodRequestHandler.handleRequest(EventHandlerLoader.java:456)
    at lambdainternal.EventHandlerLoader$PojoHandlerAsStreamHandler.handleRequest(EventHandlerLoader.java:375)
    at lambdainternal.EventHandlerLoader$2.call(EventHandlerLoader.java:1139)
    at lambdainternal.AWSLambda$2.call(AWSLambda.java:94)
    at lambdainternal.AWSLambda.startRuntime(AWSLambda.java:290)
    at lambdainternal.AWSLambda.<clinit>(AWSLambda.java:57)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at lambdainternal.LambdaRTEntry.main(LambdaRTEntry.java:94)

Is there any way around this?  I need to manipulate the video data but cannot without making it into a file first.  Any suggestions are welcome. Thank you.


问:
Activity componnent messed up when handling configuration Changes myself
I added this code in my activity

```<code>@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

        setContentView(R.layout.activityView);

}
</code>```

And also added this line in the Manifest file

```<code>android:configChanges="orientation|keyboardHidden|screenSize"
</code>```

The activity is not restarting, but the layout is not correctly loaded : not all componnent are showing and buttons click listner is never called ...

I'm using the same name file for all the layouts. but different content depending on orientation.

I even tried with different names : activityView_port/activityView_land and changed the code to:

```<code>@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.activityView_port);

    } else {
        setContentView(R.layout.activityView_land);
    }
}
</code>```

but nothing is working ...

any help would be appreciated :)

答:
```<code> setContentView(R.layout.activityView_land);
</code>```

please dont call above method on configuration change. instead you can try with use some flag for determine what layout has to be set and call reCreate() method.

```<code>If don't want to destroy the current instance, better you can try removing and adding of views with animation.
</code>```

Body:
I added this code in my activity

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

        setContentView(R.layout.activityView);

}

And also added this line in the Manifest file

android:configChanges="orientation|keyboardHidden|screenSize"

The activity is not restarting, but the layout is not correctly loaded : not all componnent are showing and buttons click listner is never called ...

I'm using the same name file for all the layouts. but different content depending on orientation.

I even tried with different names : activityView_port/activityView_land and changed the code to:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.activityView_port);

    } else {
        setContentView(R.layout.activityView_land);
    }
}

but nothing is working ...

any help would be appreciated :)

Body:
 setContentView(R.layout.activityView_land);

please dont call above method on configuration change. instead you can try with use some flag for determine what layout has to be set and call reCreate() method.

If don't want to destroy the current instance, better you can try removing and adding of views with animation.


问:
SQL data is returned as an array using Doctrine (and Silex)
I'm using doctrine to fetch data from my MySQL database. This is all done in Silex. These are the lines of code that enable Doctrine for me.

```<code>$config = new \Doctrine\DBAL\Configuration();
$connParams = array(
    'driver'   => 'pdo_mysql',
    'dbname'   => 'webshop',
    'host'     => 'localhost',
    'user'     => 'root',
    'password' => '',
    'charset'  => 'utf8'
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connParams, $config);
$app['dbcon'] = $conn;

$app->get('/', function () use ($app){

    $user = new User($app['dbcon']);

    return $app['twig']->render('home.twig', [
        'content' => 'Home',
    ]);

})->bind('home');
</code>```

And I'm trying to create a user class for login stuff etc. The user class looks like this:

```<code><?php

namespace Models;

class User
{
    private $db;

    public function __construct($db)
    {
        $this->db = $db;
        $query = $this->db->prepare("SELECT * FROM users");
        $query->execute();

        $query = $query->fetchAll();

        foreach($query as $user){
            print_r($user);
        }

    }
}
</code>```

Though, the following is the result:

Array ( [id] => 1 [username] => araguera [password] => password [salt] => ksjdfiwe98ru2w98h )

Why does it return as an array and not as an object? Because I want to be able to do something like "$query->username".

答:
To add to u_mulder's comment, you can use PDO style to fetch results as object:

```<code>$res = $query->fetchAll(\PDO::FETCH_OBJ);
</code>```

And in case you want to use fetch (to get one row) you can use:

```<code>$res = $query->fetchObject();
</code>```

Body:
I'm using doctrine to fetch data from my MySQL database. This is all done in Silex. These are the lines of code that enable Doctrine for me.

$config = new \Doctrine\DBAL\Configuration();
$connParams = array(
    'driver'   => 'pdo_mysql',
    'dbname'   => 'webshop',
    'host'     => 'localhost',
    'user'     => 'root',
    'password' => '',
    'charset'  => 'utf8'
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connParams, $config);
$app['dbcon'] = $conn;

$app->get('/', function () use ($app){

    $user = new User($app['dbcon']);

    return $app['twig']->render('home.twig', [
        'content' => 'Home',
    ]);

})->bind('home');

And I'm trying to create a user class for login stuff etc. The user class looks like this:

<?php

namespace Models;

class User
{
    private $db;

    public function __construct($db)
    {
        $this->db = $db;
        $query = $this->db->prepare("SELECT * FROM users");
        $query->execute();

        $query = $query->fetchAll();

        foreach($query as $user){
            print_r($user);
        }

    }
}

Though, the following is the result:

Array ( [id] => 1 [username] => araguera [password] => password [salt] => ksjdfiwe98ru2w98h )

Why does it return as an array and not as an object? Because I want to be able to do something like "$query->username".

Body:
To add to u_mulder's comment, you can use PDO style to fetch results as object:

$res = $query->fetchAll(\PDO::FETCH_OBJ);

And in case you want to use fetch (to get one row) you can use:

$res = $query->fetchObject();


问:
Trying to hook into Model 'updating' event with a trait
I'm trying to provide a way to track when a user makes a change to a model for a notes section in my application. E.g. John goes and modifies 2 fields, a note would be created saying John has changed title from 'My title 1' to 'My title 2' and content from 'Lipsum' to 'Lipsum2'.

Here is a trait I created:

```<code><?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait TrackChanges
{
    public $changes;

    public static function bootChangesTrait()
    {
        static::updating(function($model)
        {
            $this->changes = [];

            foreach($model->getDirty() as $key => $value)
            {
                $original = $model->getOriginal($key);

                 $this->changes[$key] = [
                    'old' => $original,
                    'new' => $value,
                ];
            }
        });
    }
}
</code>```

And I am using that trait successfully on my model. However, I'm not sure how to capture the contents of the changes, or if they are even working correctly.

In my controller I have:

```<code>$site = Site::findOrFail($id);

// Catch and cast the is_active checkbox if it's been unselected
if ( ! $request->exists('is_active') )
{
    $request->request->add([ 'is_active' => 0 ]);
}

// // Get rid of the CSRF field & method
$data = $request->except([ '_token', '_method' ]);

$site->update($data);
</code>```

I tried dd($site->changes) before and after $site->update($data); but it just returns null.

What am I doing wrong?

答:
You need to change your boot method in your trait to bootTrackChanges().  To boot traits you need to follow the naming pattern of boot{TraitName} for your boot method.  Then you need to change your $this calls in your trait to $model so the change get saved to the model so your trait should look like this:

```<code><?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait TrackChanges
{
    public $changes;

    public static function bootTrackChanges()
    {
        static::updating(function($model)
        {
            $changes = [];

            foreach($model->getDirty() as $key => $value)
            {
                $original = $model->getOriginal($key);

                 $changes[$key] = [
                    'old' => $original,
                    'new' => $value,
                ];
            }

            $model->changes = $changes;
        });
    }
}
</code>```

Another thing to note is if you have defined a boot method in your model make sure you call the parent boot method as well or else your trait's boot methods will not be called and your listener will not be registered..  I have spent hours and hours on this one before due to forgetting to call the parent method.  In your model defining a boot method is not required but if you did call the parent like:

```<code>class MyModel extends Model
{
    use TrackChanges;

    protected static function boot()
    {
        // Your boot logic here

        parent::boot();
    }
}
</code>```

Body:
I'm trying to provide a way to track when a user makes a change to a model for a notes section in my application. E.g. John goes and modifies 2 fields, a note would be created saying John has changed title from 'My title 1' to 'My title 2' and content from 'Lipsum' to 'Lipsum2'.

Here is a trait I created:

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait TrackChanges
{
    public $changes;

    public static function bootChangesTrait()
    {
        static::updating(function($model)
        {
            $this->changes = [];

            foreach($model->getDirty() as $key => $value)
            {
                $original = $model->getOriginal($key);

                 $this->changes[$key] = [
                    'old' => $original,
                    'new' => $value,
                ];
            }
        });
    }
}

And I am using that trait successfully on my model. However, I'm not sure how to capture the contents of the changes, or if they are even working correctly.

In my controller I have:

$site = Site::findOrFail($id);

// Catch and cast the is_active checkbox if it's been unselected
if ( ! $request->exists('is_active') )
{
    $request->request->add([ 'is_active' => 0 ]);
}

// // Get rid of the CSRF field & method
$data = $request->except([ '_token', '_method' ]);

$site->update($data);

I tried dd($site->changes) before and after $site->update($data); but it just returns null.

What am I doing wrong?

Body:
You need to change your boot method in your trait to bootTrackChanges().  To boot traits you need to follow the naming pattern of boot{TraitName} for your boot method.  Then you need to change your $this calls in your trait to $model so the change get saved to the model so your trait should look like this:

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;

trait TrackChanges
{
    public $changes;

    public static function bootTrackChanges()
    {
        static::updating(function($model)
        {
            $changes = [];

            foreach($model->getDirty() as $key => $value)
            {
                $original = $model->getOriginal($key);

                 $changes[$key] = [
                    'old' => $original,
                    'new' => $value,
                ];
            }

            $model->changes = $changes;
        });
    }
}

Another thing to note is if you have defined a boot method in your model make sure you call the parent boot method as well or else your trait's boot methods will not be called and your listener will not be registered..  I have spent hours and hours on this one before due to forgetting to call the parent method.  In your model defining a boot method is not required but if you did call the parent like:

class MyModel extends Model
{
    use TrackChanges;

    protected static function boot()
    {
        // Your boot logic here

        parent::boot();
    }
}


问:
Java dynamically changing components when scrollbar appears
I'm trying to implement a feature that (in my test project) once a button is pressed, it adds a random number to my JPanel. (I use the layouts I have because in my real program, I have more items inside and it displays correctly). But I need my program to recognize when the scrollbar is visible (which I implemented that, but it's a little delay. What I mean by delay is I push the button to add a number, if the scrollbar becomes visible nothing happens. But then the next time I press the button it shifts over like I want). The other problem I have (the one I'm focused on now) is that when I dynamically change the size of the JPanel, if the scrollbar is visible, I have it set to change the width to my width - the width of the scrollbar. But It seems like when the scrollbar is visible, the newly inputted number moves over twice the scrollbar width instead of just once. I've been at this part of my program for over a day and can't figure it out. I'll add my full code and some screenshots.

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
    JFrame frame;
    JPanel topPanel;
    JPanel memoryPanel;
    JScrollPane sPane;
    JButton button;
    ArrayList<Integer> list = new ArrayList<>();
    boolean isVScrollVisible = false;
    int scrollBarSize = 0;

    public class MyChangeListener implements ChangeListener {
        @Override
        public void stateChanged(ChangeEvent e) {
            isVScrollVisible = (sPane.getVerticalScrollBar().isVisible());
        }
    }

    public class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            Random random = new Random();
            int r = random.nextInt(10);

            list.add(r);

            int n;
            if (isVScrollVisible) {
                n = scrollBarSize;
            } else {
                n = 0;
            }

            JPanel nextPanel = new JPanel();
            nextPanel.setName("" + r);
            nextPanel.setForeground(Color.BLACK);
            nextPanel.setPreferredSize(new Dimension(200 - n, 55));
            nextPanel.setMinimumSize(new Dimension(200 - n, 55));
            nextPanel.setMaximumSize(new Dimension(200 - n, 55));

            JPanel labelPanel = new JPanel();
            labelPanel.setLayout(new BorderLayout());

            JLabel label = new JLabel();
            label.setText("" + r);
            label.setPreferredSize(new Dimension(200 - n, 55));
            label.setMinimumSize(new Dimension(200 - n, 55));
            label.setMaximumSize(new Dimension(200 - n, 55));
            label.setHorizontalAlignment(JLabel.RIGHT);
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 17));
            label.setFont(new Font("Sans-Serif", Font.BOLD, 20));
            labelPanel.add(label);

            nextPanel.add(labelPanel, BorderLayout.LINE_START);

            for (int i = 0; i < memoryPanel.getComponents().length; i++) {
                memoryPanel.getComponent(i).setPreferredSize(new Dimension(200 - n, 55));
                memoryPanel.getComponent(i).revalidate();
                memoryPanel.getComponent(i).repaint();
            }

            memoryPanel.add(nextPanel, 0);

            memoryPanel.revalidate();
            memoryPanel.repaint();
            sPane.revalidate();
            sPane.repaint();
        }
    }

    public Main() {
        frame = new JFrame();

        topPanel = new JPanel();
        memoryPanel = new JPanel();
        memoryPanel.setLayout(new BoxLayout(memoryPanel, BoxLayout.Y_AXIS));

        sPane = new JScrollPane(memoryPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        sPane.setPreferredSize(new Dimension(200, 300));
        sPane.getViewport().addChangeListener(new MyChangeListener());

        scrollBarSize = ((Integer)UIManager.get("ScrollBar.width")) + 1;

        button = new JButton("Add Random Number");
        button.addActionListener(new ButtonListener());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        topPanel.add(button);

        frame.add(topPanel, BorderLayout.PAGE_START);
        frame.add(sPane, BorderLayout.CENTER);

        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }
}
</code>```

I need them to look exactly the same. Before I had the code I have now, the scrollbar would appear over the numbers which looked ugly. And the reason I have the frame resizable false is because In my real program I hard coded all the sizes, which in the future I will calculate the correct sizes based on the size of the frame, so right now setting resizable to true is out of the question. Any suggestions on what to do?

This is what I'm trying to accompolish.

答:
Get rid of all the logic that sets the preferred/minimum/maximum sizes. Each component knows what its size should be. Each layout manager will in turn know what the preferred size of the panel should be. Let the layout manager use the information to do its job.

The basic logic for dynamically adding components is:

```<code>panel.add(...);
panel.revalidate();
panel.repaint();
</code>```

Then the scrollbars will appear automatically when required. There is no need for listeners or anything.

Edit:

The reason I set all the sizes is because If I take them out then everything appears centered

Learn how to use layout managers properly and effectively.

For example when using a BoxLayout you can control the alignment of components by using:

```<code>component.setAlignmentX(JLabel.RIGHT_ALIGNMENT);
</code>```

and the component will be aligned to the right edge of the space available to the component.

When using a JLabel you may also need to set a property on the JLabel to align the text to the right edge of the label. Read the JLabel API for the appropriate method.

Body:
I'm trying to implement a feature that (in my test project) once a button is pressed, it adds a random number to my JPanel. (I use the layouts I have because in my real program, I have more items inside and it displays correctly). But I need my program to recognize when the scrollbar is visible (which I implemented that, but it's a little delay. What I mean by delay is I push the button to add a number, if the scrollbar becomes visible nothing happens. But then the next time I press the button it shifts over like I want). The other problem I have (the one I'm focused on now) is that when I dynamically change the size of the JPanel, if the scrollbar is visible, I have it set to change the width to my width - the width of the scrollbar. But It seems like when the scrollbar is visible, the newly inputted number moves over twice the scrollbar width instead of just once. I've been at this part of my program for over a day and can't figure it out. I'll add my full code and some screenshots.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {
    JFrame frame;
    JPanel topPanel;
    JPanel memoryPanel;
    JScrollPane sPane;
    JButton button;
    ArrayList<Integer> list = new ArrayList<>();
    boolean isVScrollVisible = false;
    int scrollBarSize = 0;

    public class MyChangeListener implements ChangeListener {
        @Override
        public void stateChanged(ChangeEvent e) {
            isVScrollVisible = (sPane.getVerticalScrollBar().isVisible());
        }
    }

    public class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            Random random = new Random();
            int r = random.nextInt(10);

            list.add(r);

            int n;
            if (isVScrollVisible) {
                n = scrollBarSize;
            } else {
                n = 0;
            }

            JPanel nextPanel = new JPanel();
            nextPanel.setName("" + r);
            nextPanel.setForeground(Color.BLACK);
            nextPanel.setPreferredSize(new Dimension(200 - n, 55));
            nextPanel.setMinimumSize(new Dimension(200 - n, 55));
            nextPanel.setMaximumSize(new Dimension(200 - n, 55));

            JPanel labelPanel = new JPanel();
            labelPanel.setLayout(new BorderLayout());

            JLabel label = new JLabel();
            label.setText("" + r);
            label.setPreferredSize(new Dimension(200 - n, 55));
            label.setMinimumSize(new Dimension(200 - n, 55));
            label.setMaximumSize(new Dimension(200 - n, 55));
            label.setHorizontalAlignment(JLabel.RIGHT);
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 17));
            label.setFont(new Font("Sans-Serif", Font.BOLD, 20));
            labelPanel.add(label);

            nextPanel.add(labelPanel, BorderLayout.LINE_START);

            for (int i = 0; i < memoryPanel.getComponents().length; i++) {
                memoryPanel.getComponent(i).setPreferredSize(new Dimension(200 - n, 55));
                memoryPanel.getComponent(i).revalidate();
                memoryPanel.getComponent(i).repaint();
            }

            memoryPanel.add(nextPanel, 0);

            memoryPanel.revalidate();
            memoryPanel.repaint();
            sPane.revalidate();
            sPane.repaint();
        }
    }

    public Main() {
        frame = new JFrame();

        topPanel = new JPanel();
        memoryPanel = new JPanel();
        memoryPanel.setLayout(new BoxLayout(memoryPanel, BoxLayout.Y_AXIS));

        sPane = new JScrollPane(memoryPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        sPane.setPreferredSize(new Dimension(200, 300));
        sPane.getViewport().addChangeListener(new MyChangeListener());

        scrollBarSize = ((Integer)UIManager.get("ScrollBar.width")) + 1;

        button = new JButton("Add Random Number");
        button.addActionListener(new ButtonListener());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        topPanel.add(button);

        frame.add(topPanel, BorderLayout.PAGE_START);
        frame.add(sPane, BorderLayout.CENTER);

        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }
}

I need them to look exactly the same. Before I had the code I have now, the scrollbar would appear over the numbers which looked ugly. And the reason I have the frame resizable false is because In my real program I hard coded all the sizes, which in the future I will calculate the correct sizes based on the size of the frame, so right now setting resizable to true is out of the question. Any suggestions on what to do?

This is what I'm trying to accompolish.

Body:
Get rid of all the logic that sets the preferred/minimum/maximum sizes. Each component knows what its size should be. Each layout manager will in turn know what the preferred size of the panel should be. Let the layout manager use the information to do its job.

The basic logic for dynamically adding components is:

panel.add(...);
panel.revalidate();
panel.repaint();

Then the scrollbars will appear automatically when required. There is no need for listeners or anything.

Edit:

The reason I set all the sizes is because If I take them out then everything appears centered

Learn how to use layout managers properly and effectively.

For example when using a BoxLayout you can control the alignment of components by using:

component.setAlignmentX(JLabel.RIGHT_ALIGNMENT);

and the component will be aligned to the right edge of the space available to the component.

When using a JLabel you may also need to set a property on the JLabel to align the text to the right edge of the label. Read the JLabel API for the appropriate method.


问:
search in a range of latitude and longitude from text file on server in iOS app
I am trying to search in a text file (available on a url) , there is latitude, longitude and other information separated by commas.
I need to search lat lon which is nearest to user's selected lat lon in app.
Code is done to read that file and search but it do not work perfectly.
Please let me know , how should I approach in this type of situation.
1)File get updated in real time , so I need to call url and read file every time user select location and click to get information.
2)And then search for nearest lat lon to the user's selected lat lon.

NSDICTIONARY DATA GETTING :-

```<code>(
    {
    "altitude_m" = "90.0";
    engName = “Station 1”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.058873";
    "local_time" = "16:20";
    lon = "23.976741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
{
    "altitude_m" = "90.0";
    engName = “Station 2”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.048873";
    "local_time" = "16:20";
    lon = "23.876741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
{
    "altitude_m" = "90.0";
    engName = “Station 3”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.059873";
    "local_time" = "16:20";
    lon = "23.986741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
</code>```

// MATCHING FUNCTION :-

```<code>-(void)matchLAtLongNow: (NSString *)latitude :(NSString *)longitude {

CLLocationCoordinate2D pinlocation;

pinlocation.latitude   = [latitude doubleValue];

pinlocation.longitude  = [longitude doubleValue];

float minLat = pinlocation.latitude - (searchDistance / 69);

float maxLat = pinlocation.latitude + (searchDistance / 69);

float minLon = pinlocation.longitude - searchDistance / fabs(cos(deg2rad(pinlocation.latitude))*69);
float maxLon = pinlocation.longitude + searchDistance / fabs(cos(deg2rad(pinlocation.longitude))*69);

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"lat <= %f AND lat >= %f AND lon <= %f AND lon >= %f",
                          maxLat, minLat, maxLon, minLon];

MatchedTxtArray = [myArray filteredArrayUsingPredicate:applePred];

}
</code>```

//GETTING ERROR
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber _fastCStringContents]: unrecognized selector sent to instance 0x175426460'
* First throw call stack:

答: NSDictionaries return NSNumbers. Check where you call matchAtLongNow: You probably have NSNumbers where you're expecting strings. </p>

Body:
I am trying to search in a text file (available on a url) , there is latitude, longitude and other information separated by commas.
I need to search lat lon which is nearest to user's selected lat lon in app.
Code is done to read that file and search but it do not work perfectly.
Please let me know , how should I approach in this type of situation.
1)File get updated in real time , so I need to call url and read file every time user select location and click to get information.
2)And then search for nearest lat lon to the user's selected lat lon.

NSDICTIONARY DATA GETTING :-

(
    {
    "altitude_m" = "90.0";
    engName = “Station 1”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.058873";
    "local_time" = "16:20";
    lon = "23.976741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
{
    "altitude_m" = "90.0";
    engName = “Station 2”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.048873";
    "local_time" = "16:20";
    lon = "23.876741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}
{
    "altitude_m" = "90.0";
    engName = “Station 3”;
    grkName = "\U039d\U03ad\U03b1 \U039c\U03ac\U03ba\U03c1\U03b7 \U0391\U03c4\U03c4\U03b9\U03ba\U03ae\U03c2";
    "humidity_P" = "50.0";
    lat = "38.059873";
    "local_time" = "16:20";
    lon = "23.986741";
    "pressure_hPA" = "1019.9";
    "rain_mm" = "0.0";
    "tem_C" = "17.2";
    "wind_Gusts_khm" = "51.5";
    "wind_degrees" = "22.5";
    "wind_kmh" = "25.7";
}

// MATCHING FUNCTION :-

-(void)matchLAtLongNow: (NSString *)latitude :(NSString *)longitude {

CLLocationCoordinate2D pinlocation;

pinlocation.latitude   = [latitude doubleValue];

pinlocation.longitude  = [longitude doubleValue];

float minLat = pinlocation.latitude - (searchDistance / 69);

float maxLat = pinlocation.latitude + (searchDistance / 69);

float minLon = pinlocation.longitude - searchDistance / fabs(cos(deg2rad(pinlocation.latitude))*69);
float maxLon = pinlocation.longitude + searchDistance / fabs(cos(deg2rad(pinlocation.longitude))*69);

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"lat <= %f AND lat >= %f AND lon <= %f AND lon >= %f",
                          maxLat, minLat, maxLon, minLon];

MatchedTxtArray = [myArray filteredArrayUsingPredicate:applePred];

}

//GETTING ERROR
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber _fastCStringContents]: unrecognized selector sent to instance 0x175426460'
* First throw call stack:


问:
ng-repeat not tracking old key-pair value
I've json like this..

```<code>var storedData = {
 "Feb 7, 2017":[
   {
     "emMessageId":1019,
     "message":"HI",
     "userId":100166,
     "imHashTagId":null,
     "taggedUser":null,
     "iconPath":"i",
     "sendMsgDate":1486469494000
   },
   {....}
 ],
"Feb 8, 2017":[
  {
     "emMessageId":1090,
     "message":"hi",
     "userId":100165,
     "imHashTagId":null,
     "taggedUser":null,
     "iconPath":"i",
     "sendMsgDate":1486495671000
  },
  {....}
 ]
}
</code>```

now i'm adding more data to "today" key like..

```<code> if(!storedData['Today'])
   storedData['Today'] = [{new obj}]
 else
    storedData['Today'].push({new obj});
</code>```

It's adding fine but "ng-repeat" not tracking old key-pairs value.Please help me Expert's, Thanks in advance.

Plunker Demo: https://plnkr.co/edit/YHQhC0Qibbrr5fD73fGr?p=info

答:
The issue here was that ng-repeat, when adding a new item to self.storedData['Today'], is processing just that last added item.

Here is the plunker link that does what you want. Basically I have added a temporary array self.todayItems and when Send button is clicked, just do self.storedData['Today'] = angular.copy(self.todayItems);, which creates a copy of the entire array. Since a new array is added, all items in that array are re-evaluated.

Body:
I've json like this..

var storedData = {
 "Feb 7, 2017":[
   {
     "emMessageId":1019,
     "message":"HI",
     "userId":100166,
     "imHashTagId":null,
     "taggedUser":null,
     "iconPath":"i",
     "sendMsgDate":1486469494000
   },
   {....}
 ],
"Feb 8, 2017":[
  {
     "emMessageId":1090,
     "message":"hi",
     "userId":100165,
     "imHashTagId":null,
     "taggedUser":null,
     "iconPath":"i",
     "sendMsgDate":1486495671000
  },
  {....}
 ]
}

now i'm adding more data to "today" key like..

 if(!storedData['Today'])
   storedData['Today'] = [{new obj}]
 else
    storedData['Today'].push({new obj});

It's adding fine but "ng-repeat" not tracking old key-pairs value.Please help me Expert's, Thanks in advance.

Plunker Demo: https://plnkr.co/edit/YHQhC0Qibbrr5fD73fGr?p=info


问:
SqlException: Deadlock
I have these two exceptions generated when I try to get data from SQL database in C#:

System.Data.SqlClient.SqlException:  Transaction (Process ID 97) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

OR

System.Data.SqlClient.SqlException: Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

OR

System.Data.SqlClient.SqlException: Transaction (Process ID 54) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

this is the code:

```<code> using (SqlConnection con = new SqlConnection(datasource))
 {
    SqlCommand cmd = new SqlCommand("Select * from MyTable Where ID='1' ", con);
    cmd.CommandTimeout = 300;
    con.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adapter.Fill(ds);
    con.Close();
    return ds.Tables[0];
 }
</code>```

These happened every time.

Any ideas on how these can be resolved?

答:
There are a couple of things you can do to lessen the number of deadlocks you receive, and some things you can do to completely eliminate them.

First off, launch SQL Server Profiler and tell it to give you a deadlock graph.  Running this trace will tell you the other query which is conflicting with yours.  Your query is quite simple, though I seriously doubt you have a SELECT * query off a table called MyTable in your system...

Anyway, armed with the deadlock graph and the other query, you should be able to tell what resources are deadlocking.  The classic solution is to change the order of both queries such that the resources are accessed in the same order -- this avoids cycles.

Other things you can do:

Speed up your queries by, among other things, applying the correct indexes to them.

Enable snapshot isolation on the database and use SET TRANSACTION ISOLATION LEVEL SNAPSHOT in your transactions where appropriate.  Also enable read committed with row-versioning.  In many cases, this is enough to eliminate most deadlocks completely.  Read about transaction isolation levels.  Understand what you're doing.

ContentLicense: CC BY-SA 4.0

Title: SqlException: Deadlock

Body:
I have these two exceptions generated when I try to get data from SQL database in C#:

System.Data.SqlClient.SqlException:  Transaction (Process ID 97) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

OR

System.Data.SqlClient.SqlException: Transaction (Process ID 62) was deadlocked on lock resources with another process and has been chosen as the deadlock victim.

OR

System.Data.SqlClient.SqlException: Transaction (Process ID 54) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

this is the code:

 using (SqlConnection con = new SqlConnection(datasource))
 {
    SqlCommand cmd = new SqlCommand("Select * from MyTable Where ID='1' ", con);
    cmd.CommandTimeout = 300;
    con.Open();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adapter.Fill(ds);
    con.Close();
    return ds.Tables[0];
 }

These happened every time.

Any ideas on how these can be resolved?


问:
SQL: Only Group to only display 1 Membership Level
```<code>select
u.Resnet_Agent_ID,
u.First_Name + ' ' + u.Last_Name AS [Agent Name],
u.Email,
[Current Membership Level] = CASE
 WHEN u.UserMembershiptType_CodeID = 1 THEN 'Standard'
 WHEN u.UserMembershiptType_CodeID = 2 THEN 'Premium Membership'
 WHEN u.UserMembershiptType_CodeID = 3 THEN 'Pro Plus Membership'
 WHEN u.UserMembershiptType_CodeID = 4 THEN 'Pro Plus Trial'
 WHEN u.UserMembershiptType_CodeID = 5 THEN 'Premium Free Trial'
 WHEN u.UserMembershiptType_CodeID = 6 THEN 'Pro'
 WHEN u.UserMembershiptType_CodeID = 7 THEN 'Pro Plus Comp - Trial'
 ELSE NULL END,
[Prior Paid Membership Level] = CASE
 WHEN mh.MembershipType_CodeID = 2 THEN 'Premium Membership'
 WHEN mh.MembershipType_CodeID = 3 THEN 'Pro Plus Membership'
 WHEN mh.MembershipType_CodeID = 4 THEN 'Pro Plus Trial'
 WHEN mh.MembershipType_CodeID = 5 THEN 'Premium Free Trial'
 WHEN mh.MembershipType_CodeID = 6 THEN 'Pro'
 WHEN mh.MembershipType_CodeID = 7 THEN 'Pro Plus Comp - Trial'
 ELSE NULL END, mh.Description
  from amp.dbo.tbl_User u (nolock)
join amp.dbo.tbl_MembershipHistoryNew mh (nolock)
    on u.UniversalUserId = mh.AgentUniversalUserId
where u.IsAgent = 1 and mh.MembershipType_CodeID <> 1
</code>```

How can  I group the Current Membership Level to only display  "one current membership level, only one Resnet_Agent_ID, only one Agent Name, only one Email" ?

答:
One option is using cross apply() to get the latest row based on some column, e.g. ExpirationDate:

```<code>select
    u.Resnet_Agent_id
  , [Agent Name]= u.First_Name + ' ' + u.Last_Name
  , u.Email
  , [Current Membership Level] = case
     when u.UserMembershiptType_Codeid = 1 then 'Standard'
     when u.UserMembershiptType_Codeid = 2 then 'Premium Membership'
     when u.UserMembershiptType_Codeid = 3 then 'Pro Plus Membership'
     when u.UserMembershiptType_Codeid = 4 then 'Pro Plus Trial'
     when u.UserMembershiptType_Codeid = 5 then 'Premium Free Trial'
     when u.UserMembershiptType_Codeid = 6 then 'Pro'
     when u.UserMembershiptType_Codeid = 7 then 'Pro Plus Comp - Trial'
    else null end
  , [Prior Paid Membership Level] = case
     when mh.MembershipType_Codeid = 2 then 'Premium Membership'
     when mh.MembershipType_Codeid = 3 then 'Pro Plus Membership'
     when mh.MembershipType_Codeid = 4 then 'Pro Plus Trial'
     when mh.MembershipType_Codeid = 5 then 'Premium Free Trial'
     when mh.MembershipType_Codeid = 6 then 'Pro'
     when mh.MembershipType_Codeid = 7 then 'Pro Plus Comp - Trial'
     else null end
  , mh.Description
from amp.dbo.tbl_User u (nolock)
  cross apply (
    select top 1
        MembershipType_Codeid
      , Description
    from amp.dbo.tbl_MembershipHistoryNew i (nolock)
    where u.UniversalUserId = i.AgentUniversalUserId
    order by i.ExpirationDate desc /* order by to get the latest first here */
    ) mh
where u.IsAgent = 1
  and mh.MembershipType_Codeid <> 1
</code>```

Body:
select
u.Resnet_Agent_ID,
u.First_Name + ' ' + u.Last_Name AS [Agent Name],
u.Email,
[Current Membership Level] = CASE
 WHEN u.UserMembershiptType_CodeID = 1 THEN 'Standard'
 WHEN u.UserMembershiptType_CodeID = 2 THEN 'Premium Membership'
 WHEN u.UserMembershiptType_CodeID = 3 THEN 'Pro Plus Membership'
 WHEN u.UserMembershiptType_CodeID = 4 THEN 'Pro Plus Trial'
 WHEN u.UserMembershiptType_CodeID = 5 THEN 'Premium Free Trial'
 WHEN u.UserMembershiptType_CodeID = 6 THEN 'Pro'
 WHEN u.UserMembershiptType_CodeID = 7 THEN 'Pro Plus Comp - Trial'
 ELSE NULL END,
[Prior Paid Membership Level] = CASE
 WHEN mh.MembershipType_CodeID = 2 THEN 'Premium Membership'
 WHEN mh.MembershipType_CodeID = 3 THEN 'Pro Plus Membership'
 WHEN mh.MembershipType_CodeID = 4 THEN 'Pro Plus Trial'
 WHEN mh.MembershipType_CodeID = 5 THEN 'Premium Free Trial'
 WHEN mh.MembershipType_CodeID = 6 THEN 'Pro'
 WHEN mh.MembershipType_CodeID = 7 THEN 'Pro Plus Comp - Trial'
 ELSE NULL END, mh.Description
  from amp.dbo.tbl_User u (nolock)
join amp.dbo.tbl_MembershipHistoryNew mh (nolock)
    on u.UniversalUserId = mh.AgentUniversalUserId
where u.IsAgent = 1 and mh.MembershipType_CodeID <> 1

How can  I group the Current Membership Level to only display  "one current membership level, only one Resnet_Agent_ID, only one Agent Name, only one Email" ?

Body:
One option is using cross apply() to get the latest row based on some column, e.g. ExpirationDate:

select
    u.Resnet_Agent_id
  , [Agent Name]= u.First_Name + ' ' + u.Last_Name
  , u.Email
  , [Current Membership Level] = case
     when u.UserMembershiptType_Codeid = 1 then 'Standard'
     when u.UserMembershiptType_Codeid = 2 then 'Premium Membership'
     when u.UserMembershiptType_Codeid = 3 then 'Pro Plus Membership'
     when u.UserMembershiptType_Codeid = 4 then 'Pro Plus Trial'
     when u.UserMembershiptType_Codeid = 5 then 'Premium Free Trial'
     when u.UserMembershiptType_Codeid = 6 then 'Pro'
     when u.UserMembershiptType_Codeid = 7 then 'Pro Plus Comp - Trial'
    else null end
  , [Prior Paid Membership Level] = case
     when mh.MembershipType_Codeid = 2 then 'Premium Membership'
     when mh.MembershipType_Codeid = 3 then 'Pro Plus Membership'
     when mh.MembershipType_Codeid = 4 then 'Pro Plus Trial'
     when mh.MembershipType_Codeid = 5 then 'Premium Free Trial'
     when mh.MembershipType_Codeid = 6 then 'Pro'
     when mh.MembershipType_Codeid = 7 then 'Pro Plus Comp - Trial'
     else null end
  , mh.Description
from amp.dbo.tbl_User u (nolock)
  cross apply (
    select top 1
        MembershipType_Codeid
      , Description
    from amp.dbo.tbl_MembershipHistoryNew i (nolock)
    where u.UniversalUserId = i.AgentUniversalUserId
    order by i.ExpirationDate desc /* order by to get the latest first here */
    ) mh
where u.IsAgent = 1
  and mh.MembershipType_Codeid <> 1


问:
Delete Action methods of Web API did not get trigger
I have a web api controller in my project, as follows

```<code>public class EmployeeController : ApiController
{
    static readonly IEmployeeRepository repository = new EmployeeRepository();
    // GET api/<controller>
    [HttpGet]
    public object Get()
    {
        var queryString = HttpContext.Current.Request.QueryString;
        var data = repository.GetAll().ToList();
        return new { Items = data, Count = data.Count() };
    }

    public Employee GetEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return emp;
    }

    // POST api/<controller>
    public HttpResponseMessage PostEmployee(Employee emp)
    {
        emp = repository.Add(emp);
        var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

        string uri = Url.Link("Employee", new { id = emp.EmployeeID });
        response.Headers.Location = new Uri(uri);
        return response;
    }
     [HttpPut]
    // PUT api/<controller>
    public void PutEmployee(Employee emp)
    {

        if (!repository.Update(emp))
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

    }
    [HttpDelete]
     public void DeleteEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        repository.Remove(id);
    }
}
</code>```

For me, get and post method getting triggered correctly

But, Delete Method is not getting triggered.

and my Webapicongif.cs

```<code>    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "Employee",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        //config.EnableQuerySupport();
    }
</code>```

and the global.cs file as follows

```<code>    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        GlobalConfiguration.Configure(WebApiConfig.Register);

        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

    }
</code>```

once i did the delete to the Employee

```<code>General:

Request URL:http://localhost:63187/api/Employee/2
Request Method:DELETE
Status Code:404 Not Found
Remote Address:[::1]:63187
</code>```

Response Headers

```<code>   Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Cache-Control:no-cache
Content-Length:204
Content-Type:application/json; charset=utf-8
Date:Thu, 30 Mar 2017 12:00:21 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpcU2FtcGxlXE1WQ1xEYXRhTWFuYWdlclxBZGFwdG9yc1xTYW1wbGVcYXBpXEVtcGxveWVlXDI=?=
</code>```

Request Headers

```<code>Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:1
Content-Type:application/json; charset=UTF-8
DataServiceVersion:2.0
Host:localhost:63187
MaxDataServiceVersion:2.0
Origin:http://localhost:63187
Referer:http://localhost:63187/CRUDRemote/Remove
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-Requested-With:XMLHttpRequest
</code>```

Request Payload

```<code>2
</code>```

my ajax request will as below

```<code>beforeSend:function (),
contentType:"application/json; charset=utf-8",
data:"2",
error:function (e),
success:function (),
type:"DELETE",
url:"/api/Employee/2",
</code>```

Where i committing my mistake

答:
In the new WebAPI project hosted under IIS, PUT and DELETE methods return 404 errors out of the box. applicationhost.config of IIS has to be edited before you use them.

%userprofile%\documents\iisexpress\config\applicationhost.config

Search for

```<code><add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</code>```

and replace it by

```<code><add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</code>```

and in addition to this as this stackoverflow answer suggests, you have to comment out the following lines in the same file.

```<code><add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />
<add name="WebDAVModule" />
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />
</code>```

Body:
I have a web api controller in my project, as follows

public class EmployeeController : ApiController
{
    static readonly IEmployeeRepository repository = new EmployeeRepository();
    // GET api/<controller>
    [HttpGet]
    public object Get()
    {
        var queryString = HttpContext.Current.Request.QueryString;
        var data = repository.GetAll().ToList();
        return new { Items = data, Count = data.Count() };
    }

    public Employee GetEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return emp;
    }

    // POST api/<controller>
    public HttpResponseMessage PostEmployee(Employee emp)
    {
        emp = repository.Add(emp);
        var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

        string uri = Url.Link("Employee", new { id = emp.EmployeeID });
        response.Headers.Location = new Uri(uri);
        return response;
    }
     [HttpPut]
    // PUT api/<controller>
    public void PutEmployee(Employee emp)
    {

        if (!repository.Update(emp))
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

    }
    [HttpDelete]
     public void DeleteEmployee(int id)
    {
        Employee emp = repository.Get(id);
        if (emp == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

        repository.Remove(id);
    }
}

For me, get and post method getting triggered correctly

But, Delete Method is not getting triggered.

and my Webapicongif.cs

    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "Employee",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        //config.EnableQuerySupport();
    }

and the global.cs file as follows

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        GlobalConfiguration.Configure(WebApiConfig.Register);

        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

    }

once i did the delete to the Employee

General:

Request URL:http://localhost:63187/api/Employee/2
Request Method:DELETE
Status Code:404 Not Found
Remote Address:[::1]:63187

Response Headers

   Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Cache-Control:no-cache
Content-Length:204
Content-Type:application/json; charset=utf-8
Date:Thu, 30 Mar 2017 12:00:21 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpcU2FtcGxlXE1WQ1xEYXRhTWFuYWdlclxBZGFwdG9yc1xTYW1wbGVcYXBpXEVtcGxveWVlXDI=?=

Request Headers

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:1
Content-Type:application/json; charset=UTF-8
DataServiceVersion:2.0
Host:localhost:63187
MaxDataServiceVersion:2.0
Origin:http://localhost:63187
Referer:http://localhost:63187/CRUDRemote/Remove
User-Agent:Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload

2

my ajax request will as below

beforeSend:function (),
contentType:"application/json; charset=utf-8",
data:"2",
error:function (e),
success:function (),
type:"DELETE",
url:"/api/Employee/2",

Where i committing my mistake

Body:
In the new WebAPI project hosted under IIS, PUT and DELETE methods return 404 errors out of the box. applicationhost.config of IIS has to be edited before you use them.

%userprofile%\documents\iisexpress\config\applicationhost.config

Search for

<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

and replace it by

<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

and in addition to this as this stackoverflow answer suggests, you have to comment out the following lines in the same file.

<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />
<add name="WebDAVModule" />
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />


问:
How to Encrypt Files For Modelsim with Vivado
A vendor is using a tool which compiles some code into raw VHDL. They do not wish for me to see the raw code and instead want to encrypt the output files. At the moment they encrypt it into EDIF netlists using Vivado.

This is fine when implementing the design; I take it as a black box, use the wrapper for the i/o and write the bitstream. They ensure me their black box design works. I indeed see my resource usage going up to what I expect however I would like to simulate and verify their results.

When trying to simulate it with modelsim, it of course has no idea how to decrypt these files. If you write the netlists to VHDL, you just get the error:

```<code># ** Error: Formatter.vhd(58329): near "AES128-CBC": Unknown session key in protected region
</code>```

I asked them to include the encryption key for modelsim when encrypting these files, but they did not know how to.

I understand their rough workflow with their .tcl is:

```<code>synth_design -top Formatter
write_edif -force ./Formatteredf
</code>```

So my question is, how do they include the modelsim encryption key when they generate the EDIF files with Vivado?

答:
If the EDIF is encrypted, write_vhdl will almost certainly produce another encrypted netlist. That VHDL netlist might simulate in Modelsim, but I would guess not.

Modelsim comes with a tool "vhencrypt.exe" which will encrypt the source using IEEE 1735. The resulting file can be simulated by Modelsim, but you have to start with the source, not the EDIF. You would now have the problem of using the EDIF in Vivado and the vhencrypt output in Modelsim, but it's a step in the right direction.

IEEE 1735 can produce a single output that can be consumed by both Vivado and Modelsim, but you will need to provide a public key from Xilinx. As far as I know, Xilinx does not publish their public key for 1735, but they would probably share it with an IP partner.

Body:
A vendor is using a tool which compiles some code into raw VHDL. They do not wish for me to see the raw code and instead want to encrypt the output files. At the moment they encrypt it into EDIF netlists using Vivado.

This is fine when implementing the design; I take it as a black box, use the wrapper for the i/o and write the bitstream. They ensure me their black box design works. I indeed see my resource usage going up to what I expect however I would like to simulate and verify their results.

When trying to simulate it with modelsim, it of course has no idea how to decrypt these files. If you write the netlists to VHDL, you just get the error:

# ** Error: Formatter.vhd(58329): near "AES128-CBC": Unknown session key in protected region

I asked them to include the encryption key for modelsim when encrypting these files, but they did not know how to.

I understand their rough workflow with their .tcl is:

synth_design -top Formatter
write_edif -force ./Formatteredf

So my question is, how do they include the modelsim encryption key when they generate the EDIF files with Vivado?


问:
JBOSS 5 Auto deployment of mbeans In JMX server-ISSUE using HTTP url
In JBoss 4.x i used to deploy *.sar files via JMX server  .I use server.invoke(new ObjectName("jboss.system:service=MainDeployer"),"deploy",new Object[]{"http://"+hostname+":"+port+"/resources/jbossexample.sar"},new String[]{"java.lang.String"});

The *.sar is present in a remote location.So i used http:\.

This used to be suceessfull.In JBoss 5.x i m not able to do this .It throws up following exception.Is there any new process to be followed  in my side.Is this JBoss bug fixed in other versions?Kindly  give your suggestions.

java.io.IOException: No context factory for http://192.168.112.103:9090/resource
s/jbossagent.sar
        at org.jboss.virtual.VFS.getVFS(VFS.java:196)
        at org.jboss.virtual.VFS.getRoot(VFS.java:212)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:815)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:790)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatch
er.java:157)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.
java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.jmx.connector.invoker.InvokerAdaptorService.invoke(InvokerA
daptorService.java:270)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatch
er.java:157)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
        at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractIntercept
or.java:138)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:90)
        at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelM
BeanOperationInterceptor.java:140)
        at org.jboss.jmx.connector.invoker.SerializableInterceptor.invoke(Serial
izableInterceptor.java:74)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:90)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.
java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
        at org.jboss.invocation.jrmp.server.JRMPProxyFactory.invoke(JRMPProxyFac
tory.java:180)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatch
er.java:157)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:96)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.
java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668)
        at org.jboss.invocation.jrmp.server.JRMPInvoker$MBeanServerAction.invoke
(JRMPInvoker.java:855)
        at org.jboss.invocation.jrmp.server.JRMPInvoker.invoke(JRMPInvoker.java:
422)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:305)
        at sun.rmi.transport.Transport$1.run(Transport.java:159)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:5
35)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTranspor
t.java:790)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport
.java:649)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec
utor.java:885)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:907)
        at java.lang.Thread.run(Thread.java:619)

答:
It's broken in JBoss 5 and fixed in JBoss 6.0.0.CR1

https://jira.jboss.org/browse/JBAS-8319?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel


问:
Linux recursively replace periods for all directorys and all but last period for files with underscores
I have the following command which recursively renames all the files/directory's to lowercase and replaces spaces with _.

```<code>find . -iname "*" |  rename 'y/A-Z/a-z/; s/ /_/g;'
</code>```

How do I extend it to remove all periods from directories and leave just the last period for files?

So input would be:
this.is.a.directory
this.is.a.file.txt

Output
this_is_a_directory
this_is_a_file.txt

答:
You can do this using find in a while loop and using a regex to leave last DOT for files:

```<code>while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename 'y/A-Z/a-z/; s/ /_/g; s/\./_/g' "$entry"
   else
      rename 'y/A-Z/a-z/; s/ /_/g; s/\.(?=.*\.)/_/g' "$entry"
   fi
done < <(find . -iname '*' -print0)
</code>```

s/\.(?=.*\.)/_/g will only replace a DOT if there is another DOT ahead in the input.

Body:
I have the following command which recursively renames all the files/directory's to lowercase and replaces spaces with _.

find . -iname "*" |  rename 'y/A-Z/a-z/; s/ /_/g;'

How do I extend it to remove all periods from directories and leave just the last period for files?

So input would be:
this.is.a.directory
this.is.a.file.txt

Output
this_is_a_directory
this_is_a_file.txt

Body:
You can do this using find in a while loop and using a regex to leave last DOT for files:

while IFS= read -rd '' entry; do
   entry="${entry#./}"         # strip ./
   if [[ -d $entry ]]; then
      rename 'y/A-Z/a-z/; s/ /_/g; s/\./_/g' "$entry"
   else
      rename 'y/A-Z/a-z/; s/ /_/g; s/\.(?=.*\.)/_/g' "$entry"
   fi
done < <(find . -iname '*' -print0)

s/\.(?=.*\.)/_/g will only replace a DOT if there is another DOT ahead in the input.


问:
New TFS 2015 Web based build definition is not cleaning artifact from previous build even after specify clean
Building a solution with new web based build definition. passing MSBuild arguments during the build. checked clean options. but TFS is not removing old build artifacts from previous build, instead of removing an artifacts, it's giving just appending new one with old one.

using MS Build arguments:  /p:DeployOnBuild=true /P:PackageTempRootDir=\Release /p:DeployIisAppPath="Default Web Site";DefaultPackageFileName=DemoApp.zip /p:OutputPath="$(Build.BinariesDirectory)\$(BuildPlatform)\$(BuildConfiguration)"

I tried by changing the name of DefaultPackageFileName with something else like (TestApp.zip)

if I see in my output folder. I am getting both zip file created instead of one. what can be issue?

答:
Found it. Looks like in some cases, we need to pass variable Build.Clean with Value binary. found it from https://www.visualstudio.com/en-us/docs/build/define/repository
Thanks for response.


问:
Apache Camel: How to use a Property placeholder to enable or disable a route?
I am new to Apache Camel, and have a problem statement in hand. I want to build a code where I can refer to the flags in the camel properties and allow a route to be enabled/disabled based on the flags availability in the properties file.
How do I proceed with it?</p>

答:
You can use the .autoStartup("{{propertyName}}") function from the Java DSL. For example:

```<code>from("activemq:queue:special").autoStartup("{{startupRouteProperty}}").to("file://backup");
</code>```

http://camel.apache.org/configuring-route-startup-ordering-and-autostartup

Body:
You can use the .autoStartup("{{propertyName}}") function from the Java DSL. For example:

from("activemq:queue:special").autoStartup("{{startupRouteProperty}}").to("file://backup");

http://camel.apache.org/configuring-route-startup-ordering-and-autostartup


问:
php display records not showing
I am trying to show records in php with mysqli. this is my code for php display record which does not gives any error but does  not shows any records as well. insert operation is working but display not working what is missing here ???</p>

```<code>    <!DOCTYPE html>
<html>
<body>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

   movie_name<input type="text" name="movie_name"><br>
   movie_embedded_id<input type="text" name="movie_embedded_id"><br>
   rating_no<input type="text" name="rating_no"><br>
   movie_description<input type="text" name="movie_description"><br>
   <input type="submit" name="submit" value="Submit">

</form>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="mydb";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

        if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
                $sql = "INSERT INTO movies (movie_name, movie_embedded_id, rating_no, movie_description)VALUES ('".$_POST['movie_name']."', '".$_POST['movie_embedded_id']."', '".$_POST['rating_no']."','".$_POST['movie_description']."')";

            if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
            } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
            }

        }

$conn->close();

?>

<?php

      if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
$sql = "select * from movies where movie_id = ".$_GET["id"]."";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "<table><tr><th>ID</th><th>movie_name</th><th>movie_embedded_id</th><th>rating_no</th><th>movie_description</th></tr>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<tr><td>" . $row["id"]. "</td><td>" . $row["movie_name"]. " </td><td>" . $row["movie_embedded_id"]. " </td><td>" . $row["rating_no"]. "</td><td> " . $row["rating_no"]. "</td></tr>";
     }
     echo "</table>";
} else {
     echo "0 results";
}

    }

  ?>

</body>
</html>
</code>```

答:
I am very thank you all for kind responses. here i have figure out my issue.only there is problem when i add id column , extra empty column getting added , don't know why.Kindly review this code for  more secure and optimized.</p>

```<code>    <div class="container">
<form class="form-horizontal" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <div class="form-group">
    <label class="control-label col-sm-2" for="movie_name">movie_name:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="movie_name" name="movie_name" placeholder="Enter movie name">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-2" for="movie_embedded_id">movie_embedded_id:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="movie_embedded_id" name="movie_embedded_id" placeholder="Enter embeded id">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-2" for="rating_no">rating_no:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="rating_no" name="rating_no" placeholder="Enter rating_no">
    </div>
  </div>
    <div class="form-group">
    <label class="control-label col-sm-2" for="movie_description">rating_no:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="movie_description" name="movie_description" placeholder="Enter movie_description">
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" name="submit" class="btn btn-default" >submit</button>
    </div>
  </div>
</form>
</div>
  <table class="table table-bordered">
    <thead>
      <tr>
<!--       <th>ID.<th> -->
       <th>movie_name</th>
       <th>movie_embedded_id</th>
       <th>rating_no</th>
       <th>movie_description</th>
       <th>Update</th>
      </tr>
    </thead>
        <tbody>
    <?php
    include "db.php";
    include "movieinsert.php";

      $result ="select * from movies";
      $get=mysqli_query($conn, $result);

    while ($data = mysqli_fetch_array($get))
        {
    ?>
          <tr>
    <!--      <td><?php //echo "$data[0]"; ?><td> -->
          <td><?php echo "$data[1]"; ?></td>
          <td><?php echo "$data[2]"; ?></td>
          <td><?php echo "$data[3]"; ?></td>
          <td><?php echo "$data[4]"; ?></td>
          <td>
          <a href='mvieupdate.php?id=$data[0]' class="btn btn-info" role="button">Update</a>
          </td>
          </tr>
    <?php
         }
     ?>
  <tbody>
   </table>
</code>```

Title: php display records not showing

Body:
I am trying to show records in php with mysqli. this is my code for php display record which does not gives any error but does  not shows any records as well. insert operation is working but display not working what is missing here ???

    <!DOCTYPE html>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

   movie_name<input type="text" name="movie_name">

   movie_embedded_id<input type="text" name="movie_embedded_id">

   rating_no<input type="text" name="rating_no">

   movie_description<input type="text" name="movie_description">

   <input type="submit" name="submit" value="Submit">

</form>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="mydb";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

        if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
                $sql = "INSERT INTO movies (movie_name, movie_embedded_id, rating_no, movie_description)VALUES ('".$_POST['movie_name']."', '".$_POST['movie_embedded_id']."', '".$_POST['rating_no']."','".$_POST['movie_description']."')";

            if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
            } else {
            echo "Error: " . $sql . "
" . $conn->error;
            }

        }

$conn->close();

?>

<?php

      if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
$sql = "select * from movies where movie_id = ".$_GET["id"]."";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "

ID	movie_name	movie_embedded_id	rating_no	movie_description
";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "
" . $row["id"]. "	" . $row["movie_name"]. " 	" . $row["movie_embedded_id"]. " 	" . $row["rating_no"]. "	 " . $row["rating_no"]. "
";
     }
     echo "
";
} else {
     echo "0 results";
}

    }

  ?>

Body:
I am very thank you all for kind responses. here i have figure out my issue.only there is problem when i add id column , extra empty column getting added , don't know why.Kindly review this code for  more secure and optimized.

    <div class="container">
<form class="form-horizontal" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <div class="form-group">
    <label class="control-label col-sm-2" for="movie_name">movie_name:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="movie_name" name="movie_name" placeholder="Enter movie name">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-2" for="movie_embedded_id">movie_embedded_id:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="movie_embedded_id" name="movie_embedded_id" placeholder="Enter embeded id">
    </div>
  </div>
  <div class="form-group">
    <label class="control-label col-sm-2" for="rating_no">rating_no:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="rating_no" name="rating_no" placeholder="Enter rating_no">
    </div>
  </div>
    <div class="form-group">
    <label class="control-label col-sm-2" for="movie_description">rating_no:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="movie_description" name="movie_description" placeholder="Enter movie_description">
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" name="submit" class="btn btn-default" >submit</button>
    </div>
  </div>
</form>
</div>
  <table class="table table-bordered">
    <thead>
      <tr>
<!--       <th>ID.<th> -->
       <th>movie_name</th>
       <th>movie_embedded_id</th>
       <th>rating_no</th>
       <th>movie_description</th>
       <th>Update</th>
      </tr>
    </thead>
        <tbody>
    <?php
    include "db.php";
    include "movieinsert.php";

      $result ="select * from movies";
      $get=mysqli_query($conn, $result);

    while ($data = mysqli_fetch_array($get))
        {
    ?>
          <tr>
    <!--      <td><?php //echo "$data[0]"; ?><td> -->
          <td><?php echo "$data[1]"; ?></td>
          <td><?php echo "$data[2]"; ?></td>
          <td><?php echo "$data[3]"; ?></td>
          <td><?php echo "$data[4]"; ?></td>
          <td>
          <a href='mvieupdate.php?id=$data[0]' class="btn btn-info" role="button">Update</a>
          </td>
          </tr>
    <?php
         }
     ?>
  <tbody>
   </table>


问:
Authorized used of goo.gl API to add URLs to user history
With Google opening the goo.gl API a few weeks ago, it's quite easy to use it with POST:

```<code>curl -F "url=LONGURL" http://goo.gl/api/shorten
</code>```

The response is like this:

```<code>{"short_url":"http://goo.gl/A9MR","added_to_history":false}
</code>```

So, does anyone know how to perform an authorized POST to the goo.gl API so that the shortened URL is added to the users history as if you would use the browser?
I tried providing a basic Authorization header using my Google mail address and password, but that doesn't work.

答:
It's not really a public API, yet. What you're using is what the goo.gl site uses itself, but it's not designed for public use like you're trying to do. They do plan on launching one though, and when they do I'm sure they'll add it as an option.

See this post

EDIT: This is now possible with the newly launched API. See the docs here.

Body:
With Google opening the goo.gl API a few weeks ago, it's quite easy to use it with POST:

curl -F "url=LONGURL" http://goo.gl/api/shorten

The response is like this:

{"short_url":"http://goo.gl/A9MR","added_to_history":false}

So, does anyone know how to perform an authorized POST to the goo.gl API so that the shortened URL is added to the users history as if you would use the browser?
I tried providing a basic Authorization header using my Google mail address and password, but that doesn't work.