问:
Add  tag to BlueImp gallery title
I'm trying to add an  tag to the title of each video (this gallery holds Youtube videos instead of images) on a BlueImp gallery like so:

```<code>galleryVideos.push({
                    title: " <img src='link.jpg'>",
                    href: 'http://link.com',
                    type: 'text/html'
                  })
</code>```

But when it gets rendered the text on the screen is  (it renders the text instead of the image), and when I inspect the tag looks like:

```<code><h3 class="title"> <img src='link.jpg'></h3>
</code>```

If I manually edit the HTML code through the developer tools editor, and substitute the < and > for < and > anchor symbols the image renders correctly.

I have tried escaping the characters but no luck.

Greetings
Thank you

答:
I think the title value is automatically escaped to avoid script injection attack.

By looking the BlueImp doc, you need to do something like this :

```<code>galleryVideos.push({
                title: '',
                href: 'http://link.com',
                type: 'image/jpeg',
                thumbnail: 'link.jpg'
              })
</code>```

Title: Add <img> tag to BlueImp gallery title

Body:
I'm trying to add an  tag to the title of each video (this gallery holds Youtube videos instead of images) on a BlueImp gallery like so:

galleryVideos.push({
                    title: " ",
                    href: 'http://link.com',
                    type: 'text/html'
                  })

But when it gets rendered the text on the screen is  (it renders the text instead of the image), and when I inspect the tag looks like:

If I manually edit the HTML code through the developer tools editor, and substitute the < and > for < and > anchor symbols the image renders correctly.

I have tried escaping the characters but no luck.

Greetings
Thank you

Body:
I think the title value is automatically escaped to avoid script injection attack.

By looking the BlueImp doc, you need to do something like this :

galleryVideos.push({
                title: '',
                href: 'http://link.com',
                type: 'image/jpeg',
                thumbnail: 'link.jpg'
              })


来源: stackexchange

问:
Exception while attempting to add an entry to the access log
Tomcat 7 can't write the access log and throws the following exception.

```<code>Nov 17, 2016 5:10:37 PM org.apache.catalina.connector.CoyoteAdapter log
WARNING: Exception while attempting to add an entry to the access log
java.lang.NullPointerException
        at org.apache.catalina.connector.CoyoteAdapter.log(CoyoteAdapter.java:555)
        at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:182)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
</code>```

How to fix this?

答:
This is a known issue in Tomcat which is fixed in Tomcat 8.0.29. Upgrading Tomcat should resolve this problem.
https://bz.apache.org/bugzilla/show_bug.cgi?id=58578

Other way is to modify access logging pattern not to include cookie. Use something like this:

```<code>pattern="%t %H request:%{SESSIONID}r %m %U %s %q %r"
</code>```

instead of

```<code>pattern="%t %H cookie:%{SESSIONID}c request:%{SESSIONID}r %m %U %s %q %r"
</code>```

in server.xml.

```<code>    <!-- Access log processes all example.
         Documentation at: /docs/config/valve.html
         Note: The pattern used is equivalent to using pattern="common" -->
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log" suffix=".txt"
           pattern="%h %l %u %t "%r" %s %b" />

  </Host>
</Engine>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Tomcat 7 can't write the access log and throws the following exception.

Nov 17, 2016 5:10:37 PM org.apache.catalina.connector.CoyoteAdapter log
WARNING: Exception while attempting to add an entry to the access log
java.lang.NullPointerException
        at org.apache.catalina.connector.CoyoteAdapter.log(CoyoteAdapter.java:555)
        at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:182)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

How to fix this?

Body:
This is a known issue in Tomcat which is fixed in Tomcat 8.0.29. Upgrading Tomcat should resolve this problem.
https://bz.apache.org/bugzilla/show_bug.cgi?id=58578

Other way is to modify access logging pattern not to include cookie. Use something like this:

pattern="%t %H request:%{SESSIONID}r %m %U %s %q %r"

instead of

pattern="%t %H cookie:%{SESSIONID}c request:%{SESSIONID}r %m %U %s %q %r"

in server.xml.

    <!-- Access log processes all example.
         Documentation at: /docs/config/valve.html
         Note: The pattern used is equivalent to using pattern="common" -->
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log" suffix=".txt"
           pattern="%h %l %u %t &quot;%r&quot; %s %b" />

  </Host>
</Engine>


问:
Why is nginx responding to any domain name?
I have nginx up and running with a Ruby/Sinatra app and all is well. However, I'm now trying to have a second application running from the same server and I noticed something weird. First, here's my nginx.conf:

```<code>pid /tmp/nginx.pid;
error_log /tmp/nginx.error.log;

events {
  worker_connections 1024;
  accept_mutex off;
}

http {
  default_type application/octet-stream;
  access_log /tmp/nginx.access.log combined;

  sendfile on;
  tcp_nopush on;
  tcp_nodelay off;

  gzip on;
  gzip_http_version 1.0;
  gzip_proxied any;
  gzip_min_length 500;
  gzip_disable "MSIE [1-6]\.";
  gzip_types text/plain text/xml text/css
             text/comma-separated-values
             text/javascript application/x-javascript
             application/atom+xml;

  upstream app {
    server unix:/var/www/app/tmp/sockets/unicorn.sock fail_timeout=0;
  }

  server {
    listen 80;
    client_max_body_size 4G;
    server_name FAKE.COM;

    keepalive_timeout 5;

    root /var/www/app/public;

    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;

      if (!-f $request_filename) {
        proxy_pass http://app;
        break;
      }
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
      root /var/www/app/public;
    }
  }
}
                                                          68,0-1        B
</code>```

Notice how server_name is set to FAKE.COM yet the server is responding to all hosts that hit that server via other domain names. How can I make that particular server respond only to requests for FAKE.COM?

答:
To answer your question - nginx picks the first server if there's no match. See documentation:

If its value does not match any server name, or the request does not
  contain this header field at all, then nginx will route the request to
  the default server for this port. In the configuration above, the
  default server is the first one...

Now, if you wanted to have a default catch-all server that, say, responds with 404 to all requests, then here's how to do it:

```<code>server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name _;
    ssl_certificate <path to cert>
    ssl_certificate_key <path to key>
    return 404;
}
</code>```

Note that you need to specify certificate/key (that can be self-signed), otherwise all SSL connections will fail as nginx will try to accept connection using this default_server and won't find cert/key.

Body:
I have nginx up and running with a Ruby/Sinatra app and all is well. However, I'm now trying to have a second application running from the same server and I noticed something weird. First, here's my nginx.conf:

pid /tmp/nginx.pid;
error_log /tmp/nginx.error.log;

events {
  worker_connections 1024;
  accept_mutex off;
}

http {
  default_type application/octet-stream;
  access_log /tmp/nginx.access.log combined;

  sendfile on;
  tcp_nopush on;
  tcp_nodelay off;

  gzip on;
  gzip_http_version 1.0;
  gzip_proxied any;
  gzip_min_length 500;
  gzip_disable "MSIE [1-6]\.";
  gzip_types text/plain text/xml text/css
             text/comma-separated-values
             text/javascript application/x-javascript
             application/atom+xml;

  upstream app {
    server unix:/var/www/app/tmp/sockets/unicorn.sock fail_timeout=0;
  }

  server {
    listen 80;
    client_max_body_size 4G;
    server_name FAKE.COM;

    keepalive_timeout 5;

    root /var/www/app/public;

    location / {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;

      if (!-f $request_filename) {
        proxy_pass http://app;
        break;
      }
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
      root /var/www/app/public;
    }
  }
}
                                                          68,0-1        B

Notice how server_name is set to FAKE.COM yet the server is responding to all hosts that hit that server via other domain names. How can I make that particular server respond only to requests for FAKE.COM?

Body:
To answer your question - nginx picks the first server if there's no match. See documentation:

If its value does not match any server name, or the request does not
  contain this header field at all, then nginx will route the request to
  the default server for this port. In the configuration above, the
  default server is the first one...

Now, if you wanted to have a default catch-all server that, say, responds with 404 to all requests, then here's how to do it:

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name _;
    ssl_certificate <path to cert>
    ssl_certificate_key <path to key>
    return 404;
}

Note that you need to specify certificate/key (that can be self-signed), otherwise all SSL connections will fail as nginx will try to accept connection using this default_server and won't find cert/key.


问:
Does the main thread run on blocking threads?
When I started to look into threading in c++11, I thought that .join() was used to make a blocking operation on the main thread and std::async() was used to run non-blocking threads.

This answer explains std:async() pretty well in my opinion. https://stackoverflow.com/a/15035157/1770034

But I wanted to understand the join method better. I found several examples like this: https://stackoverflow.com/a/11229853/1770034 Where only 1 thread is created from the main thread.

Then I found this https://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/

Snippet of Code from site:

```<code>#include <iostream>
#include <thread>

static const int num_threads = 10;

//This function will be called from a thread

void call_from_thread(int tid) {
    std::cout << "Launched by thread " << tid << std::endl;
}

int main() {
    std::thread t[num_threads];

    //Launch a group of threads
    for (int i = 0; i < num_threads; ++i) {
        t[i] = std::thread(call_from_thread, i);
    }

    std::cout << "Launched from the main\n";

    //Join the threads with the main thread
    for (int i = 0; i < num_threads; ++i) {
        t[i].join();
    }

    return 0;
}
</code>```

The part I'm curious about this this part right here:

```<code>//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
    t[i].join();
}
</code>```

If the main thread stops to wait until .join() is complete, how can the loop run to join more threads? The fact it works is great! But, why does it work?

Why does it work this way? This was my impression of how it worked.

Main thread joins 1st thread.

Main thread waits until 1st thread finishes.

1st thread finishes.

Main thread continues in for loop and joins 2nd thread.

Main thread waits until 2nd thread finishes.

... ... ...

If it keep cycling through the for loop when does the main thread actually get blocked to wait?

Edit

Example:

```<code>//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
    t[i].join();
    // --- Perform some long operation here ---
}
</code>```

When would the long operation take place?

答:
When I posted this question I didn't understand exactly what was going on when it came to multi-threading.

Even in reading several tutorials on the subject matter in C++, it can still be a bit hazy what is exactly going on. So this is an explanation of what is actually happening.

To keep it simple let's use this code:

```<code>#include <thread>

void my_function()
{
     *** Some Code ***
}

int main()
{
    std::thread threads[10]; //create 10 std::thread objects

    for(int loop = 0; loop < 10; loop++)
    {
        threads[loop] = std::thread(my_function);
    }

    //Threads are executing on machine and main code is also running

    for(int loop = 0; loop < 10; loop++)
    {
        threads[loop].join; //If threads[loop] is still running wait for it, otherwise keep moving forward.
    }

    return 0;
} //all 10 thread objects (threads) are going out of scope and their destructors are being called
</code>```

At the top of main (in the main thread) we create space for 10 thread objects on the stack. Inside the first for loop we actually create a std::thread, which will call my_function on a separate thread.

Let's assume that we have a quad-core processor and one thread can only run at a processor at a time. (Quite the assumption!) The main thread is currently using one of the processors and one of our 10 threads will use the second one. One of the remaining 9 will use the third one and one of the remaining 8 will use the fourth one.

Between the for loops we can execute all the code we want on our main thread. (ie: the main thread is not blocked). Next we get to the second for loop. This loop will go through and tell each of the threads to join.

Let's pretend that threads 1-9 have executed by this point in time but we are still running thread 10 in the background. When the for loop joins thread 1. Since it is already complete the for loop runs again. This continues to happen through the first 9 threads. Now we join thread 10. It is still running, the main thread will now wait until thread 10 is done. (This is good if you need code done at a certain point before you can move forward.)

Next we have return 0; and the std::threads that we created go out of scope and since they are objects the destructor is called. Since all the threads are joined to the main, no exceptions are thrown and everything ends nicely.

If we thought, "hey, I don't care if the thread finished or not, this program is over." When the std::thread destructor is called the std::thread object will noticed that something is wrong and raise std::terminate.

If we really don't care when the thread finishes or if it finishes. We can use detach. This will allow it to run until it completes its task. If it is still running at the end of main the thread will die without exception (a modern OS will kill it with the process.)

What is joinable? joinable will be true if you did not join a thread to or detach a thread from the caller (the main thread in our case). If you want to check if a thread is still running and not join it until it is. You'll need to use std::async instead. (Can C++11 tell if std::thread is active?)

Body:
When I started to look into threading in c++11, I thought that .join() was used to make a blocking operation on the main thread and std::async() was used to run non-blocking threads.

This answer explains std:async() pretty well in my opinion. https://stackoverflow.com/a/15035157/1770034

But I wanted to understand the join method better. I found several examples like this: https://stackoverflow.com/a/11229853/1770034 Where only 1 thread is created from the main thread.

Then I found this https://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/

Snippet of Code from site:

#include <iostream>
#include <thread>

static const int num_threads = 10;

//This function will be called from a thread

void call_from_thread(int tid) {
    std::cout << "Launched by thread " << tid << std::endl;
}

int main() {
    std::thread t[num_threads];

    //Launch a group of threads
    for (int i = 0; i < num_threads; ++i) {
        t[i] = std::thread(call_from_thread, i);
    }

    std::cout << "Launched from the main\n";

    //Join the threads with the main thread
    for (int i = 0; i < num_threads; ++i) {
        t[i].join();
    }

    return 0;
}

The part I'm curious about this this part right here:

//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
    t[i].join();
}

If the main thread stops to wait until .join() is complete, how can the loop run to join more threads? The fact it works is great! But, why does it work?

Why does it work this way? This was my impression of how it worked.

Main thread joins 1st thread.

Main thread waits until 1st thread finishes.

1st thread finishes.

Main thread continues in for loop and joins 2nd thread.

Main thread waits until 2nd thread finishes.

... ... ...

If it keep cycling through the for loop when does the main thread actually get blocked to wait?

Edit

Example:

//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
    t[i].join();
    // --- Perform some long operation here ---
}

When would the long operation take place?

Body:
When I posted this question I didn't understand exactly what was going on when it came to multi-threading.

Even in reading several tutorials on the subject matter in C++, it can still be a bit hazy what is exactly going on. So this is an explanation of what is actually happening.

To keep it simple let's use this code:

#include <thread>

void my_function()
{
     *** Some Code ***
}

int main()
{
    std::thread threads[10]; //create 10 std::thread objects

    for(int loop = 0; loop < 10; loop++)
    {
        threads[loop] = std::thread(my_function);
    }

    //Threads are executing on machine and main code is also running

    for(int loop = 0; loop < 10; loop++)
    {
        threads[loop].join; //If threads[loop] is still running wait for it, otherwise keep moving forward.
    }

    return 0;
} //all 10 thread objects (threads) are going out of scope and their destructors are being called

At the top of main (in the main thread) we create space for 10 thread objects on the stack. Inside the first for loop we actually create a std::thread, which will call my_function on a separate thread.

Let's assume that we have a quad-core processor and one thread can only run at a processor at a time. (Quite the assumption!) The main thread is currently using one of the processors and one of our 10 threads will use the second one. One of the remaining 9 will use the third one and one of the remaining 8 will use the fourth one.

Between the for loops we can execute all the code we want on our main thread. (ie: the main thread is not blocked). Next we get to the second for loop. This loop will go through and tell each of the threads to join.

Let's pretend that threads 1-9 have executed by this point in time but we are still running thread 10 in the background. When the for loop joins thread 1. Since it is already complete the for loop runs again. This continues to happen through the first 9 threads. Now we join thread 10. It is still running, the main thread will now wait until thread 10 is done. (This is good if you need code done at a certain point before you can move forward.)

Next we have return 0; and the std::threads that we created go out of scope and since they are objects the destructor is called. Since all the threads are joined to the main, no exceptions are thrown and everything ends nicely.

If we thought, "hey, I don't care if the thread finished or not, this program is over." When the std::thread destructor is called the std::thread object will noticed that something is wrong and raise std::terminate.

If we really don't care when the thread finishes or if it finishes. We can use detach. This will allow it to run until it completes its task. If it is still running at the end of main the thread will die without exception (a modern OS will kill it with the process.)

What is joinable? joinable will be true if you did not join a thread to or detach a thread from the caller (the main thread in our case). If you want to check if a thread is still running and not join it until it is. You'll need to use std::async instead. (Can C++11 tell if std::thread is active?)


问:
Can we fetch the call details of an iPhone?
Can we fetch the call details like dialed numbers, missed calls of an iPhone?

UPDATE

Can we do it in jail broken phones for CYDIA store?

答: No - Apple simply don't provide an API to do this.</p>

ContentLicense: CC BY-SA 2.5


问:
MySQL to Eloquent query
I've been having some issues with a query. I'm trying to get the most recent record for each 'category' from a table, but I can't figure out how to write the query in Laravel.

I got the query working in MySQL, but no real luck in translating it.

The MySQL query looks like this:

```<code>SELECT *
FROM messages
WHERE id IN (
   SELECT MAX(id)
   FROM messages
   GROUP BY conversation_id
);
</code>```

I was trying something like this in Laravel, but it doesn't seem to work:

```<code>return self::where(function($query){
        $query->select(max(['id']))
        ->from('messages')
        ->groupBy('conversation_id');
    })
    ->get();
</code>```

答:
(Posted on behalf of the OP).

Thanks to AlexM's comments I figured it out.

```<code>return self::whereIn('id', function($query){
        $query->select(max(['id']))
        ->from('messages')
        ->orderBy('created_at', 'desc')
        ->groupBy('conversation_id');
    })
    ->get();
</code>```

Was my first solution but that didn't work quite well. It was selecting two records as intended, but not the last ones.

I've then come up with the idea to use selectRaw instead select, which solved my issue perfectly. The final query looks like this, for any interested:

```<code>return self::whereIn('id', function($query){
        $query->selectRaw('max(id)')
        ->from('messages')
        ->orderBy('created_at', 'desc')
        ->groupBy('conversation_id');
    })
    ->get();
</code>```

Title: MySQL to Eloquent query

Body:
I've been having some issues with a query. I'm trying to get the most recent record for each 'category' from a table, but I can't figure out how to write the query in Laravel.

I got the query working in MySQL, but no real luck in translating it.

The MySQL query looks like this:

SELECT *
FROM messages
WHERE id IN (
   SELECT MAX(id)
   FROM messages
   GROUP BY conversation_id
);

I was trying something like this in Laravel, but it doesn't seem to work:

return self::where(function($query){
        $query->select(max(['id']))
        ->from('messages')
        ->groupBy('conversation_id');
    })
    ->get();

Body:
(Posted on behalf of the OP).

Thanks to AlexM's comments I figured it out.

return self::whereIn('id', function($query){
        $query->select(max(['id']))
        ->from('messages')
        ->orderBy('created_at', 'desc')
        ->groupBy('conversation_id');
    })
    ->get();

Was my first solution but that didn't work quite well. It was selecting two records as intended, but not the last ones.

I've then come up with the idea to use selectRaw instead select, which solved my issue perfectly. The final query looks like this, for any interested:

return self::whereIn('id', function($query){
        $query->selectRaw('max(id)')
        ->from('messages')
        ->orderBy('created_at', 'desc')
        ->groupBy('conversation_id');
    })
    ->get();


问:
Condense SQL list if any value present
I have a table like this:

```<code>Email | Value
a     |  T
a     |  F
b     |  T
c     |  F
c     |  F
</code>```

I want to convert all Values for an email to T if T is present, otherwise keep as F, then group by unique email:

```<code>Email | Value
a     | T
b     | T
c     | F
</code>```

答:
With those values, you can use max() and group by.

```<code>select Email, max(value) as Value
from t
group by Email
</code>```

Title: Condense SQL list if any value present

Body:
I have a table like this:

Email | Value
a     |  T
a     |  F
b     |  T
c     |  F
c     |  F

I want to convert all Values for an email to T if T is present, otherwise keep as F, then group by unique email:

Email | Value
a     | T
b     | T
c     | F

Body:
With those values, you can use max() and group by.

select Email, max(value) as Value
from t
group by Email


问:
Json Deserialize C#
I want to parsing this json file.

{"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[26.4217861898109,40.127607984644],[26.4219934821323,40.1275230229872],[26.4218810759267,40.1273800013679],[26.4216801413981,40.1274730404221],[26.4217861898109,40.127607984644]]]},"properties":{"ParselNo":"1","Alan":"340.48
  m2","Mevkii":"-","Nitelik":"Arsa","Ada":"698","Il":"Çanakkale","Ilce":"Merkez","Pafta":"16","Mahalle":"Barbaros"}}],"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}}}

I try this code:

```<code>string fileName = file.FileName;
string json = System.IO.File.ReadAllText(fileName);
dynamic stuff = JsonConvert.DeserializeObject(json);

string s1 = Convert.ToString(stuff.features.Count);
string s2 = stuff.properties.ParselNo;
MessageBox.Show(s1);
MessageBox.Show(s2);
</code>```

s1 is working but s2 give error. How can I fix it?

I want to get it like this:

```<code>Coordinates[] coordinates = [(26.xx, 40.xx), (26.xx,40.xx) ... ]
ParselNo = 1
Alan = 340.48
Nitelik = Arsa
Ada = 698
İl = Çanakkale
İlçe = Merkez
Pafta = 16
dat_name = EPSG:4326
</code>```

what can i do?

答:
This code work: stuff.features[0].properties.ParselNo
But don't this: stuff.features[0].geometry.coordinates[0];

I don't understand it :(
Error code..

Title: Json Deserialize C#

Body:
I want to parsing this json file.

{"features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[26.4217861898109,40.127607984644],[26.4219934821323,40.1275230229872],[26.4218810759267,40.1273800013679],[26.4216801413981,40.1274730404221],[26.4217861898109,40.127607984644]]]},"properties":{"ParselNo":"1","Alan":"340.48
  m2","Mevkii":"-","Nitelik":"Arsa","Ada":"698","Il":"Çanakkale","Ilce":"Merkez","Pafta":"16","Mahalle":"Barbaros"}}],"type":"FeatureCollection","crs":{"type":"name","properties":{"name":"EPSG:4326"}}}

I try this code:

string fileName = file.FileName;
string json = System.IO.File.ReadAllText(fileName);
dynamic stuff = JsonConvert.DeserializeObject(json);

string s1 = Convert.ToString(stuff.features.Count);
string s2 = stuff.properties.ParselNo;
MessageBox.Show(s1);
MessageBox.Show(s2);

s1 is working but s2 give error. How can I fix it?

I want to get it like this:

Coordinates[] coordinates = [(26.xx, 40.xx), (26.xx,40.xx) ... ]
ParselNo = 1
Alan = 340.48
Nitelik = Arsa
Ada = 698
İl = Çanakkale
İlçe = Merkez
Pafta = 16
dat_name = EPSG:4326

what can i do?


问:
Inserting Parameters in Header in Chrome Custom Tabs
A previous question question implies that altering the Cookie Jar isn't possible. Is there at least a way to pass parameters in the header of the webcall ie:for authentication.</p>

答:
I did the following and when I inspect the request that is made, it looks like my "Cookie" header is getting replaced by Chrome custom tabs even though my "Value" header goes through.

```<code>Bundle headersBundle = new Bundle();
headersBundle.putString("Value", value);
headersBundle.putString("Cookie", cookie);
CustomTabsIntent customTabsIntent = CustomTabsIntent.Builder().build();
customTabsIntent.intent.putExtra(android.provider.Browser.EXTRA_HEADERS, headersBundle);
intent.launchUrl(context, uri);
</code>```

This answer does not provide a source but it says that it is not possible to alter the cookie jar on Chrome Custom Tabs currently.

Edit:

And this answer recommends using Smart Lock for Passwords on Android to perform authentication in custom tabs.

Body:
I did the following and when I inspect the request that is made, it looks like my "Cookie" header is getting replaced by Chrome custom tabs even though my "Value" header goes through.

Bundle headersBundle = new Bundle();
headersBundle.putString("Value", value);
headersBundle.putString("Cookie", cookie);
CustomTabsIntent customTabsIntent = CustomTabsIntent.Builder().build();
customTabsIntent.intent.putExtra(android.provider.Browser.EXTRA_HEADERS, headersBundle);
intent.launchUrl(context, uri);

This answer does not provide a source but it says that it is not possible to alter the cookie jar on Chrome Custom Tabs currently.

Edit:

And this answer recommends using Smart Lock for Passwords on Android to perform authentication in custom tabs.


问:
Efficient way to get ancestors - materialized path
I have a hierarchical data structure stored using materialized paths.

```<code>Table:Files

node  parentNode  name    path
 100    NULL       f1     /f1/
 101    100        f2     /f1/f2/
 102    101        f3     /f1/f2/f3/
</code>```

I have the node column as primary key(clustered)

Now if I want to find the ancestors of f3, given the path, I do something like this:

```<code>SELECT * FROM Files WHERE '/f1/f2/f3/' LIKE [path] + '%'
</code>```

The problem with this is, the execution plan uses a clustered index scan( which I think SQL server defaults to for table scans)

Is there anyway I can find the ancestors of a node, given the path in a more efficient manner, preferably not using a CTE? I also have a depth column at my disposal if required.

答:
If you have slow moving hierarchies, consider adding Range Keys.  They facilitate navigation, filtration, and/or aggregration without the need of recursion.

The Range keys indicate ownership between X and Y. The range keys are especially helpful when dealing with large hierarchies (180K nodes).

The following is a simplified example, but may help.

Sample Hier Build

```<code>--Drop Table #MyHier

Declare @YourTable table (id int,ParentId  int,Name varchar(50))
Insert into @YourTable values
 (11, NULL,'A')
,(12, 11   ,'B')
,(13, 12   ,'F')
,(14, 13   ,'C')
,(15, 13   ,'D')
,(16, 11   ,'E')
,(17, 12   ,'G')
,(18, NULL ,'M')
,(19, 18   ,'N')
,(20, 18   ,'O')
,(21, 20   ,'P')

Declare @Top    int         = null      --<<  Sets top of Hier Try 3
Declare @Nest   varchar(25) = '|-----'  --<<  Optional: Added for readability

;with cteP as (
      Select Seq  = cast(10000+Row_Number() over (Order by Name) as varchar(500))
            ,ID
            ,ParentId
            ,Lvl=1
            ,Name
            ,Path = cast('/'+Name+'/' as varchar(500))
      From   @YourTable
      Where  IsNull(@Top,-1) = case when @Top is null then isnull(ParentId ,-1) else ID end
      Union  All
      Select Seq  = cast(concat(p.Seq,'.',10000+Row_Number() over (Order by r.Name)) as varchar(500))
            ,r.ID
            ,r.ParentId
            ,p.Lvl+1
            ,r.Name
            ,cast(p.path + '/'+r.Name+'/' as varchar(500))
      From   @YourTable r
      Join   cteP p on r.ParentId  = p.ID)
     ,cteR1 as (Select *,R1=Row_Number() over (Order By Seq) From cteP)
     ,cteR2 as (Select A.ID,R2=Max(B.R1) From cteR1 A Join cteR1 B on (B.Seq like A.Seq+'%') Group By A.Seq,A.ID )
Select A.R1
      ,B.R2
      ,A.ID
      ,A.ParentId
      ,A.Lvl
      ,Name = Replicate(@Nest,A.Lvl-1) + A.Name
      ,Path
 Into  #MyHier
 From cteR1 A
 Join cteR2 B on A.ID=B.ID
</code>```

Select Full Hier

```<code>-- Get The Full Hier
Select *
 From #MyHier
 Order By R1
</code>```

Returns

Get Ancestors

```<code>-- Get Ancestors of a Node
Declare @GetAncestors int = 15
Select A.*
 From  #MyHier A
 Join  (Select R1 From #MyHier Where ID=@GetAncestors) B
   on  B.R1 between A.R1 and A.R2
 Order By A.R1
</code>```

Returns

Select Descendants

```<code>-- Get Descendants of a Node
Declare @GetDesendants int = 12
Select A.*
 From  #MyHier A
 Join  (Select R1,R2 From #MyHier Where ID=@GetDesendants) B
   on  A.R1 between B.R1 and B.R2
 Order By A.R1
</code>```

Returns

Body:
I have a hierarchical data structure stored using materialized paths.

Table:Files

node  parentNode  name    path
 100    NULL       f1     /f1/
 101    100        f2     /f1/f2/
 102    101        f3     /f1/f2/f3/

I have the node column as primary key(clustered)

Now if I want to find the ancestors of f3, given the path, I do something like this:

SELECT * FROM Files WHERE '/f1/f2/f3/' LIKE [path] + '%'

The problem with this is, the execution plan uses a clustered index scan( which I think SQL server defaults to for table scans)

Is there anyway I can find the ancestors of a node, given the path in a more efficient manner, preferably not using a CTE? I also have a depth column at my disposal if required.

Body:
If you have slow moving hierarchies, consider adding Range Keys.  They facilitate navigation, filtration, and/or aggregration without the need of recursion.

The Range keys indicate ownership between X and Y. The range keys are especially helpful when dealing with large hierarchies (180K nodes).

The following is a simplified example, but may help.

Sample Hier Build

--Drop Table #MyHier

Declare @YourTable table (id int,ParentId  int,Name varchar(50))
Insert into @YourTable values
 (11, NULL,'A')
,(12, 11   ,'B')
,(13, 12   ,'F')
,(14, 13   ,'C')
,(15, 13   ,'D')
,(16, 11   ,'E')
,(17, 12   ,'G')
,(18, NULL ,'M')
,(19, 18   ,'N')
,(20, 18   ,'O')
,(21, 20   ,'P')

Declare @Top    int         = null      --<<  Sets top of Hier Try 3
Declare @Nest   varchar(25) = '|-----'  --<<  Optional: Added for readability

;with cteP as (
      Select Seq  = cast(10000+Row_Number() over (Order by Name) as varchar(500))
            ,ID
            ,ParentId
            ,Lvl=1
            ,Name
            ,Path = cast('/'+Name+'/' as varchar(500))
      From   @YourTable
      Where  IsNull(@Top,-1) = case when @Top is null then isnull(ParentId ,-1) else ID end
      Union  All
      Select Seq  = cast(concat(p.Seq,'.',10000+Row_Number() over (Order by r.Name)) as varchar(500))
            ,r.ID
            ,r.ParentId
            ,p.Lvl+1
            ,r.Name
            ,cast(p.path + '/'+r.Name+'/' as varchar(500))
      From   @YourTable r
      Join   cteP p on r.ParentId  = p.ID)
     ,cteR1 as (Select *,R1=Row_Number() over (Order By Seq) From cteP)
     ,cteR2 as (Select A.ID,R2=Max(B.R1) From cteR1 A Join cteR1 B on (B.Seq like A.Seq+'%') Group By A.Seq,A.ID )
Select A.R1
      ,B.R2
      ,A.ID
      ,A.ParentId
      ,A.Lvl
      ,Name = Replicate(@Nest,A.Lvl-1) + A.Name
      ,Path
 Into  #MyHier
 From cteR1 A
 Join cteR2 B on A.ID=B.ID

Select Full Hier

-- Get The Full Hier
Select *
 From #MyHier
 Order By R1

Returns

Get Ancestors

-- Get Ancestors of a Node
Declare @GetAncestors int = 15
Select A.*
 From  #MyHier A
 Join  (Select R1 From #MyHier Where ID=@GetAncestors) B
   on  B.R1 between A.R1 and A.R2
 Order By A.R1

Returns

Select Descendants

-- Get Descendants of a Node
Declare @GetDesendants int = 12
Select A.*
 From  #MyHier A
 Join  (Select R1,R2 From #MyHier Where ID=@GetDesendants) B
   on  A.R1 between B.R1 and B.R2
 Order By A.R1

Returns


问:
normalizr schema - child reference parent
Trying to get to grips with normalizr, data structure and schema shown below:

```<code>const data = {
    "name": "abc",
    "outlet": [
        {
            "id": 1,
            "retailer": {
                "id": 1
            }
        },
        {
            "id": 2,
            "retailer": {
                "id": 1
            }
        }
    ]
}

const retailerSchema = new schema.Entity('retailers');

const outletSchema = new schema.Entity('outlets', {
    retailer: retailerSchema
});

const normalized = normalize(data, {
    retailers: [retailerSchema],
    outlets: [outletSchema]
})
</code>```

Current result:

```<code>normalized.result == {name: "abc", outlets: [1, 2]}
normalized.entities.retailers == {1: {id: 1}}
normalized.entities.outlets == {1: {id: 1, retailer: 1}, 2: {id: 2, retailer: 1}}
</code>```

Is it possible to add outlet references based on unique retailers? e.g.

```<code>normalized.result == {name: "abc", outlets: [1, 2], retailers: [1]}
normalized.entities.retailers == {1: {id: 1, outlets: [1, 2]}}
normalized.entities.outlets == {1: {id: 1, retailer: 1}, 2: {id: 2, retailer: 1}}
</code>```

答:
Is it possible to add outlet references based on unique retailers?

Not really. The result that Normalizr returns is always in the same format of the input data. Since your data is { name, outlet }, those are the only keys that will exist in the result output.

If you had a unique identifier on the top-level object (the whole data structure), you could make use of the processStrategy for schema.Entity and shuffle things around, but this is really not recommended.

Body:
Trying to get to grips with normalizr, data structure and schema shown below:

const data = {
    "name": "abc",
    "outlet": [
        {
            "id": 1,
            "retailer": {
                "id": 1
            }
        },
        {
            "id": 2,
            "retailer": {
                "id": 1
            }
        }
    ]
}

const retailerSchema = new schema.Entity('retailers');

const outletSchema = new schema.Entity('outlets', {
    retailer: retailerSchema
});

const normalized = normalize(data, {
    retailers: [retailerSchema],
    outlets: [outletSchema]
})

Current result:

normalized.result == {name: "abc", outlets: [1, 2]}
normalized.entities.retailers == {1: {id: 1}}
normalized.entities.outlets == {1: {id: 1, retailer: 1}, 2: {id: 2, retailer: 1}}

Is it possible to add outlet references based on unique retailers? e.g.

normalized.result == {name: "abc", outlets: [1, 2], retailers: [1]}
normalized.entities.retailers == {1: {id: 1, outlets: [1, 2]}}
normalized.entities.outlets == {1: {id: 1, retailer: 1}, 2: {id: 2, retailer: 1}}


问:
Set partition Array in Ruby
I am working on a script to reload a server with a custom partition scheme. I have this working in Python but I cannot get the same code working in Ruby as I am new to the language.

```<code>require 'softlayer_api'
require 'pp'

client = SoftLayer::Client.new(:timeout => 120)
server_id = REDACTED

config = {

    'upgradeHardDriveFirmware' => 0,
        'upgradeBios' => 0,
        'hardDrives' => [
            {
                'complexType' => "SoftLayer_Hardware_Component_HardDrive",
                'partitions' => [
                    { 'name' => { "/" => { "minimumSize" => "212"} } },
                    { 'name' => { "/boot" => { "minimumSize" => ".25" } } },
                    { 'name' => { "/swap0" => { "minimumSize" => "32"} } },
                    { 'name' => { "/tmp" => { "minimumSize" => "212"} } },
                    { 'name' => { "/var" => { "minimumSize" => "212"} } },
                    { 'name' => { "/remove" => { "minimumSize" => "1", "grow" => "1" } } }
                ]
            }
        ]
     }

setclient = client['Hardware_Server']
reload = setclient.object_with_id(server_id).reloadOperatingSystem('FORCE', config)

pp reload
</code>```

When I run the script I get an error about the partition array beginning with /:

```<code>$ ruby osReloadCustomPartitions.rb
    /Users/ryan/.rbenv/versions/2.3.0/lib/ruby/2.3.0/xmlrpc/client.rb:272:in `call':
Partition (Array) must begin with a / (XMLRPC::FaultException)
</code>```

答:
Try with the below config:</p>

```<code>config = {
    'upgradeHardDriveFirmware' => 0,
        'upgradeBios' => 0,
        'hardDrives' => [
            {
                'complexType' => "SoftLayer_Hardware_Component_HardDrive",
                'partitions' => [
                    { 'name' =>  "/",  "minimumSize" => "212"  },
                    { 'name' =>  "/boot",  "minimumSize" => ".25" },
                    { 'name' =>  "/swap0", "minimumSize" => "32" },
                    { 'name' => "/tmp" ,  "minimumSize" => "212"},
                    { 'name' =>  "/var",  "minimumSize" => "212" },
                    { 'name' =>  "/remove",  "minimumSize" => "1", "grow" => "1"  }
                ]
            }
        ]
     }
</code>```

Title: Set partition Array in Ruby

Body:
I am working on a script to reload a server with a custom partition scheme. I have this working in Python but I cannot get the same code working in Ruby as I am new to the language.

require 'softlayer_api'
require 'pp'

client = SoftLayer::Client.new(:timeout => 120)
server_id = REDACTED

config = {

    'upgradeHardDriveFirmware' => 0,
        'upgradeBios' => 0,
        'hardDrives' => [
            {
                'complexType' => "SoftLayer_Hardware_Component_HardDrive",
                'partitions' => [
                    { 'name' => { "/" => { "minimumSize" => "212"} } },
                    { 'name' => { "/boot" => { "minimumSize" => ".25" } } },
                    { 'name' => { "/swap0" => { "minimumSize" => "32"} } },
                    { 'name' => { "/tmp" => { "minimumSize" => "212"} } },
                    { 'name' => { "/var" => { "minimumSize" => "212"} } },
                    { 'name' => { "/remove" => { "minimumSize" => "1", "grow" => "1" } } }
                ]
            }
        ]
     }

setclient = client['Hardware_Server']
reload = setclient.object_with_id(server_id).reloadOperatingSystem('FORCE', config)

pp reload

When I run the script I get an error about the partition array beginning with /:

$ ruby osReloadCustomPartitions.rb
    /Users/ryan/.rbenv/versions/2.3.0/lib/ruby/2.3.0/xmlrpc/client.rb:272:in `call':
Partition (Array) must begin with a / (XMLRPC::FaultException)

Body:
Try with the below config:

config = {
    'upgradeHardDriveFirmware' => 0,
        'upgradeBios' => 0,
        'hardDrives' => [
            {
                'complexType' => "SoftLayer_Hardware_Component_HardDrive",
                'partitions' => [
                    { 'name' =>  "/",  "minimumSize" => "212"  },
                    { 'name' =>  "/boot",  "minimumSize" => ".25" },
                    { 'name' =>  "/swap0", "minimumSize" => "32" },
                    { 'name' => "/tmp" ,  "minimumSize" => "212"},
                    { 'name' =>  "/var",  "minimumSize" => "212" },
                    { 'name' =>  "/remove",  "minimumSize" => "1", "grow" => "1"  }
                ]
            }
        ]
     }


问:
Weird Behavior when using between? method for dates
Open up a Rails console and enter this:

```<code>2.weeks.ago.between? 2.weeks.ago, 1.week.ago
</code>```

Did it give you true or false? No really, try it a few more times and it will give you different answers.

Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.

I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.

However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.

Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.

Oddly enough, this doesn't happen when doing:

```<code> Date.yesterday.between? Date.yesterday, Date.tomorrow
</code>```

答:
The cause is undoubtedly due to the resolution of the time function.  Sometimes the two instances of 2.weeks.ago resolve to the same time and sometimes they don't.  When you use yesterday you don't see the issue because it always resolves to zero hour instead of relative to the current time.

In a case like yours you probably only want to compare the date, not the date and time.

OwnerDisplayName: Jaryl

Body:
Open up a Rails console and enter this:

2.weeks.ago.between? 2.weeks.ago, 1.week.ago

Did it give you true or false? No really, try it a few more times and it will give you different answers.

Now, I'm thinking that because we're comparing 2.weeks.ago with 2.weeks.ago, the time between evaluating the two statements is causing this behavior.

I can't say for sure, but I am guessing that the between? method is not inclusive and so if a few milliseconds elapsed between the two statements, the above code will evaluate to true because it will be in between the two dates compared.

However, if the CPU manages to process this quickly enough such that the time elapsed is ignorable, then it will evaluate to false.

Can anyone shed some light on this? It is an edge case at best in a system where this might be critical, but it was giving me a headache when my tests passed and failed seemingly at random.

Oddly enough, this doesn't happen when doing:

 Date.yesterday.between? Date.yesterday, Date.tomorrow

LastEditorDisplayName: Jaryl

OwnerDisplayName: tvanfosson


问:
Load Image and video from url
I'm having troubles when I have to Load image from url. I get this url on a response from a POST to server.

So I have the POST funtion below:

```<code>public void getDataStruct()
{

    string url = " myurl";

    WWWForm form = new WWWForm();
    form.AddField("id", "2");
    WWW www = new WWW(url, form);

    StartCoroutine(WaitForRequest(www));
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;

    // check for errors
    if (www.error == null)
    {
        Data[] jsonData = JsonHelper.FromJson<Data>(www.text);

        for (int i = 0; i < jsonData.Length; i++)
        {
            switch(jsonData[i].tipo)
            {
            //Image
            case 0:

                GameObject plno = GameObject.Find ("Plane").gameObject;
                LoadImageFromUrl planeScript = (LoadImageFromUrl)plno.GetComponent (typeof(LoadImageFromUrl));
                planeScript.url = jsonData[i].url;

                break;

                //video
            case 1:
                GameObject video = GameObject.Find ("Video1").gameObject;
                VideoPlaybackBehaviour videocript = (VideoPlaybackBehaviour)video.GetComponent(typeof(VideoPlaybackBehaviour));
                videocript.youtubeVideoIdOrUrl=jsonData[i].url;
                break;

            case 2:
                break;
            }
        }

    }
    else {
        MobileNativeMessage msg = new MobileNativeMessage("Error", "Error");
    }
}
</code>```

I don't know why but when I do this the image/video don't show..its because that render code is inside the request function? I tested without having to POST and I just hardcoded the urls and works.

the LoadFunction:

```<code>public class LoadImageFromUrl : MonoBehaviour {

    public string url;

    // Use this for initialization
    IEnumerator Start () {
        Texture2D tex;
        tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
        WWW www = new WWW(url);
        yield return www;
        www.LoadImageIntoTexture(tex);
        GetComponent<Renderer>().material.mainTexture = tex;
    }
}
</code>```

答:
```<code>GameObject plno = GameObject.Find ("Plane").gameObject;
            LoadImageFromUrl planeScript = (LoadImageFromUrl)plno.GetComponent (typeof(LoadImageFromUrl));
            planeScript.url = jsonData[i].url;
</code>```

You assign the url, now you must call download coroutine from LoadImageFromUrl  component. Change your class to something like this:

```<code>public class LoadImageFromUrl : MonoBehaviour {

public string url;

public void Download()
{
    StartCoroutine(DownloadRoutine());
}

// Use this for initialization
IEnumerator DownloadRoutine () {
    Texture2D tex;
    tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
    WWW www = new WWW(url);
    yield return www;
    www.LoadImageIntoTexture(tex);
    GetComponent<Renderer>().material.mainTexture = tex;
}
}
</code>```

And add

```<code>planeScript.Download()
</code>```

after

```<code>planeScript.url = jsonData[i].url;
</code>```

Same with video

Title: Load Image and video from url

Body:
I'm having troubles when I have to Load image from url. I get this url on a response from a POST to server.

So I have the POST funtion below:

public void getDataStruct()
{

    string url = " myurl";

    WWWForm form = new WWWForm();
    form.AddField("id", "2");
    WWW www = new WWW(url, form);

    StartCoroutine(WaitForRequest(www));
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;

    // check for errors
    if (www.error == null)
    {
        Data[] jsonData = JsonHelper.FromJson<Data>(www.text);

        for (int i = 0; i < jsonData.Length; i++)
        {
            switch(jsonData[i].tipo)
            {
            //Image
            case 0:

                GameObject plno = GameObject.Find ("Plane").gameObject;
                LoadImageFromUrl planeScript = (LoadImageFromUrl)plno.GetComponent (typeof(LoadImageFromUrl));
                planeScript.url = jsonData[i].url;

                break;

                //video
            case 1:
                GameObject video = GameObject.Find ("Video1").gameObject;
                VideoPlaybackBehaviour videocript = (VideoPlaybackBehaviour)video.GetComponent(typeof(VideoPlaybackBehaviour));
                videocript.youtubeVideoIdOrUrl=jsonData[i].url;
                break;

            case 2:
                break;
            }
        }

    }
    else {
        MobileNativeMessage msg = new MobileNativeMessage("Error", "Error");
    }
}

I don't know why but when I do this the image/video don't show..its because that render code is inside the request function? I tested without having to POST and I just hardcoded the urls and works.

the LoadFunction:

public class LoadImageFromUrl : MonoBehaviour {

    public string url;

    // Use this for initialization
    IEnumerator Start () {
        Texture2D tex;
        tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
        WWW www = new WWW(url);
        yield return www;
        www.LoadImageIntoTexture(tex);
        GetComponent<Renderer>().material.mainTexture = tex;
    }
}

Body:
GameObject plno = GameObject.Find ("Plane").gameObject;
            LoadImageFromUrl planeScript = (LoadImageFromUrl)plno.GetComponent (typeof(LoadImageFromUrl));
            planeScript.url = jsonData[i].url;

You assign the url, now you must call download coroutine from LoadImageFromUrl  component. Change your class to something like this:

public class LoadImageFromUrl : MonoBehaviour {

public string url;

public void Download()
{
    StartCoroutine(DownloadRoutine());
}

// Use this for initialization
IEnumerator DownloadRoutine () {
    Texture2D tex;
    tex = new Texture2D(4, 4, TextureFormat.DXT1, false);
    WWW www = new WWW(url);
    yield return www;
    www.LoadImageIntoTexture(tex);
    GetComponent<Renderer>().material.mainTexture = tex;
}
}

And add

planeScript.Download()

after

planeScript.url = jsonData[i].url;

Same with video


问:
Dynamically display JSON object in descending order in blade template
I'm trying to display a JSON object in descending order that is returned to my blade template that should look the output below

```<code>2007 | 30 | 28 | 5 | 2 | -10
2008 | 55 | 43 | 23 | 0.5 | -1
</code>```

JSON looks like this

```<code>{
    "2007":{
        "number-xx" : "5",
        "number-aa" : "30",
        "number-ef" : "2",
        "number-sa" : "-10",
        "number-ab" : "28",
    },
    "2008":{
        "number-xx" : "-1",
        "number-aa" : "0.5",
        "number-ef" : "23",
        "number-sa" : "55",
        "number-ab" : "43",
    }
}
</code>```

So far I have something like this that shows the year and the numbers if I manually declare them so I can't really set it in descending order.

```<code>@foreach ($data['quilt_data_obj'] as $year => $obj)
    {{ $year }} | {{ $obj['number-xx'] }} | {{ $obj['number-aa'] }} | {{ $obj['number-ef'] }} | {{ $obj['number-sa'] }} | {{ $obj['number-ab'] }}
@endforeach
</code>```

But I'm just not sure how I can get it to show the numbers dynamically in descending order in my blade template.

Any guidance would be appreciated. Thank you!

答:
Before the JSON gets sent to the blade template, mutate it in your controller:

```<code>$data = json_decode($json, true);
foreach($data as $key => &$arr) {
   natsort($arr);
   $arr = array_reverse($arr);
}
</code>```

Keys will be maintained in this way. Natsort will handle negative numbers and decimals, and array reverse will make it highest to lowest.

Body:
I'm trying to display a JSON object in descending order that is returned to my blade template that should look the output below

2007 | 30 | 28 | 5 | 2 | -10
2008 | 55 | 43 | 23 | 0.5 | -1

JSON looks like this

{
    "2007":{
        "number-xx" : "5",
        "number-aa" : "30",
        "number-ef" : "2",
        "number-sa" : "-10",
        "number-ab" : "28",
    },
    "2008":{
        "number-xx" : "-1",
        "number-aa" : "0.5",
        "number-ef" : "23",
        "number-sa" : "55",
        "number-ab" : "43",
    }
}

So far I have something like this that shows the year and the numbers if I manually declare them so I can't really set it in descending order.

@foreach ($data['quilt_data_obj'] as $year => $obj)
    {{ $year }} | {{ $obj['number-xx'] }} | {{ $obj['number-aa'] }} | {{ $obj['number-ef'] }} | {{ $obj['number-sa'] }} | {{ $obj['number-ab'] }}
@endforeach

But I'm just not sure how I can get it to show the numbers dynamically in descending order in my blade template.

Any guidance would be appreciated. Thank you!

Body:
Before the JSON gets sent to the blade template, mutate it in your controller:

$data = json_decode($json, true);
foreach($data as $key => &$arr) {
   natsort($arr);
   $arr = array_reverse($arr);
}

Keys will be maintained in this way. Natsort will handle negative numbers and decimals, and array reverse will make it highest to lowest.


问:
Node child_process mute, read and handle children logs within parent
I have a parent script that spawns children nodes.

```<code>let child = child_process.fork('foo.js', ['param1', param2])
child.on('message', data => {
//  console.log(data);
})
child.on('exit', code => {
  resolve(true)
})
</code>```

Originally I thought that child.on('message') event listener catches and handles message but that's not the case here. Children simply uses parent process.stdout.write function and log stuff to parent console by default.

Is there a way to read these logs and parse them within parent?

答:
you can set silent to true on the child fork and listen for the stdout pipe. </p>

```<code>fork('./foo.js',{silent: true})
    .stdout.on('data', data => console.log(data.toString()));
</code>```

Body:
I have a parent script that spawns children nodes.

let child = child_process.fork('foo.js', ['param1', param2])
child.on('message', data => {
//  console.log(data);
})
child.on('exit', code => {
  resolve(true)
})

Originally I thought that child.on('message') event listener catches and handles message but that's not the case here. Children simply uses parent process.stdout.write function and log stuff to parent console by default.

Is there a way to read these logs and parse them within parent?

Body:
you can set silent to true on the child fork and listen for the stdout pipe.

fork('./foo.js',{silent: true})
    .stdout.on('data', data => console.log(data.toString()));


问:
Unable to deploy WAR in an EAR on WebLogic
I have a web application running on JSF 2.2 on WebLogic Application server 12.2.1.1.

I have a simple java class and trying to initialize it as an ApplicationScoped object using CDI. This gets deployed perfectly fine as a WAR.

```<code>import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

@Named
@ApplicationScoped
public class AppContext {
    public AppContext() {
    }
}
</code>```

However, when I add this WAR to an EAR it fails to deploy. I am trying all possible solutions and nothing seems to work at this point. The exception log is as below:

```<code>weblogic.management.DeploymentException: CDI deployment failure:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]:org.jboss.weld.exceptions.DeploymentException:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]
    at org.jboss.weld.bootstrap.Validator.validateBeanNames(Validator.java:641)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:487)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:446)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:150)
    Truncated. see log file for complete stacktrace
</code>```

Also WEB-INF\beans.xml is as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
</code>```

Application Running On:

```<code>NetBeans IDE 8.2;
JDK 1.8 b121;
Mojarra JSF 2.2;
WebLogic 12.2.1.1;
</code>```

Any hint on fixing this issue is highly appreciated.

答:
IMHO: This looks like an issue from the context initialization perspective, i.e., The EAR classloader loads the bean into the context and the WAR also loads the bean into the context again. Please check this blog CDI in EARs, for understanding it more clearly. Some of the J2EE servers manages this by their own. Please check the way your application is packaged and also check the way how it is deployed.

Additional information to understand about the class loading check here:

Understanding WebLogic Server Application Classloading

Application.xml WAR EJB.jar Module order can cause ClassLoader issues

Body:
I have a web application running on JSF 2.2 on WebLogic Application server 12.2.1.1.

I have a simple java class and trying to initialize it as an ApplicationScoped object using CDI. This gets deployed perfectly fine as a WAR.

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;

@Named
@ApplicationScoped
public class AppContext {
    public AppContext() {
    }
}

However, when I add this WAR to an EAR it fails to deploy. I am trying all possible solutions and nothing seems to work at this point. The exception log is as below:

weblogic.management.DeploymentException: CDI deployment failure:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]:org.jboss.weld.exceptions.DeploymentException:WELD-001414: Bean name is ambiguous. Name appContext resolves to beans: [Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named], Managed Bean [class beans.AppContext] with qualifiers [@Default @Any @Named]]
    at org.jboss.weld.bootstrap.Validator.validateBeanNames(Validator.java:641)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:487)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:446)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at com.oracle.injection.provider.weld.WeldInjectionContainer.start(WeldInjectionContainer.java:150)
    Truncated. see log file for complete stacktrace

Also WEB-INF\beans.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Application Running On:

NetBeans IDE 8.2;
JDK 1.8 b121;
Mojarra JSF 2.2;
WebLogic 12.2.1.1;

Any hint on fixing this issue is highly appreciated.


问:
Is there a way to square off line margins in histogram plot in R?
I made a histogram plot in R using plot(type = 'h').

```<code>plot(type='h', y =runif(1:10), x = 1:10,lwd = 20,lty=7)
</code>```

I want the vertical bars to be thick, so I increase lwd.
However, the larger "bars" (really, they're lines) have rounded edges:

Is there a way to make these "bars" (i.e., lines) have square/straight edges?

I've gone through the plot documentation numerous times and couldn't find a solution. No SE or Google Searches turned up anything either...

答:
Use lend = 1.

```<code>plot(type='h', y =runif(1:10), x = 1:10,lwd = 20,l ty = 7, lend = 1)
</code>```

And output

Body:
I made a histogram plot in R using plot(type = 'h').

plot(type='h', y =runif(1:10), x = 1:10,lwd = 20,lty=7)

I want the vertical bars to be thick, so I increase lwd.
However, the larger "bars" (really, they're lines) have rounded edges:

Is there a way to make these "bars" (i.e., lines) have square/straight edges?

I've gone through the plot documentation numerous times and couldn't find a solution. No SE or Google Searches turned up anything either...

Body:
Use lend = 1.

plot(type='h', y =runif(1:10), x = 1:10,lwd = 20,l ty = 7, lend = 1)

And output


问:
Adding to local storage only working after refreshing the page after button navigation to another page
I am developing an app that allows user to search for fishing lakes in their area. To do this they can type in their location which then displays fisheries near them that i have identified in the Json data. The search works perfectly with the code below i have written (i know it maybe a little flaky as i am not the best programmer).

```<code>//search
$(document).ready(function(){
    $('#exampleSearch').keyup(function() {
        var searchVal = $('#exampleSearch').val();
        $('#results').empty();
        console.log(searchVal);
        var results = [];
        $.getJSON("/data/locations.json",function(locations) {
            for (var i = 0; i < locations.length; i++) {
                if (locations[i].location.match(searchVal)) {
                    results.push(locations[i]);
                }
            }

            $.each(results, function(index,result) {
                var $resultsLi = $(
                    '<div class="row">'+
                    '<div class="twelve columns profile-information ">'+
                    '<div class="profile-title">'+
                    '<h6>'+result.name+'</h6>'+
                    '</div> ' +
                    ' <img class= "favourites-pic" src="'+ result.image +'" alt="Fishery">'+
                    '<a class="view" href="'+ result.url + '" >View</a>'+
                    '</div>'+
                    ' </div>'
                )
                $("#results").append($resultsLi);
            });
        });
    });
});
</code>```

I have now added a feature where users can now add their search results to their favourites page, by click a Add to favorites button on the page of the fishery they found from their search with the following code:

Javascript:

```<code>//Add to Favourites
$(function() {
    $( ".addFavourites" ).on("click", function() {
        try {
            $(this).attr('disabled', true);

            var locIdToAdd = $(this).closest("p").attr("id");

            var myFavouriteLoc=JSON.parse(localStorage.getItem("favLoc"));

            if (myFavouriteLoc == null) {
                myFavouriteLoc = [];
            }

            if (myFavouriteLoc != null) {
                for ( var j = 0; j < myFavouriteLoc.length; j++) {
                    if ( locIdToAdd == myFavouriteLoc[j]) {
                        alert("This property is already in your favourites");
                        myFavouriteLoc = [];
                    }
                }
            }

            myFavouriteLoc.push(locIdToAdd);

            localStorage.setItem("favLoc", JSON.stringify(myFavouriteLoc));

        } catch (e) {
            if (e == QUOTA_EXCEEDED_ERR) {
                console.log("Error: Local storage limit exceeds");
            } else {
                console.log("ERROR: Saving to local storge.");
            }
        }
    });
});
</code>```

Html:

```<code><p id="loc 1">
    <input class="button-primary green addFavourites" type="submit" value="Add to Favourites">
</p>
</code>```

THE PROBLEM

Upon clicking the 'view' button on the search page results, and navigating to a fishery page. I have a problem where i have to then refresh the page again before the add to favourites button will add anything to the local storage, it is clickable, but nothing happens. once i refresh the page it works fine.

Can anyone help with why i have to refresh the page first? any help is a appreciated :)

答:
Try this jquery code to add favorites, it should work on each click:

```<code>$( document ).on("click", ".addFavourites", function(e) {
    e.preventDefault();
    try {
        $(this).attr('disabled', true);

        var locIdToAdd = $(this).closest("p").attr("id");

        var myFavouriteLoc=JSON.parse(localStorage.getItem("favLoc"));

        if (myFavouriteLoc == null) {
            myFavouriteLoc = [];
        }

        if (myFavouriteLoc != null) {
            for ( var j = 0; j < myFavouriteLoc.length; j++) {
                if ( locIdToAdd == myFavouriteLoc[j]) {
                    alert("This property is already in your favourites");
                    myFavouriteLoc = [];
                }
            }
        }

        myFavouriteLoc.push(locIdToAdd);

        localStorage.setItem("favLoc", JSON.stringify(myFavouriteLoc));

    } catch (e) {
        if (e == QUOTA_EXCEEDED_ERR) {
            console.log("Error: Local storage limit exceeds");
        } else {
            console.log("ERROR: Saving to local storge.");
        }
    }
});
</code>```

Just make sure you are not putting this jquery function inside $(document).ready(function(){}) or $(function(){}) because it is not required

Body:
I am developing an app that allows user to search for fishing lakes in their area. To do this they can type in their location which then displays fisheries near them that i have identified in the Json data. The search works perfectly with the code below i have written (i know it maybe a little flaky as i am not the best programmer).

//search
$(document).ready(function(){
    $('#exampleSearch').keyup(function() {
        var searchVal = $('#exampleSearch').val();
        $('#results').empty();
        console.log(searchVal);
        var results = [];
        $.getJSON("/data/locations.json",function(locations) {
            for (var i = 0; i < locations.length; i++) {
                if (locations[i].location.match(searchVal)) {
                    results.push(locations[i]);
                }
            }

            $.each(results, function(index,result) {
                var $resultsLi = $(
                    '
'+
                    '
'+
                    '
'+
                    '
'+result.name+'
'+
                    '
 ' +
                    ' '+
                    'View'+
                    '
'+
                    '
'
                )
                $("#results").append($resultsLi);
            });
        });
    });
});

I have now added a feature where users can now add their search results to their favourites page, by click a Add to favorites button on the page of the fishery they found from their search with the following code:

Javascript:

//Add to Favourites
$(function() {
    $( ".addFavourites" ).on("click", function() {
        try {
            $(this).attr('disabled', true);

            var locIdToAdd = $(this).closest("p").attr("id");

            var myFavouriteLoc=JSON.parse(localStorage.getItem("favLoc"));

            if (myFavouriteLoc == null) {
                myFavouriteLoc = [];
            }

            if (myFavouriteLoc != null) {
                for ( var j = 0; j < myFavouriteLoc.length; j++) {
                    if ( locIdToAdd == myFavouriteLoc[j]) {
                        alert("This property is already in your favourites");
                        myFavouriteLoc = [];
                    }
                }
            }

            myFavouriteLoc.push(locIdToAdd);

            localStorage.setItem("favLoc", JSON.stringify(myFavouriteLoc));

        } catch (e) {
            if (e == QUOTA_EXCEEDED_ERR) {
                console.log("Error: Local storage limit exceeds");
            } else {
                console.log("ERROR: Saving to local storge.");
            }
        }
    });
});

Html:

    <input class="button-primary green addFavourites" type="submit" value="Add to Favourites">

THE PROBLEM

Upon clicking the 'view' button on the search page results, and navigating to a fishery page. I have a problem where i have to then refresh the page again before the add to favourites button will add anything to the local storage, it is clickable, but nothing happens. once i refresh the page it works fine.

Can anyone help with why i have to refresh the page first? any help is a appreciated :)

Body:
Try this jquery code to add favorites, it should work on each click:

$( document ).on("click", ".addFavourites", function(e) {
    e.preventDefault();
    try {
        $(this).attr('disabled', true);

        var locIdToAdd = $(this).closest("p").attr("id");

        var myFavouriteLoc=JSON.parse(localStorage.getItem("favLoc"));

        if (myFavouriteLoc == null) {
            myFavouriteLoc = [];
        }

        if (myFavouriteLoc != null) {
            for ( var j = 0; j < myFavouriteLoc.length; j++) {
                if ( locIdToAdd == myFavouriteLoc[j]) {
                    alert("This property is already in your favourites");
                    myFavouriteLoc = [];
                }
            }
        }

        myFavouriteLoc.push(locIdToAdd);

        localStorage.setItem("favLoc", JSON.stringify(myFavouriteLoc));

    } catch (e) {
        if (e == QUOTA_EXCEEDED_ERR) {
            console.log("Error: Local storage limit exceeds");
        } else {
            console.log("ERROR: Saving to local storge.");
        }
    }
});

Just make sure you are not putting this jquery function inside $(document).ready(function(){}) or $(function(){}) because it is not required


问:
Wrong number or types of arguments when calling a procedure in WCF service
I'm sort of having a hard time with this one. Well ok, I have two different solutions (solution1 has a WebApplication Project; solution2 has a Website Project). Inside the two solutions, there's a WCF service structure. I have the exact same code in both services (in their respective solutions). My code compiles just fine. From the service I do a simple call to a procedure that returns a cursor. When I execute the service from the WebApplication it works just fine; when I do the same from the Website I get error: "wrong number or types of arguments". They both call the same procedure, in the same DB. And I triple check my code, and is the same in both services. Any ideas or suggestions? My code is as follows in both solutions:
Service.cs

```<code>public List<A1001310> SearchClient_A1001310()
    {
        DataTable dataTable = new DataTable();
        dataTable = DataManager.SearchClient();

        List<A1001310> list = new List<A1001310>();
        list = (from DataRow dr in dataTable.Rows
                select new A1001310()
                {
                    Id = Convert.ToInt32(dr["CLIENT_ID"]),
                    //ClientName = dr["NOM_CLIENTE"].ToString()
                }).ToList();
        return list;
    }
</code>```

DataManager.cs

```<code>public static DataTable SearchClient()
    {
        try
        {
            using (OleDbCommand cmd = new OleDbCommand(packetName + ".select_A1001310"))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                SqlManager sqlManager = new SqlManager();
                return sqlManager.GetDataTable(cmd);
            }
        }
        catch (Exception ex)
        {
            //TODO; Handle exception
        }
        return null;
    }
</code>```

The call to DataTable is:

```<code>public DataTable GetDataTable(OleDbCommand cmd)
    {
        using (DataSet ds = GetDataSet(cmd))
        {
            return ((ds != null && ds.Tables.Count > 0) ? ds.Tables[0] : null);
        }
    }

public DataSet GetDataSet(OleDbCommand cmd)
    {
        using (DataSet ds = new DataSet())
        {
            this.ConvertToNullBlankParameters(cmd);

            using (OleDbConnection conn = new OleDbConnection(cmd.Connection == null ? _dbConnection : cmd.Connection.ConnectionString))
            {
                cmd.Connection = conn;
                cmd.CommandTimeout = _connTimeout;

                conn.Open();
                //cmd.ExecuteScalar();

                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                    da.Fill(ds);
            }
            return ds;
        }
    }
</code>```

The procedure is as follow:

```<code>    PROCEDURE select_A1001310(io_cursor OUT lcursor_data)
  AS
  BEGIN
    OPEN io_cursor FOR
    --
      SELECT client_id
        FROM a1001310
       WHERE status = 'A'
    --
  EXCEPTION
    WHEN OTHERS THEN
      IF io_cursor%ISOPEN THEN
        CLOSE io_cursor;
      END IF;
    --REVIRE: EXCEPTION HANDLER
  END select_A1001310;
</code>```

答:
So if it helps anyone, I resolved my issue by specifying the OUT parameter declared in the procedure. This resulted in me changing from Oledb to OracleClient as follow:

```<code>public static DataTable SearchClient()
    {
        string connection = ConfigurationManager.ConnectionStrings["DBConnection_Oracle"].ToString();
        string procedure = packetName + ".p_search_client";

        OracleParameter[] parameters = new OracleParameter[1];
        parameters[0] = new OracleParameter("io_cursor", OracleType.Cursor, 4000, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Current, String.Empty);

        DataTable dt = new DataTable();
        dt = DataManager_Oracle.GetDataTable_(connection, procedure, parameters);
        return dt;
    }
</code>```

It seems that on the Website environment it didn't like leaving out the OUT parameter; whereas on the WebApplication I did not specify it, and it worked just fine... If some one know the why , PLEASE let me know :)

Body:
I'm sort of having a hard time with this one. Well ok, I have two different solutions (solution1 has a WebApplication Project; solution2 has a Website Project). Inside the two solutions, there's a WCF service structure. I have the exact same code in both services (in their respective solutions). My code compiles just fine. From the service I do a simple call to a procedure that returns a cursor. When I execute the service from the WebApplication it works just fine; when I do the same from the Website I get error: "wrong number or types of arguments". They both call the same procedure, in the same DB. And I triple check my code, and is the same in both services. Any ideas or suggestions? My code is as follows in both solutions:
Service.cs

public List<A1001310> SearchClient_A1001310()
    {
        DataTable dataTable = new DataTable();
        dataTable = DataManager.SearchClient();

        List<A1001310> list = new List<A1001310>();
        list = (from DataRow dr in dataTable.Rows
                select new A1001310()
                {
                    Id = Convert.ToInt32(dr["CLIENT_ID"]),
                    //ClientName = dr["NOM_CLIENTE"].ToString()
                }).ToList();
        return list;
    }

DataManager.cs

public static DataTable SearchClient()
    {
        try
        {
            using (OleDbCommand cmd = new OleDbCommand(packetName + ".select_A1001310"))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                SqlManager sqlManager = new SqlManager();
                return sqlManager.GetDataTable(cmd);
            }
        }
        catch (Exception ex)
        {
            //TODO; Handle exception
        }
        return null;
    }

The call to DataTable is:

public DataTable GetDataTable(OleDbCommand cmd)
    {
        using (DataSet ds = GetDataSet(cmd))
        {
            return ((ds != null && ds.Tables.Count > 0) ? ds.Tables[0] : null);
        }
    }

public DataSet GetDataSet(OleDbCommand cmd)
    {
        using (DataSet ds = new DataSet())
        {
            this.ConvertToNullBlankParameters(cmd);

            using (OleDbConnection conn = new OleDbConnection(cmd.Connection == null ? _dbConnection : cmd.Connection.ConnectionString))
            {
                cmd.Connection = conn;
                cmd.CommandTimeout = _connTimeout;

                conn.Open();
                //cmd.ExecuteScalar();

                using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
                    da.Fill(ds);
            }
            return ds;
        }
    }

The procedure is as follow:

    PROCEDURE select_A1001310(io_cursor OUT lcursor_data)
  AS
  BEGIN
    OPEN io_cursor FOR
    --
      SELECT client_id
        FROM a1001310
       WHERE status = 'A'
    --
  EXCEPTION
    WHEN OTHERS THEN
      IF io_cursor%ISOPEN THEN
        CLOSE io_cursor;
      END IF;
    --REVIRE: EXCEPTION HANDLER
  END select_A1001310;

Body:
So if it helps anyone, I resolved my issue by specifying the OUT parameter declared in the procedure. This resulted in me changing from Oledb to OracleClient as follow:

public static DataTable SearchClient()
    {
        string connection = ConfigurationManager.ConnectionStrings["DBConnection_Oracle"].ToString();
        string procedure = packetName + ".p_search_client";

        OracleParameter[] parameters = new OracleParameter[1];
        parameters[0] = new OracleParameter("io_cursor", OracleType.Cursor, 4000, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Current, String.Empty);

        DataTable dt = new DataTable();
        dt = DataManager_Oracle.GetDataTable_(connection, procedure, parameters);
        return dt;
    }

It seems that on the Website environment it didn't like leaving out the OUT parameter; whereas on the WebApplication I did not specify it, and it worked just fine... If some one know the why , PLEASE let me know :)


问:
R: Assign variable labels of data frame columns
I am struggling with variable labels of data.frame columns. Say I have the following data frame (part of much larger data frame):

```<code>data <- data.frame(age = c(21, 30, 25, 41, 29, 33), sex = factor(c(1, 2, 1, 2, 1, 2), labels = c("Female", "Male")))
#
</code>```

I also have a named vector with the variable labels for this data frame:

```<code>var.labels <- c(age = "Age in Years", sex = "Sex of the participant")
</code>```

I want to assign the variable labels in var.labels to the columns in the data frame data using the function label from the Hmisc package. I can do them one by one like this and check the result afterwards:

```<code>> label(data[["age"]]) <- "Age in years"
> label(data[["sex"]]) <- "Sex of the participant"
> label(data)
                 age                      sex
      "Age in years" "Sex of the participant"
</code>```

The variable labels are assigned as attributes of the columns:

```<code>> attr(data[["age"]], "label")
[1] "Age in years"
> attr(data[["sex"]], "label")
[1] "Sex of the participant"
</code>```

Wonderful. However, with a larger data frame, say 100 or more columns, this will not be convenient or efficient. Another option is to assign them as attributes directly:

```<code>> attr(data, "variable.labels") <- var.labels
</code>```

Does not help. The variable labels are not assigned to the columns:

```<code>> label(data)
age sex
 ""  ""
</code>```

Instead, they are assigned as an attribute of the data frame itself (see the last component of the list):

```<code>> attributes(data)
$names
[1] "age" "sex"

$row.names
[1] 1 2 3 4 5 6

$class
[1] "data.frame"

$variable.labels
                 age                      sex
      "Age in Years" "Sex of the participant"
</code>```

And this is not what I want. I need the variable labels as attributes of the columns. I tried to write the following function (and many others):

```<code>set.var.labels <- function(dataframe, label.vector){
  column.names <- names(dataframe)
  dataframe <- mapply(label, column.names, label.vector)
  return(dataframe)
}
</code>```

And then execute it:

```<code>> set.var.labels(data, var.labels)
</code>```

Did not help. It returns the values of the vector var.labels but does not assign the variable labels. If I try to assign it to a new object, it just contains the values of the variable labels as a vector.

答:
If your vector of labels matches the order of your data.frame columns, but isn't a named vector (so can't be used to subset data.frame columns by name like the lapply approach in the other answer), you can use a for-loop:

```<code>for(i in seq_along(data)){
  Hmisc::label(data[, i]) <- var.labels[i]
}

label(data)
#>                      age                      sex
#>           "Age in Years" "Sex of the participant"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am struggling with variable labels of data.frame columns. Say I have the following data frame (part of much larger data frame):

data <- data.frame(age = c(21, 30, 25, 41, 29, 33), sex = factor(c(1, 2, 1, 2, 1, 2), labels = c("Female", "Male")))
#

I also have a named vector with the variable labels for this data frame:

var.labels <- c(age = "Age in Years", sex = "Sex of the participant")

I want to assign the variable labels in var.labels to the columns in the data frame data using the function label from the Hmisc package. I can do them one by one like this and check the result afterwards:

> label(data[["age"]]) <- "Age in years"
> label(data[["sex"]]) <- "Sex of the participant"
> label(data)
                 age                      sex
      "Age in years" "Sex of the participant"

The variable labels are assigned as attributes of the columns:

> attr(data[["age"]], "label")
[1] "Age in years"
> attr(data[["sex"]], "label")
[1] "Sex of the participant"

Wonderful. However, with a larger data frame, say 100 or more columns, this will not be convenient or efficient. Another option is to assign them as attributes directly:

> attr(data, "variable.labels") <- var.labels

Does not help. The variable labels are not assigned to the columns:

> label(data)
age sex
 ""  ""

Instead, they are assigned as an attribute of the data frame itself (see the last component of the list):

> attributes(data)
$names
[1] "age" "sex"

$row.names
[1] 1 2 3 4 5 6

$class
[1] "data.frame"

$variable.labels
                 age                      sex
      "Age in Years" "Sex of the participant"

And this is not what I want. I need the variable labels as attributes of the columns. I tried to write the following function (and many others):

set.var.labels <- function(dataframe, label.vector){
  column.names <- names(dataframe)
  dataframe <- mapply(label, column.names, label.vector)
  return(dataframe)
}

And then execute it:

> set.var.labels(data, var.labels)

Did not help. It returns the values of the vector var.labels but does not assign the variable labels. If I try to assign it to a new object, it just contains the values of the variable labels as a vector.

Body:
If your vector of labels matches the order of your data.frame columns, but isn't a named vector (so can't be used to subset data.frame columns by name like the lapply approach in the other answer), you can use a for-loop:

for(i in seq_along(data)){
  Hmisc::label(data[, i]) <- var.labels[i]
}

label(data)
#>                      age                      sex
#>           "Age in Years" "Sex of the participant"


问:
Java Proxy is not sending anything back to browser
I have created a proxy server in Java, (See code below), the thing is, I'm getting response back from the web-server however my client-side of the proxy which handles the connections between clients(browser) and the web-server after a socket has been created with the server side of the proxy. The server side creates a client  and sends the request and socket and this is then handled in a new thread.
I have a few questions:

First Code is of the Client-side of the proxy second code part is of the Server-side of the proxy

What type of streams should I use when sending data between browser/proxy/webserver?

Is it fine to use a String or should I use some type of byte array when sending and receiving from streams?

Why is the browser not receiving anything from the proxy? Since I can print it out from the console but when writing to the stream nothing happens in the browser.

Also, why do I need to click "enter" twice in the browser for the proxy to react?

```<code>public class Client implements Runnable {

private String request;
private String response;
private Socket browserSocket;

public Client(String request, Socket browserSocket) {
    this.request = request;
    this.response = "";
    this.browserSocket = browserSocket;

}

@Override
public void run() {
    /* Send request to web server and get the response. */
    this.request = Client.modifyHttpHeader("Connection", "close", this.request);
    String hostName = Client.getHttpHeader("Host", this.request);
    if (!hostName.isEmpty()) {
        try {
            /* Send request to the web-server. */
            Socket socket = new Socket(hostName, 80);
            OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
            PrintWriter pw = new PrintWriter(osw);
            pw.write(this.request);
            pw.flush();

            System.out.println("---S:REQUEST---");
            System.out.println(this.request);
            System.out.println("---S:REQUEST---");

            /* Receive the response from the web-server. */
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String response = "";
            int tmpData;
            while ((tmpData = br.read()) != -1) {
                response += (char)tmpData;
            }
            this.response = response;
            socket.close(); /* Close the socket between client-side and web-server. */

            /* Send the response back to the browser. */
            OutputStreamWriter oswbrowser = new OutputStreamWriter(this.browserSocket.getOutputStream());
            PrintWriter pwBrowser = new PrintWriter(oswbrowser);
            pwBrowser.write(this.response);
            pwBrowser.flush();
            pwBrowser.close();

            this.browserSocket.close(); /* Close the socket between client-side and browser. */

            System.out.println("---C:RESPONSE---");
            System.out.println(this.response);
            System.out.println("---C:RESPONSE---");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
public String getHttpResponse() {
    return this.response;
}

/**
 *
 * @param header
 * The name of the HTTP header. Example: "GET".
 * Note: Header name is case sensitive.
 * @param request
 * The HTTP message.
 * @return
 * On success: The value following the HTTP header ": " (colon and whitespace).
 * On failure: Empty string.
 */
public static String getHttpHeader(String header, String request) {

    int startHeaderIndex = request.indexOf(header) + header.length();
    int endHeaderIndex = request.indexOf('\n', startHeaderIndex);

    /* Could not find the searched header. */
    if (startHeaderIndex == -1 || endHeaderIndex == -1)
        return "";

    /* Add 2 to remove ':' and ' '(white space). Decrement 1 to exclude '\r' and '\n' */
    return request.substring(startHeaderIndex + 2, endHeaderIndex - 1);
}

/**
 *
 * @param header
 * The name of the HTTP header. Example: "Connection"
 * Note: The header is case sensitive.
 * @param value
 * The new value you want to put. Example: "Close"
 * @param request
 * The HTTP message.
 * @return
 * On success: A new HTTP request with the modified header value.
 * On failure: Empty string.
 *
 */
public static String modifyHttpHeader(String header, String value, String request) {
    int startHeaderIndex = request.indexOf(header) + header.length();
    int endHeaderIndex = request.indexOf('\n', startHeaderIndex);

    /* Could not find the searched header. */
    if (startHeaderIndex == -1 || endHeaderIndex == -1)
        return "";

    String newRequest = "";
    /* Copy all characters including ':' and ' ' (whitespace) */
    for (int i = 0; i < startHeaderIndex + 2; i++) {
        newRequest += request.charAt(i);
    }
    newRequest += value;
    newRequest += "\r\n";
    /* Add the rest of the request. */
    for (int i = endHeaderIndex + 1; i < request.length(); i++) {
        newRequest += request.charAt(i);
    }

    return newRequest;
}

}

 public class Server {

public static void main(String[] args) throws Exception{
    /* Receiving and parsing port number from command line arguments. */
    int ssPort = 0;
    if (args.length > 1 || args.length == 0){
        System.err.println("Only one argument allowed; port number (int).");
        System.exit(1);

    } else {
        try {
            ssPort = Integer.parseInt(args[0]);
        } catch(NumberFormatException exception) {
            System.err.println("Argument \"" + args[0] + "\" must be a number.");
            System.exit(1);
        }
    }
    ServerSocket serverSocket = new ServerSocket(ssPort); /* Creating the server socket. */
    System.out.println("Proxy running on port: " + ssPort);

    while(true) {
        System.out.println("Waiting for client...");
        Socket clientSocket = serverSocket.accept(); /* Listening for connections. */
        BufferedReader bReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String request = "";
        int tmpData;
        while ((tmpData = bReader.read()) != -1) {
            request += (char)tmpData;
        }

        Client clientObject = new Client(request, clientSocket);
        Thread clientThread = new Thread(clientObject);
        clientThread.start(); /* Start the client thread. */
    }
}
</code>```

}

答:
Throw it all away. This isn't how proxies are written. An HTTP proxy should:

Read one line from the downstream client, to determine whom to connect to upstream, without buffering.

Connect upstream.

If (2) fails, send an appropriate HTTP response downstream and close the connection.

Otherwise, start copying bytes, in both directions, simultaneously.

You should not attempt to assemble the entire request, or even the headers, and the words 'bytes' and 'simultaneously' above are critical. Note that you don't have to do anything about HTTP keep-alive, Connection headers, HTTPS, etc.

Body:
I have created a proxy server in Java, (See code below), the thing is, I'm getting response back from the web-server however my client-side of the proxy which handles the connections between clients(browser) and the web-server after a socket has been created with the server side of the proxy. The server side creates a client  and sends the request and socket and this is then handled in a new thread.
I have a few questions:

First Code is of the Client-side of the proxy second code part is of the Server-side of the proxy

What type of streams should I use when sending data between browser/proxy/webserver?

Is it fine to use a String or should I use some type of byte array when sending and receiving from streams?

Why is the browser not receiving anything from the proxy? Since I can print it out from the console but when writing to the stream nothing happens in the browser.

Also, why do I need to click "enter" twice in the browser for the proxy to react?

public class Client implements Runnable {

private String request;
private String response;
private Socket browserSocket;

public Client(String request, Socket browserSocket) {
    this.request = request;
    this.response = "";
    this.browserSocket = browserSocket;

}

@Override
public void run() {
    /* Send request to web server and get the response. */
    this.request = Client.modifyHttpHeader("Connection", "close", this.request);
    String hostName = Client.getHttpHeader("Host", this.request);
    if (!hostName.isEmpty()) {
        try {
            /* Send request to the web-server. */
            Socket socket = new Socket(hostName, 80);
            OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
            PrintWriter pw = new PrintWriter(osw);
            pw.write(this.request);
            pw.flush();

            System.out.println("---S:REQUEST---");
            System.out.println(this.request);
            System.out.println("---S:REQUEST---");

            /* Receive the response from the web-server. */
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String response = "";
            int tmpData;
            while ((tmpData = br.read()) != -1) {
                response += (char)tmpData;
            }
            this.response = response;
            socket.close(); /* Close the socket between client-side and web-server. */

            /* Send the response back to the browser. */
            OutputStreamWriter oswbrowser = new OutputStreamWriter(this.browserSocket.getOutputStream());
            PrintWriter pwBrowser = new PrintWriter(oswbrowser);
            pwBrowser.write(this.response);
            pwBrowser.flush();
            pwBrowser.close();

            this.browserSocket.close(); /* Close the socket between client-side and browser. */

            System.out.println("---C:RESPONSE---");
            System.out.println(this.response);
            System.out.println("---C:RESPONSE---");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
public String getHttpResponse() {
    return this.response;
}

/**
 *
 * @param header
 * The name of the HTTP header. Example: "GET".
 * Note: Header name is case sensitive.
 * @param request
 * The HTTP message.
 * @return
 * On success: The value following the HTTP header ": " (colon and whitespace).
 * On failure: Empty string.
 */
public static String getHttpHeader(String header, String request) {

    int startHeaderIndex = request.indexOf(header) + header.length();
    int endHeaderIndex = request.indexOf('\n', startHeaderIndex);

    /* Could not find the searched header. */
    if (startHeaderIndex == -1 || endHeaderIndex == -1)
        return "";

    /* Add 2 to remove ':' and ' '(white space). Decrement 1 to exclude '\r' and '\n' */
    return request.substring(startHeaderIndex + 2, endHeaderIndex - 1);
}

/**
 *
 * @param header
 * The name of the HTTP header. Example: "Connection"
 * Note: The header is case sensitive.
 * @param value
 * The new value you want to put. Example: "Close"
 * @param request
 * The HTTP message.
 * @return
 * On success: A new HTTP request with the modified header value.
 * On failure: Empty string.
 *
 */
public static String modifyHttpHeader(String header, String value, String request) {
    int startHeaderIndex = request.indexOf(header) + header.length();
    int endHeaderIndex = request.indexOf('\n', startHeaderIndex);

    /* Could not find the searched header. */
    if (startHeaderIndex == -1 || endHeaderIndex == -1)
        return "";

    String newRequest = "";
    /* Copy all characters including ':' and ' ' (whitespace) */
    for (int i = 0; i < startHeaderIndex + 2; i++) {
        newRequest += request.charAt(i);
    }
    newRequest += value;
    newRequest += "\r\n";
    /* Add the rest of the request. */
    for (int i = endHeaderIndex + 1; i < request.length(); i++) {
        newRequest += request.charAt(i);
    }

    return newRequest;
}

}

 public class Server {

public static void main(String[] args) throws Exception{
    /* Receiving and parsing port number from command line arguments. */
    int ssPort = 0;
    if (args.length > 1 || args.length == 0){
        System.err.println("Only one argument allowed; port number (int).");
        System.exit(1);

    } else {
        try {
            ssPort = Integer.parseInt(args[0]);
        } catch(NumberFormatException exception) {
            System.err.println("Argument \"" + args[0] + "\" must be a number.");
            System.exit(1);
        }
    }
    ServerSocket serverSocket = new ServerSocket(ssPort); /* Creating the server socket. */
    System.out.println("Proxy running on port: " + ssPort);

    while(true) {
        System.out.println("Waiting for client...");
        Socket clientSocket = serverSocket.accept(); /* Listening for connections. */
        BufferedReader bReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String request = "";
        int tmpData;
        while ((tmpData = bReader.read()) != -1) {
            request += (char)tmpData;
        }

        Client clientObject = new Client(request, clientSocket);
        Thread clientThread = new Thread(clientObject);
        clientThread.start(); /* Start the client thread. */
    }
}

}