问:
how to remove this error in Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner
```<code>import java.sql.*;
import java.util.*;
import java.text.*;

public class DataInsertDemo1{

    public static void main(String kl[]) throws SQLException,Exception{
        String url="jdbc:oracle:thin:@localhost:1521:orcl";
        String driver="oracle.jdbc.OracleDriver";
        Class.forName(driver);
        Connection con=DriverManager.getConnection(url,"System","System1996");

        Scanner sc=new Scanner("System.in");
        System.out.println("enter person name");
        String name=sc.next();

        System.out.println("Enter DOP(dd-mm-yyyy):");
        String dop=sc.next();

        SimpleDateFormat sdf=new SimpleDateFormat("dd-mm-yyyy");
        java.util.Date udate=sdf.parse(dop);
        long l=udate.getTime();
        java.sql.Date sdate=new java.sql.Date(l);

        String sql="insert into userdate values(?,?)";

        PreparedStatement  ps=con.prepareStatement(sql);
        ps.setString(1,name);
        ps.setDate(2,sdate);

        int rc=ps.executeUpdate();

            if(rc == 0){
                System.out.println("Record not inserted");
            }
            else{
                System.out.println("record is inserted");
            }

    con.close();

    }
}
</code>```

答:
Change

```<code>new Scanner("System.in");
</code>```

to

```<code>new Scanner(System.in);
</code>```

You should also change

```<code>dd-mm-yyyy
</code>```

to

```<code>dd-MM-yyyy
</code>```

Body:
Change

new Scanner("System.in");

to

new Scanner(System.in);

You should also change

dd-mm-yyyy

to

dd-MM-yyyy


来源: stackexchange

问:
What does the `[4,5) notation mean when compile facebook sdk in Android?
In https://developers.facebook.com/docs/android/componentsdks, the syntax to add the facebook sdk is as the following:

```<code>compile 'com.facebook.android:facebook-core:[4,5)'
</code>```

How does [4, 5) work? I have not seen this syntax anywhere else.

Thanks

答:
It is a ivy syntax.

[4, 5) means 4 <= x < 5.

ContentLicense: CC BY-SA 3.0

Body:
In https://developers.facebook.com/docs/android/componentsdks, the syntax to add the facebook sdk is as the following:

compile 'com.facebook.android:facebook-core:[4,5)'

How does [4, 5) work? I have not seen this syntax anywhere else.

Thanks


问:
Show common part of 2 semitransparent objects?
I'm creating a math app that uses OpenGL to show several geometric 3D shapes. In some cases these shapes intersect and when this happen I want to show the intersecting part of each shape inside the other. As the both shapes are translucent, what I need is more or less something like this:

However, with 2 translucent spheres I get that result instead:

I know that, to achieve a correct transparency effect, the depth testing should be turned off before the transparent shapes are drawn. However this cause another side effect when a transparent shape is beyond another non transparent shape:

So, is there a way to show correctly the intersecting part of 2 volumetric shapes, each inside the other, without breaking the depth testing?

答:
So, is there a way to show (…) volumetric shapes

OpenGL (by itself) doesn't know about "volumes". It knows flat triangles, lines and points, which by pure happenstance also may cause rendering side effects like depth sorting by a depth buffer test.

Technically it is possible to chain a series of drawing and stencil buffer operations to perform CSG (constructive solid geometry); see ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node22.html for details.

However what you want to do is easier implemented through a simple raytracer executed in the fragment shader. Now raytracing by itself is a broad subject and you can fill books on it (actually lots of books have been written on the subject). It's probably best to refer to an example. In this case I refer to the following ShaderToy https://www.shadertoy.com/view/ldS3DW – a slightly stripped down version of that shader draws the kind of intersectional geometry you're interested in:

```<code>float sphere(vec3 ray, vec3 dir, vec3 center, float radius)
{
    vec3 rc = ray-center;
    float c = dot(rc, rc) - (radius*radius);
    float b = dot(dir, rc);
    float d = b*b - c;
    float t = -b - sqrt(abs(d));
    float st = step(0.0, min(t,d));
    return mix(-1.0, t, st);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = (-1.0 + 2.0*fragCoord.xy / iResolution.xy) *
        vec2(iResolution.x/iResolution.y, 1.0);

    vec3 ro = vec3(0.0, 0.0, -3.0);
    vec3 rd = normalize(vec3(uv, 1.0));

    vec3 p0 = vec3(0.5, 0.0, 0.0);
    float t0 = sphere(ro, rd, p0, 1.0);

    vec3 p1 = vec3(-0.05, 0.0, 0.0);
    float t1 = sphere(ro, rd, p1, 1.0);

    fragColor = vec4( step(0.0,t0)*step(0.0,t1)*rd, 1.0 );
}
</code>```

Body:
So, is there a way to show (…) volumetric shapes

OpenGL (by itself) doesn't know about "volumes". It knows flat triangles, lines and points, which by pure happenstance also may cause rendering side effects like depth sorting by a depth buffer test.

Technically it is possible to chain a series of drawing and stencil buffer operations to perform CSG (constructive solid geometry); see ftp://ftp.sgi.com/opengl/contrib/blythe/advanced99/notes/node22.html for details.

However what you want to do is easier implemented through a simple raytracer executed in the fragment shader. Now raytracing by itself is a broad subject and you can fill books on it (actually lots of books have been written on the subject). It's probably best to refer to an example. In this case I refer to the following ShaderToy https://www.shadertoy.com/view/ldS3DW – a slightly stripped down version of that shader draws the kind of intersectional geometry you're interested in:

float sphere(vec3 ray, vec3 dir, vec3 center, float radius)
{
    vec3 rc = ray-center;
    float c = dot(rc, rc) - (radius*radius);
    float b = dot(dir, rc);
    float d = b*b - c;
    float t = -b - sqrt(abs(d));
    float st = step(0.0, min(t,d));
    return mix(-1.0, t, st);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = (-1.0 + 2.0*fragCoord.xy / iResolution.xy) *
        vec2(iResolution.x/iResolution.y, 1.0);

    vec3 ro = vec3(0.0, 0.0, -3.0);
    vec3 rd = normalize(vec3(uv, 1.0));

    vec3 p0 = vec3(0.5, 0.0, 0.0);
    float t0 = sphere(ro, rd, p0, 1.0);

    vec3 p1 = vec3(-0.05, 0.0, 0.0);
    float t1 = sphere(ro, rd, p1, 1.0);

    fragColor = vec4( step(0.0,t0)*step(0.0,t1)*rd, 1.0 );
}


问:
Adapting hypermedia links based on environment
I have an on-premise ASP.NET Web API that's querying on-premise data. The plan is for the client web application to call an Azure Function which will deal with authentication (Azure AD B2C) and validating the request before actually forwarding the request to the on-premise API itself (over a VPN).

The API is generating Hypermedia links that point to the API itself. This works nicely when querying the API directly as each of the links helps in the discovery of the application.

This API is currently in use locally within the organisation, but we now need to expose it so it can be consumed over the web. We don't want to expose the API directly, we'd rather route it through a Function App that can authenticate, validate and perform any other logic we may need.

The question I have is, how would you translate these URLs to an endpoint in the Azure Function? i.e., I would really like the consuming web application to be able to use these Hypermedia links directly, and have the Azure Function route them to the correct API endpoint.

In an ideal world, we'd have the links exposed on the client, which would map to the resource. As the API isn't exposed, how do we route it via the Function App?

答:
It sounds like what you want is for Azure Functions to operate as a reverse proxy.

One trick to achieve this is to have one HttpTrigger that catches all traffic that hits your function application. You can do this by setting the properties route: "{*uri}" and methods: ["get", "post", "put", "patch", "delete"] in the function.json. You can add additional HTTP methods to the methods list as necessary. These should catch all requests in the form "https://{app-name}.azurefunctions.net/api/*".

The code below is a rough outline of how you could achieve the redirect from your function app to the unexposed API. In it's current representation, the relative URI path after /api/ will be redirected to your unexposed api with the exact same body request.

```<code>using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    //Validation logic here

    string actualUrl = "{hosturl}/";
    string proxyUrl = "https://{app-name}.azurewebsites.net/api/";

    req.RequestUri = new Uri(req.RequestUri.ToString().Replace(proxyUrl, actualUrl));
    req.Headers.Host = req.RequestUri.Host;
    using(var client = new HttpClient())
    {
        return await client.SendAsync(req);
    }
}
</code>```

You can now generate all of your Hypermedia links pointing to your function hostname, and they will be properly redirected.

NOTE: If you expect many instances of the function to spin up (i.e. a high concurrent usage of your function), then it is possible that you will run into SocketException errors as documented here.

Body:
It sounds like what you want is for Azure Functions to operate as a reverse proxy.

One trick to achieve this is to have one HttpTrigger that catches all traffic that hits your function application. You can do this by setting the properties route: "{*uri}" and methods: ["get", "post", "put", "patch", "delete"] in the function.json. You can add additional HTTP methods to the methods list as necessary. These should catch all requests in the form "https://{app-name}.azurefunctions.net/api/*".

The code below is a rough outline of how you could achieve the redirect from your function app to the unexposed API. In it's current representation, the relative URI path after /api/ will be redirected to your unexposed api with the exact same body request.

using System.Net;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    //Validation logic here

    string actualUrl = "{hosturl}/";
    string proxyUrl = "https://{app-name}.azurewebsites.net/api/";

    req.RequestUri = new Uri(req.RequestUri.ToString().Replace(proxyUrl, actualUrl));
    req.Headers.Host = req.RequestUri.Host;
    using(var client = new HttpClient())
    {
        return await client.SendAsync(req);
    }
}

You can now generate all of your Hypermedia links pointing to your function hostname, and they will be properly redirected.

NOTE: If you expect many instances of the function to spin up (i.e. a high concurrent usage of your function), then it is possible that you will run into SocketException errors as documented here.


问:
Visual Studio 2015 loop performance degradation when storing pointers in struct
I found that the following loop

```<code>std::vector<int> x,y,z;
...
unsigned int res=0;
auto p=x.data();
auto q=y.data();
auto r=z.data();
for(unsigned int i=0;i<N;++i){
  res+=*p++ +*q++ +*r++;
}
</code>```

runs almost twice as fast as this one, which merely packs the pointers in a struct:

```<code>struct pdata{int *px,*py,*pz;};

unsigned int res=0;
pdata d{x.data(),y.data(),z.data()};
for(unsigned int i=0;i<N;++i){
  res+=*d.px++ +*d.py++ +*d.pz++;
}
return res;
</code>```

Is this a known performance issue? Please find below complete program and performance measurements for Visual C++ 2015 in 32-bit (x86) release mode (default settings), Windows 7 64-bit, Intel Core i5-2520M @2.5GHz:

```<code>#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <numeric>

std::chrono::high_resolution_clock::time_point measure_start,measure_pause;

template<typename F>
double measure(F f)
{
  using namespace std::chrono;

  static const int              num_trials=10;
  static const milliseconds     min_time_per_trial(200);
  std::array<double,num_trials> trials;
  volatile decltype(f())        res; /* to avoid optimizing f() away */

  for(int i=0;i<num_trials;++i){
    int                               runs=0;
    high_resolution_clock::time_point t2;

    measure_start=high_resolution_clock::now();
    do{
      res=f();
      ++runs;
      t2=high_resolution_clock::now();
    }while(t2-measure_start<min_time_per_trial);
    trials[i]=duration_cast<duration<double>>(t2-measure_start).count()/runs;
  }
  (void)res; /* var not used warn */

  std::sort(trials.begin(),trials.end());
  return std::accumulate(
    trials.begin()+2,trials.end()-2,0.0)/(trials.size()-4);
}

template<typename F>
double measure(unsigned int n,F f)
{
  double t=measure(f);
  return (t/n)*10E9;
}

#include <iostream>
#include <vector>

int main()
{
  static const unsigned int N=100000;
  std::vector<int> x(N),y(N),z(N);

  for(int i=0;i<N;i++){
    x[i]=i;
    y[i]=i+1;
    z[i]=i+2;
  }

  std::cout<<measure(N,[&]{
    unsigned int res=0;
    auto p=x.data();
    auto q=y.data();
    auto r=z.data();
    for(unsigned int i=0;i<N;++i){
      res+=*p++ +*q++ +*r++;
    }
    return res;
  })<<",";

  std::cout<<measure(N,[&]{
    struct pdata{int *px,*py,*pz;};

    unsigned int res=0;
    pdata d{x.data(),y.data(),z.data()};
    for(unsigned int i=0;i<N;++i){
      res+=*d.px++ +*d.py++ +*d.pz++;
    }
    return res;
  })<<"\n";
}
</code>```

Output

```<code>4.24541,7.44588
</code>```

Thank you,

答:
As the poster has pointed out above, the compiler has done some vectorization in the first case. Likely it is having trouble proving, or perhaps didn't try to prove at all, that the pointers for the std::vector cannot overlap the struct itself on the stack.

You can try labeling the pointers with the restrict qualifier, though I am not sure it is supported in your target environment.

Body:
I found that the following loop

std::vector<int> x,y,z;
...
unsigned int res=0;
auto p=x.data();
auto q=y.data();
auto r=z.data();
for(unsigned int i=0;i<N;++i){
  res+=*p++ +*q++ +*r++;
}

runs almost twice as fast as this one, which merely packs the pointers in a struct:

struct pdata{int *px,*py,*pz;};

unsigned int res=0;
pdata d{x.data(),y.data(),z.data()};
for(unsigned int i=0;i<N;++i){
  res+=*d.px++ +*d.py++ +*d.pz++;
}
return res;

Is this a known performance issue? Please find below complete program and performance measurements for Visual C++ 2015 in 32-bit (x86) release mode (default settings), Windows 7 64-bit, Intel Core i5-2520M @2.5GHz:

#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <numeric>

std::chrono::high_resolution_clock::time_point measure_start,measure_pause;

template<typename F>
double measure(F f)
{
  using namespace std::chrono;

  static const int              num_trials=10;
  static const milliseconds     min_time_per_trial(200);
  std::array<double,num_trials> trials;
  volatile decltype(f())        res; /* to avoid optimizing f() away */

  for(int i=0;i<num_trials;++i){
    int                               runs=0;
    high_resolution_clock::time_point t2;

    measure_start=high_resolution_clock::now();
    do{
      res=f();
      ++runs;
      t2=high_resolution_clock::now();
    }while(t2-measure_start<min_time_per_trial);
    trials[i]=duration_cast<duration<double>>(t2-measure_start).count()/runs;
  }
  (void)res; /* var not used warn */

  std::sort(trials.begin(),trials.end());
  return std::accumulate(
    trials.begin()+2,trials.end()-2,0.0)/(trials.size()-4);
}

template<typename F>
double measure(unsigned int n,F f)
{
  double t=measure(f);
  return (t/n)*10E9;
}

#include <iostream>
#include <vector>

int main()
{
  static const unsigned int N=100000;
  std::vector<int> x(N),y(N),z(N);

  for(int i=0;i<N;i++){
    x[i]=i;
    y[i]=i+1;
    z[i]=i+2;
  }

  std::cout<<measure(N,[&]{
    unsigned int res=0;
    auto p=x.data();
    auto q=y.data();
    auto r=z.data();
    for(unsigned int i=0;i<N;++i){
      res+=*p++ +*q++ +*r++;
    }
    return res;
  })<<",";

  std::cout<<measure(N,[&]{
    struct pdata{int *px,*py,*pz;};

    unsigned int res=0;
    pdata d{x.data(),y.data(),z.data()};
    for(unsigned int i=0;i<N;++i){
      res+=*d.px++ +*d.py++ +*d.pz++;
    }
    return res;
  })<<"\n";
}

Output

4.24541,7.44588

Thank you,


问:
How to throw an std::system_error exception from a FAILED(HRESULT)?
This is how to throw ordinary Win32 errors correctly, automatically retrieving the error description, and it works marvellously well:

```<code>if (!SomeWinFunc()) {
  throw std::system_error(GetLastError(),
    std::system_category(),
    "SomeWinFunc crashed badly");
}
</code>```

However, I'm uncertain on how to deal with COM errors, which are checked idiomatically like this:

```<code>HRESULT hr = comObj->SomeFunc();
if (FAILED(hr)) {
  throw std::system_error(hr, // <-- is it correct here?
    std::system_category(),
    "SomeFunc crashed right now");
}
</code>```

Is it correct to pass an HRESULT to system_error, or there is another way to throw exceptions from a COM function?

答:
Typically, I handle this using the Microsoft standard _com_error exception type, which can be easily raised by one of the following.

```<code>_com_util::CheckError(hr); // throws when FAILED(hr)
_com_issue_error(hr); // throws always
</code>```

A Win32 error can be converted to an HRESULT like so:

```<code>hr = HRESULT_FROM_WIN32(GetLastError());
</code>```

However, this means that you have to deal with a new exception type, which may be problematic. To do this the pure STL way, I think you need to derive a new error_category and use that instead of system_category. I would look at the <system_error> header and copy the implementation of system_category, updating as necessary for HRESULTs.

Ideally, the different facility codes in the HRESULT would be served by different error_category implementations -- doing so would very effectively communicate the exception and its source. But that is tricky, and you can probably get away with a single com_category that deals with HRESULTs generically.

Body:
This is how to throw ordinary Win32 errors correctly, automatically retrieving the error description, and it works marvellously well:

if (!SomeWinFunc()) {
  throw std::system_error(GetLastError(),
    std::system_category(),
    "SomeWinFunc crashed badly");
}

However, I'm uncertain on how to deal with COM errors, which are checked idiomatically like this:

HRESULT hr = comObj->SomeFunc();
if (FAILED(hr)) {
  throw std::system_error(hr, // <-- is it correct here?
    std::system_category(),
    "SomeFunc crashed right now");
}

Is it correct to pass an HRESULT to system_error, or there is another way to throw exceptions from a COM function?

Body:
Typically, I handle this using the Microsoft standard _com_error exception type, which can be easily raised by one of the following.

_com_util::CheckError(hr); // throws when FAILED(hr)
_com_issue_error(hr); // throws always

A Win32 error can be converted to an HRESULT like so:

hr = HRESULT_FROM_WIN32(GetLastError());

However, this means that you have to deal with a new exception type, which may be problematic. To do this the pure STL way, I think you need to derive a new error_category and use that instead of system_category. I would look at the <system_error> header and copy the implementation of system_category, updating as necessary for HRESULTs.

Ideally, the different facility codes in the HRESULT would be served by different error_category implementations -- doing so would very effectively communicate the exception and its source. But that is tricky, and you can probably get away with a single com_category that deals with HRESULTs generically.


问:
remove value from string
If I have a string with IDs

```<code>$myIDs = '22,34,445,67889,23';
</code>```

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

```<code>$removeID = '445';
</code>```

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

```<code>preg_replace($removeID, '', $myIDs);
</code>```

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

```<code>$myIDs = '2312,23,234234';
</code>```

and ID to remove

```<code>$removeID = '23';
</code>```

There's too many potential matches...

ContentLicense: CC BY-SA 2.5

Title: remove value from string

Body:
If I have a string with IDs

$myIDs = '22,34,445,67889,23';

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

$removeID = '445';

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

preg_replace($removeID, '', $myIDs);

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

$myIDs = '2312,23,234234';

and ID to remove

$removeID = '23';

There's too many potential matches...

Body:
$myIDs = '1,2,3,4,5';
$remID = '5';

$myIDs = preg_replace(array("/^$remID,|(?:,|^)$remID$/","/,$remID,/"),
                      array('',','),
                      $myIDs);

Ideone Link


问:
How to take values from multiple mysql rows?
I am new to web development, just started php.

Situation and What I'm trying to do: so I have a uni project where a user has a dashboard and has all the events and each event detail listed under neath it. So on the dashboard I want something like this:

Event name

Event Start date

Event description

Event name

Event Start date

Event description

And repeat until all the rows in the database have been outputted.

I have tried to use this code:

$eventsquery = ("SELECT * FROM Careerevents JOIN Tickets ON CareerEvents.Event_ID=Tickets.Event_ID JOIN Potential_Employee ON Tickets.User_ID=Potential_Employee.User_ID WHERE Email = '$email'");
$result = mysqli_query($connection, $eventsquery);
$row = mysqli_fetch_assoc($result);

    for ($i=0; $i < mysqli_num_rows($result); $i++) {
    $eventname = $row['Event_Name'];
    $startdate = $row['Start_Date'];
    $enddate = $row['End_date'];
    $description = $row['Event_Description'];
    }```

And after this I just echoed the results in the html part of the page of the dashboard. But only the first row shows up. How would I do it if i want all the row results to show up.

答:
When you do

```<code>$row = mysqli_fetch_assoc($result);
</code>```

You're pulling the first row. So when you try to grab a value as

```<code>$eventname = $row['Event_Name'];
</code>```

You're always pulling that same variable. You're never updating $row with a new value, so you're always getting the same one back. It's why people typically use a while loop, with the definition as the condition of the loop; as long as its valid (eg, it pulls a row), it'll continue the loop.

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

That said, I recommend you learn PDO and not use mysqli. PDO is far more modern, more secure, and you'll run into it a lot more, and is functionally nearly the same as mysqli. If you're already comfortable with mysqli, its not a big jump over, but from a learning perspective, is FAR ahead.

Body:
I am new to web development, just started php.

Situation and What I'm trying to do: so I have a uni project where a user has a dashboard and has all the events and each event detail listed under neath it. So on the dashboard I want something like this:

Event name

Event Start date

Event description

Event name

Event Start date

Event description

And repeat until all the rows in the database have been outputted.

I have tried to use this code:

$eventsquery = ("SELECT * FROM Careerevents JOIN Tickets ON CareerEvents.Event_ID=Tickets.Event_ID JOIN Potential_Employee ON Tickets.User_ID=Potential_Employee.User_ID WHERE Email = '$email'");
$result = mysqli_query($connection, $eventsquery);
$row = mysqli_fetch_assoc($result);

    for ($i=0; $i < mysqli_num_rows($result); $i++) {
    $eventname = $row['Event_Name'];
    $startdate = $row['Start_Date'];
    $enddate = $row['End_date'];
    $description = $row['Event_Description'];
    }

And after this I just echoed the results in the html part of the page of the dashboard. But only the first row shows up. How would I do it if i want all the row results to show up.

Body:
When you do

$row = mysqli_fetch_assoc($result);

You're pulling the first row. So when you try to grab a value as

$eventname = $row['Event_Name'];

You're always pulling that same variable. You're never updating $row with a new value, so you're always getting the same one back. It's why people typically use a while loop, with the definition as the condition of the loop; as long as its valid (eg, it pulls a row), it'll continue the loop.

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

That said, I recommend you learn PDO and not use mysqli. PDO is far more modern, more secure, and you'll run into it a lot more, and is functionally nearly the same as mysqli. If you're already comfortable with mysqli, its not a big jump over, but from a learning perspective, is FAR ahead.


问:
getting val() to use in sessionStorage
The key line in the script isvar tmp = $(this).parent().find('select').val();

and tmp returns, for example, "s1" (including the quotes) as seen in the console, which is what is expected. tmp will have different values depending on what is picked on the page.

But sessionStorage.tmp = 2 created a key:value pair of ``tmp:2, nots1:2.

How do I create a sessionStorage object s1 with value 2?

Seems like this should be simple. I tried tmp = tmp.toString(); and a million other things, but I'm too much of a newbie to figure this out. Thanks for any help.

答:
If you want to use a string as a property name you'll have to use a construct like this:

```<code>sessionStorage[tmp] = 2
</code>```

This seems to be called bracket notation you can find more details about it HERE

Title: getting val() to use in sessionStorage

Body:
If you want to use a string as a property name you'll have to use a construct like this:

sessionStorage[tmp] = 2

This seems to be called bracket notation you can find more details about it HERE


问:
Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found
I've seen other questions related to this issue but none of them actually helps with my issue.

I have these two properties defined in my test class.

```<code>  @Autowired
  private MessagingProperties messagingProperties;

  @Autowired
  private MessagingPropertiesRefactor messagingPropertiesRefactor;
</code>```

I am trying to create a new version of MessagingProperties.java. I basically copied this class and create a new file MessagingPropertiesRefactor.java (same package/dir) and pasted the same code. I changed the class definition, etc., but for the most part are the same.

I get an IntelliJ design time compiler error stating that "Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found."

I then searched for every single Usage of the original class to double check if it has been declared somewhere but I have found nothing.

I am "new" to Java (and Spring). Has anyone run into the same issue before?

答:
So, I found the "magic" line of code that makes it a "bean".

```<code>@EnableConfigurationProperties({MessagingProperties.class, MessagingPropertiesRefactor.class})
public class MessagingConfiguration {

@Autowired
  private MessagingProperties messagingProperties;

@Autowired
  private MessagingPropertiesRefactor messagingProperties;
</code>```

So, apparently all I needed to do is add this class to the @EnableConfigurationProperties attribute. Then I can use it anywere by using the @Autowired attribute.

Now... why or how, I don't know (like I said, I am "new" to java) and I would love for someone to elaborate on this.

Body:
I've seen other questions related to this issue but none of them actually helps with my issue.

I have these two properties defined in my test class.

  @Autowired
  private MessagingProperties messagingProperties;

  @Autowired
  private MessagingPropertiesRefactor messagingPropertiesRefactor;

I am trying to create a new version of MessagingProperties.java. I basically copied this class and create a new file MessagingPropertiesRefactor.java (same package/dir) and pasted the same code. I changed the class definition, etc., but for the most part are the same.

I get an IntelliJ design time compiler error stating that "Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found."

I then searched for every single Usage of the original class to double check if it has been declared somewhere but I have found nothing.

I am "new" to Java (and Spring). Has anyone run into the same issue before?

Body:
So, I found the "magic" line of code that makes it a "bean".

@EnableConfigurationProperties({MessagingProperties.class, MessagingPropertiesRefactor.class})
public class MessagingConfiguration {

@Autowired
  private MessagingProperties messagingProperties;

@Autowired
  private MessagingPropertiesRefactor messagingProperties;

So, apparently all I needed to do is add this class to the @EnableConfigurationProperties attribute. Then I can use it anywere by using the @Autowired attribute.

Now... why or how, I don't know (like I said, I am "new" to java) and I would love for someone to elaborate on this.


问:
ios Instagram api POST Relationship Endpoints using Alamofire - Error
i'm using swift in my app

and i'm trying to post a relationship (Follow) with scope ("follower_list+relationships") using Alamofire

Note: I'm using sandbox users for testing

with this code

```<code>let userid = "testAccount"
    let urlString = "https://api.instagram.com/v1/users/\(userid)/relationship?access_token=\(INSTAGRAM_IDS.INSTAGRAM_Token)&action=follow"

    Alamofire.request(urlString).responseJSON { response in switch response.result {

        case .success(let JSON):

        let response = JSON as! NSDictionary
        let userModel = response

            print("SUCCESS")
            print(userModel)

        case .failure(let error):

            print("ERROR")
            print(error)
        }
    }
</code>```

and also tried this one

```<code>let userid = "testAccount"
    let urlString = "https://api.instagram.com/v1/users/\(userid)/relationship?access_token=\(INSTAGRAM_IDS.INSTAGRAM_Token)"
    let parameters: Parameters = ["action": "follow"]

    Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in switch response.result {

        case .success(let JSON):

        let response = JSON as! NSDictionary
        let userModel = response

            print("SUCCESS")
            print(userModel)

        case .failure(let error):

            print("ERROR")
            print(error)
        }
    }
</code>```

BUT still got this message ??

ERROR
  responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

any idea ??

答:
I found the problem .... I've been using account username rather than user-id
there is a difference...my bad

You can get user-id from (search) Endpoint api OR use a web site like
https://smashballoon.com/instagram-feed/find-instagram-user-id/

you put the username and you will get the ID

Body:
i'm using swift in my app

and i'm trying to post a relationship (Follow) with scope ("follower_list+relationships") using Alamofire

Note: I'm using sandbox users for testing

with this code

let userid = "testAccount"
    let urlString = "https://api.instagram.com/v1/users/\(userid)/relationship?access_token=\(INSTAGRAM_IDS.INSTAGRAM_Token)&action=follow"

    Alamofire.request(urlString).responseJSON { response in switch response.result {

        case .success(let JSON):

        let response = JSON as! NSDictionary
        let userModel = response

            print("SUCCESS")
            print(userModel)

        case .failure(let error):

            print("ERROR")
            print(error)
        }
    }

and also tried this one

let userid = "testAccount"
    let urlString = "https://api.instagram.com/v1/users/\(userid)/relationship?access_token=\(INSTAGRAM_IDS.INSTAGRAM_Token)"
    let parameters: Parameters = ["action": "follow"]

    Alamofire.request(urlString, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { response in switch response.result {

        case .success(let JSON):

        let response = JSON as! NSDictionary
        let userModel = response

            print("SUCCESS")
            print(userModel)

        case .failure(let error):

            print("ERROR")
            print(error)
        }
    }

BUT still got this message ??

ERROR
  responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

any idea ??


问:
Need help displaying serial monitor on LCD
I'm having issues displaying the serial monitor on an lcd. I am not getting any error and the LCD is lit up so I don't think I wired it wrong. I am able to open up the serial monitor/plotter and see in information changing so my other component is also working so the problem must be in the code...

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

/**
 * LIDARLite I2C Example
 * Author: Garmin
 * Modified by: Shawn Hymel (SparkFun Electronics)
 * Date: June 29, 2017
 *
 * Read distance from LIDAR-Lite v3 over I2C
 *
 * See the Operation Manual for wiring diagrams and more information:
 * http://static.garmin.com/pumac/LIDAR_Lite_v3_Operation_Manual_and_Technical_Specifications.pdf
 */

#include <Wire.h>
#include <LIDARLite.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// Globals
LIDARLite lidarLite;
int cal_cnt = 0;

void setup()
{
  Serial.begin(9600); // Initialize serial connection to display distance readings

  lidarLite.begin(0, true); // Set configuration to default and I2C to 400 kHz
  lidarLite.configure(0); // Change this number to try out alternate configurations

  lcd.begin(16, 2);
  // initialize the serial communications:
}

void loop()
{
  int dist;

  // At the beginning of every 100 readings,
  // take a measurement with receiver bias correction
  if ( cal_cnt == 0 ) {
    dist = lidarLite.distance();      // With bias correction
  } else {
    dist = lidarLite.distance(false); // Without bias correction
  }

  // Increment reading counter
  cal_cnt++;
  cal_cnt = cal_cnt % 100;

  // Display distance
  Serial.print(dist);
  Serial.println(" cm");

  delay(10);

    // when characters arrive over the serial port...
  if (Serial.available()) {
    // wait a bit for the entire message to arrive
    delay(100);
    // clear the screen
    lcd.clear();
    // read all the available characters
    while (Serial.available() > 0) {
      // display each character to the LCD
      lcd.write(Serial.read());
    }
  }
}
</code>```

The LCD should be displaying the changing measurements

The LCD is lit up and I can adjust the back light but I can't get anything to show up.

答:
Just because the LCD is "lit" doesn't mean it's wired correctly.  In fact, the backlighting circuit is usually totally separate from the data and control signals circuits.  I would start by checking the assumption that it's wired correctly with a simple command to print a known value to the LCD:

```<code>lcd.clear();
lcd.println("TEST");
</code>```

If this works, then you know the LCD is working and can look elsewhere for the problem.

If this doesn't work, I'd question your assumption that it's hooked up correctly, but if you still get nothing but "blue blocks" then it might be something as simple as your contrast is not correct.  It can be tricky getting the contrast and brightness to a good combination for readability.  See if your display has a small potentiometer (usually adjustable with a very small Philips-head driver) on the back and carefully adjust the contrast.

Brightness is often changeable through software commands but most LCDs default to high brightness when first booted up.

If changing contrast doesn't work, you may have a real wiring problem and then it really is off-topic for this forum.  In that case you should sketch a schematic and post on Electrical Engineering stack.

Body:
I'm having issues displaying the serial monitor on an lcd. I am not getting any error and the LCD is lit up so I don't think I wired it wrong. I am able to open up the serial monitor/plotter and see in information changing so my other component is also working so the problem must be in the code...

#include <LiquidCrystal.h>

/**
 * LIDARLite I2C Example
 * Author: Garmin
 * Modified by: Shawn Hymel (SparkFun Electronics)
 * Date: June 29, 2017
 *
 * Read distance from LIDAR-Lite v3 over I2C
 *
 * See the Operation Manual for wiring diagrams and more information:
 * http://static.garmin.com/pumac/LIDAR_Lite_v3_Operation_Manual_and_Technical_Specifications.pdf
 */

#include <Wire.h>
#include <LIDARLite.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// Globals
LIDARLite lidarLite;
int cal_cnt = 0;

void setup()
{
  Serial.begin(9600); // Initialize serial connection to display distance readings

  lidarLite.begin(0, true); // Set configuration to default and I2C to 400 kHz
  lidarLite.configure(0); // Change this number to try out alternate configurations

  lcd.begin(16, 2);
  // initialize the serial communications:
}

void loop()
{
  int dist;

  // At the beginning of every 100 readings,
  // take a measurement with receiver bias correction
  if ( cal_cnt == 0 ) {
    dist = lidarLite.distance();      // With bias correction
  } else {
    dist = lidarLite.distance(false); // Without bias correction
  }

  // Increment reading counter
  cal_cnt++;
  cal_cnt = cal_cnt % 100;

  // Display distance
  Serial.print(dist);
  Serial.println(" cm");

  delay(10);

    // when characters arrive over the serial port...
  if (Serial.available()) {
    // wait a bit for the entire message to arrive
    delay(100);
    // clear the screen
    lcd.clear();
    // read all the available characters
    while (Serial.available() > 0) {
      // display each character to the LCD
      lcd.write(Serial.read());
    }
  }
}

The LCD should be displaying the changing measurements

The LCD is lit up and I can adjust the back light but I can't get anything to show up.

Body:
Just because the LCD is "lit" doesn't mean it's wired correctly.  In fact, the backlighting circuit is usually totally separate from the data and control signals circuits.  I would start by checking the assumption that it's wired correctly with a simple command to print a known value to the LCD:

lcd.clear();
lcd.println("TEST");

If this works, then you know the LCD is working and can look elsewhere for the problem.

If this doesn't work, I'd question your assumption that it's hooked up correctly, but if you still get nothing but "blue blocks" then it might be something as simple as your contrast is not correct.  It can be tricky getting the contrast and brightness to a good combination for readability.  See if your display has a small potentiometer (usually adjustable with a very small Philips-head driver) on the back and carefully adjust the contrast.

Brightness is often changeable through software commands but most LCDs default to high brightness when first booted up.

If changing contrast doesn't work, you may have a real wiring problem and then it really is off-topic for this forum.  In that case you should sketch a schematic and post on Electrical Engineering stack.


问:
Optimise T-sql query
The query I need to develop is to list out sites which have no records (retail transactions) for a given date.  I've been able to accomplish this for a specific site, but I know the query can be written more efficiently using joins but my foray into inners and outers hasn't been much fun.

Here's what I have so far:

```<code>DECLARE @StartDate DATE = '2017-11-01',
    @EndDate DATE = '2017-11-30';

SELECT tx.Txndate, count(*) as txCount
FROM [Report].[dbo].[FactTransactions] tx
where tx.Site = 2
and tx.TxnDate between @StartDate and @EndDate
group by tx.TxnDate
union all
select db.daybookdate, 0 as txCount
from DimDaybook db
where db.daybookdate between @StartDate and @EndDate
and NOT EXISTS (SELECT 1 FROM [Report].[dbo].[FactTransactions] AS t WHERE t.TxnDate = db.daybookdate and t.txndate between @StartDate and @EndDate and t.site = 2)
order by tx.Txndate
</code>```

This returns me the result set for site 2

```<code>Txndate txCount
2017-11-01  1691
2017-11-02  1657
2017-11-03  1835
2017-11-04  1587
2017-11-05  1489
2017-11-06  1544
2017-11-07  1525
2017-11-08  1782
2017-11-09  1848
2017-11-10  1990
2017-11-11  0
2017-11-12  0
</code>```

What I'd really like to have is a result set that looks like this and runs much much quicker than my hack (currently around 2mins - for context the transactions table has 83,486,412 records)

```<code>Site    Date    Transactions
2   11/11/17    0
2   12/11/27    0
3   12/11/17    0
22  1/11/17     0
</code>```

答:
One way could be the following:

```<code>DECLARE @StartDate DATE = '2017-11-01', @EndDate DATE = '2017-11-30';
With cte as (
 SELECT tx.Txndate, count(*) as txCount FROM
[Report].[dbo].[FactTransactions] tx where tx.Site = 2 and tx.TxnDate between @StartDate and @EndDate group by tx.TxnDate)
Select db.daybookdate, isnull(txCount,0) from DimDaybook db left join cte on db.daybookdate = cte.Txndate
</code>```

I'm missing the site id but there's nowhere I can get it from your sample code.

Title: Optimise T-sql query

Body:
The query I need to develop is to list out sites which have no records (retail transactions) for a given date.  I've been able to accomplish this for a specific site, but I know the query can be written more efficiently using joins but my foray into inners and outers hasn't been much fun.

Here's what I have so far:

DECLARE @StartDate DATE = '2017-11-01',
    @EndDate DATE = '2017-11-30';

SELECT tx.Txndate, count(*) as txCount
FROM [Report].[dbo].[FactTransactions] tx
where tx.Site = 2
and tx.TxnDate between @StartDate and @EndDate
group by tx.TxnDate
union all
select db.daybookdate, 0 as txCount
from DimDaybook db
where db.daybookdate between @StartDate and @EndDate
and NOT EXISTS (SELECT 1 FROM [Report].[dbo].[FactTransactions] AS t WHERE t.TxnDate = db.daybookdate and t.txndate between @StartDate and @EndDate and t.site = 2)
order by tx.Txndate

This returns me the result set for site 2

Txndate txCount
2017-11-01  1691
2017-11-02  1657
2017-11-03  1835
2017-11-04  1587
2017-11-05  1489
2017-11-06  1544
2017-11-07  1525
2017-11-08  1782
2017-11-09  1848
2017-11-10  1990
2017-11-11  0
2017-11-12  0

What I'd really like to have is a result set that looks like this and runs much much quicker than my hack (currently around 2mins - for context the transactions table has 83,486,412 records)

Site    Date    Transactions
2   11/11/17    0
2   12/11/27    0
3   12/11/17    0
22  1/11/17     0

Body:
One way could be the following:

DECLARE @StartDate DATE = '2017-11-01', @EndDate DATE = '2017-11-30';
With cte as (
 SELECT tx.Txndate, count(*) as txCount FROM
[Report].[dbo].[FactTransactions] tx where tx.Site = 2 and tx.TxnDate between @StartDate and @EndDate group by tx.TxnDate)
Select db.daybookdate, isnull(txCount,0) from DimDaybook db left join cte on db.daybookdate = cte.Txndate

I'm missing the site id but there's nowhere I can get it from your sample code.


答:
```<code>$myarray=explode(',', $myIDs)
$excluded=preg_grep('^' . $removeID . '$', $myarray, PREG_GREP_INVERT)
$newId=join(',', $excluded)
</code>```

Title: remove value from string


问:
Python compare/replace keys in dic with values of another dic
I'm looking for a way to compare/replace a value of a dictionary with a key of another dictionary  like so :

```<code>DicA = {'abc' : 1 , 'def' : 2 , 'ghi' : 3}

DicB = {3: 'klm' , 2 : 'nop' ,1 : 'qrs'}
</code>```

Result should be:

```<code>DicC = {'abc' : 'qrs' , 'def' : 'nop' ,'ghi' : 'klm'}
</code>```

So the Value "1" in DicA got replaced with "qrs" because they key in DicB(1) matched with the Value in DicA(1) so the result is -> abc : qrs.

How do I compare the  key with the value of another dictionary?(for loops)?

How do I replace it afterwards?

Is there a way to use the implemented map() function for this? E.g.

```<code>map(lambda dicA, dicB):
</code>```

答:
You could do it with a dictionary comprehension:

```<code>dicA= {'abc': 1, 'def': 2, 'ghi': 3}
dicB= {3: 'klm', 2: 'nop', 1: 'qrs'}

dicC = {key: dicB[val] for key, val in dicA.items()}
</code>```

However, this will fail if dicB does not have a key for one of the items in dicA.  You can get around this by using the get dictionary method which accepts a default value, as pointed out by MCBama.

```<code>dicA = {'abc': 1, 'def': 2, 'ghi': 3}
dicB = {2: 'nop', 1: 'qrs'}

dicC = {key: dicB.get(val,"") for key, val in dicA.items()}
# {'abc': 'qrs', 'def': 'nop', 'ghi': ''}
</code>```

Body:
I'm looking for a way to compare/replace a value of a dictionary with a key of another dictionary  like so :

DicA = {'abc' : 1 , 'def' : 2 , 'ghi' : 3}

DicB = {3: 'klm' , 2 : 'nop' ,1 : 'qrs'}

Result should be:

DicC = {'abc' : 'qrs' , 'def' : 'nop' ,'ghi' : 'klm'}

So the Value "1" in DicA got replaced with "qrs" because they key in DicB(1) matched with the Value in DicA(1) so the result is -> abc : qrs.

How do I compare the  key with the value of another dictionary?(for loops)?

How do I replace it afterwards?

Is there a way to use the implemented map() function for this? E.g.

map(lambda dicA, dicB):

Body:
You could do it with a dictionary comprehension:

dicA= {'abc': 1, 'def': 2, 'ghi': 3}
dicB= {3: 'klm', 2: 'nop', 1: 'qrs'}

dicC = {key: dicB[val] for key, val in dicA.items()}

However, this will fail if dicB does not have a key for one of the items in dicA.  You can get around this by using the get dictionary method which accepts a default value, as pointed out by MCBama.

dicA = {'abc': 1, 'def': 2, 'ghi': 3}
dicB = {2: 'nop', 1: 'qrs'}

dicC = {key: dicB.get(val,"") for key, val in dicA.items()}
# {'abc': 'qrs', 'def': 'nop', 'ghi': ''}


问:
Mapping DTO with final members in MapStruct
is there a way to map a DTO using MatStruct which have a few final data members as well and cannot have a default constructor , like : </p>

```<code>public class TestDto {

    private final String testName;
    private int id;
    private String testCase;

    public TestDto(String testName) {
        this.testName = testName;
    }

    public String getTestName() {
        return testName;
    }

    public int getId() {
        return id;
    }

    public String getTestCase() {
        return testCase;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setTestCase(String testCase) {
        this.testCase = testCase;
    }
}
</code>```

<p>please suggest how could this DTO be mapped using MapStruct. </p>

答:
You can use @ObjectFactory that would construct an instance of your DTO.

For example:

```<code>@Mapper
public interface MyMapper {

    @ObjectFactory
    default TestDto create() {
        return new TestDto("My Test Name");
    }

    //the rest of the mappings
}
</code>```

You can also enhance the @ObjectFactory to accept the source parameter, that you can use to construct the TestDto. You can even use a @Context as an Object Factory.

NB: You don't have to put the @ObjectFactory method in the same Mapper, or even a MapStruct @Mapper. You can put it in any class (or make it static) and then @Mapper(uses = MyFactory.class)

Body:
is there a way to map a DTO using MatStruct which have a few final data members as well and cannot have a default constructor , like :

public class TestDto {

    private final String testName;
    private int id;
    private String testCase;

    public TestDto(String testName) {
        this.testName = testName;
    }

    public String getTestName() {
        return testName;
    }

    public int getId() {
        return id;
    }

    public String getTestCase() {
        return testCase;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setTestCase(String testCase) {
        this.testCase = testCase;
    }
}

please suggest how could this DTO be mapped using MapStruct.

Body:
You can use @ObjectFactory that would construct an instance of your DTO.

For example:

@Mapper
public interface MyMapper {

    @ObjectFactory
    default TestDto create() {
        return new TestDto("My Test Name");
    }

    //the rest of the mappings
}

You can also enhance the @ObjectFactory to accept the source parameter, that you can use to construct the TestDto. You can even use a @Context as an Object Factory.

NB: You don't have to put the @ObjectFactory method in the same Mapper, or even a MapStruct @Mapper. You can put it in any class (or make it static) and then @Mapper(uses = MyFactory.class)


问:
R: Parse XML in R
I have a following XML file

```<code><?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<t:Forecast xmlns:t="http://example.com">
      <Sender Abbreviation="abc" Name="xyz"/>
      <Recipient Abbreviation="efg" Name="cba"/>
      <createdUTC>2017-11-24T10:41:11Z</createdUTC>
      <MessageID>bcjs</MessageID>
      <SystemState>test</SystemState>
      <ForecastData>
          <DataHeader GroupKey="rkolo">

          <Timeseries ID="abc123">
              <TimeInt ISTUTC="2017-11-24T10:45:00Z" Out="858"/>
              <TimeInt ISTUTC="2017-11-24T11:45:00Z" Out="868"/>
          </Timeseries>

          <Timeseries ID="xyz">
              <TimeInt ISTUTC="2017-11-24T10:45:00Z" Out="870"/>
              <TimeInt ISTUTC="2017-11-24T11:45:00Z" Out="890"/>
          </Timeseries>
      </ForecastData>
</t:Forecast>
</code>```

I would like to have two data frames

```<code>TimeInt                 out
2017-11-24T10:45:00Z    858
2017-11-24T11:45:00Z    868
</code>```

and another data frame as

```<code>TimeInt                 out
2017-11-24T10:45:00Z    870
2017-11-24T11:45:00Z    890
</code>```

So far, I have done as follows:

```<code>require(XML)

temp = xmlParse("datafile.xml")
data = xmlToList(temp)
</code>```

But the output of data contains lot of nested lists. How do I get the data frames?

Edit 1: changed out values

答:
Consider the triple-colon method xmlAttrsToDataFrame but looping through each node index of Timeseries, even name each element with the corresponding Timeseries id.

```<code>library(XML)

txt='<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
     <t:Forecast xmlns:t="http://example.com">
        <Sender Abbreviation="abc" Name="xyz"/>
        <Recipient Abbreviation="efg" Name="cba"/>
        <createdUTC>2017-11-24T10:41:11Z</createdUTC>
        <MessageID>bcjs</MessageID>
        <SystemState>test</SystemState>
        <ForecastData>
           <DataHeader GroupKey="rkolo"/>
             <Timeseries ID="abc123">
                <TimeInt ISTUTC="2017-11-24T10:45:00Z" Out="858"/>
                <TimeInt ISTUTC="2017-11-24T11:45:00Z" Out="858"/>
             </Timeseries>

             <Timeseries ID="xyz">
                <TimeInt ISTUTC="2017-11-24T10:45:00Z" Out="870"/>
                <TimeInt ISTUTC="2017-11-24T11:45:00Z" Out="870"/>
             </Timeseries>
        </ForecastData>
     </t:Forecast>'

doc <- xmlParse(txt)

dfList <- lapply(1:length(xpathSApply(doc, "//Timeseries", xmlAttrs)), function(i)
    XML:::xmlAttrsToDataFrame(getNodeSet(doc, path=paste0('//Timeseries[',i,']/TimeInt')))
)

dfList <- setNames(dfList, xpathSApply(doc, path='//Timeseries', xmlAttrs))
dfList
</code>```

Output

```<code>dfList$abc123
#                 ISTUTC Out
# 1 2017-11-24T10:45:00Z 858
# 2 2017-11-24T11:45:00Z 858

dfList$xyz
#                 ISTUTC Out
# 3 2017-11-24T10:45:00Z 870
# 4 2017-11-24T11:45:00Z 870
</code>```

Title: R: Parse XML in R

Body:
I have a following XML file

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<t:Forecast xmlns:t="http://example.com">
      <Sender Abbreviation="abc" Name="xyz"/>
      <Recipient Abbreviation="efg" Name="cba"/>
      <createdUTC>2017-11-24T10:41:11Z</createdUTC>
      <MessageID>bcjs</MessageID>
      <SystemState>test</SystemState>
      <ForecastData>
          <DataHeader GroupKey="rkolo">

          <Timeseries ID="abc123">
              <TimeInt ISTUTC="2017-11-24T10:45:00Z" Out="858"/>
              <TimeInt ISTUTC="2017-11-24T11:45:00Z" Out="868"/>
          </Timeseries>

          <Timeseries ID="xyz">
              <TimeInt ISTUTC="2017-11-24T10:45:00Z" Out="870"/>
              <TimeInt ISTUTC="2017-11-24T11:45:00Z" Out="890"/>
          </Timeseries>
      </ForecastData>
</t:Forecast>

I would like to have two data frames

TimeInt                 out
2017-11-24T10:45:00Z    858
2017-11-24T11:45:00Z    868

and another data frame as

TimeInt                 out
2017-11-24T10:45:00Z    870
2017-11-24T11:45:00Z    890

So far, I have done as follows:

require(XML)

temp = xmlParse("datafile.xml")
data = xmlToList(temp)

But the output of data contains lot of nested lists. How do I get the data frames?

Edit 1: changed out values

Body:
Consider the triple-colon method xmlAttrsToDataFrame but looping through each node index of Timeseries, even name each element with the corresponding Timeseries id.

library(XML)

txt='<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
     <t:Forecast xmlns:t="http://example.com">
        <Sender Abbreviation="abc" Name="xyz"/>
        <Recipient Abbreviation="efg" Name="cba"/>
        <createdUTC>2017-11-24T10:41:11Z</createdUTC>
        <MessageID>bcjs</MessageID>
        <SystemState>test</SystemState>
        <ForecastData>
           <DataHeader GroupKey="rkolo"/>
             <Timeseries ID="abc123">
                <TimeInt ISTUTC="2017-11-24T10:45:00Z" Out="858"/>
                <TimeInt ISTUTC="2017-11-24T11:45:00Z" Out="858"/>
             </Timeseries>

             <Timeseries ID="xyz">
                <TimeInt ISTUTC="2017-11-24T10:45:00Z" Out="870"/>
                <TimeInt ISTUTC="2017-11-24T11:45:00Z" Out="870"/>
             </Timeseries>
        </ForecastData>
     </t:Forecast>'

doc <- xmlParse(txt)

dfList <- lapply(1:length(xpathSApply(doc, "//Timeseries", xmlAttrs)), function(i)
    XML:::xmlAttrsToDataFrame(getNodeSet(doc, path=paste0('//Timeseries[',i,']/TimeInt')))
)

dfList <- setNames(dfList, xpathSApply(doc, path='//Timeseries', xmlAttrs))
dfList

Output

dfList$abc123
#                 ISTUTC Out
# 1 2017-11-24T10:45:00Z 858
# 2 2017-11-24T11:45:00Z 858

dfList$xyz
#                 ISTUTC Out
# 3 2017-11-24T10:45:00Z 870
# 4 2017-11-24T11:45:00Z 870


问:
Mapping slope of an area and returning percent above and below a threshold in R
I am trying to figure our the proportion of an area that has a slope of 0, +/- 5 degrees. Another way of saying it is anything above 5 degrees and below 5 degrees are bad. I am trying to find the actual number, and a graphic.

To achieve this I turned to R and using the Raster package.
Let's use a generic country, in this case, the Philippines

```<code>{list.of.packages <- c("sp","raster","rasterVis","maptools","rgeos")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)}

library(sp)  # classes for spatial data
library(raster)  # grids, rasters
library(rasterVis)  # raster visualisation
library(maptools)
library(rgeos)
</code>```

Now let's get the altitude information and plot the slopes.

```<code>elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
plot(x$slope)
</code>```

Not very helpful due to the scale, so let's simply look at the Island of Palawan

```<code>e <- drawExtent(show=TRUE) #to crop out Palawan (it's the long skinny island that is roughly midway on the left and is oriented between 2 and 8 O'clock)
gewataSub <- crop(x,e)
plot(gewataSub, 1)## Now visualize the new cropped object
</code>```

A little bit better to visualize. I get a sense of the magnitude of the slopes and that with a 5 degree restriction, I am mostly confined to the coast. But I need a little bit more for analysis.

I would like Results to be something to be in two parts:
1. " 35 % (made up) of the selected area has a slope exceeding +/- 5 degrees" or " 65 % of the selected area is within +/- 5 degrees". (with the code to get it)
2. A picture where everything within +/- 5 degrees is one color, call it good or green, and everything else is in another color, call it bad or red.

Thanks

答:
You can use reclassify from the raster package to achieve that. The function assigns each cell value that lies within a defined interval a certain value. For example, you can assign cell values within interval (0,5] to value 0 and cell values within the interval (5, maxSlope] to value 1.

```<code>library(raster)
library(rasterVis)

elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
plot(x$slope)

e <- drawExtent(show = TRUE)
gewataSub <- crop(x, e)
plot(gewataSub$slope, 1)

m <- c(0, 5, 0,  5, maxValue(gewataSub$slope), 1)
rclmat <- matrix(m, ncol = 3, byrow = TRUE)
rc <- reclassify(gewataSub$slope, rclmat)

levelplot(
  rc,
  margin = F,
  col.regions = c("wheat", "gray"),
  colorkey = list(at = c(0, 1, 2), labels = list(at = c(0.5, 1.5), labels = c("<= 5", "> 5")))
)
</code>```

After the reclassification you can calculate the percentages:

```<code>length(rc[rc == 0]) / (length(rc[rc == 0]) + length(rc[rc == 1])) # <= 5 degrees
[1] 0.6628788
length(rc[rc == 1]) / (length(rc[rc == 0]) + length(rc[rc == 1])) # > 5 degrees
[1] 0.3371212
</code>```

Body:
I am trying to figure our the proportion of an area that has a slope of 0, +/- 5 degrees. Another way of saying it is anything above 5 degrees and below 5 degrees are bad. I am trying to find the actual number, and a graphic.

To achieve this I turned to R and using the Raster package.
Let's use a generic country, in this case, the Philippines

{list.of.packages <- c("sp","raster","rasterVis","maptools","rgeos")
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)}

library(sp)  # classes for spatial data
library(raster)  # grids, rasters
library(rasterVis)  # raster visualisation
library(maptools)
library(rgeos)

Now let's get the altitude information and plot the slopes.

elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
plot(x$slope)

Not very helpful due to the scale, so let's simply look at the Island of Palawan

e <- drawExtent(show=TRUE) #to crop out Palawan (it's the long skinny island that is roughly midway on the left and is oriented between 2 and 8 O'clock)
gewataSub <- crop(x,e)
plot(gewataSub, 1)## Now visualize the new cropped object

A little bit better to visualize. I get a sense of the magnitude of the slopes and that with a 5 degree restriction, I am mostly confined to the coast. But I need a little bit more for analysis.

I would like Results to be something to be in two parts:
1. " 35 % (made up) of the selected area has a slope exceeding +/- 5 degrees" or " 65 % of the selected area is within +/- 5 degrees". (with the code to get it)
2. A picture where everything within +/- 5 degrees is one color, call it good or green, and everything else is in another color, call it bad or red.

Thanks

Body:
You can use reclassify from the raster package to achieve that. The function assigns each cell value that lies within a defined interval a certain value. For example, you can assign cell values within interval (0,5] to value 0 and cell values within the interval (5, maxSlope] to value 1.

library(raster)
library(rasterVis)

elevation <- getData("alt", country = "PHL")
x <- terrain(elevation, opt = c("slope", "aspect"), unit = "degrees")
plot(x$slope)

e <- drawExtent(show = TRUE)
gewataSub <- crop(x, e)
plot(gewataSub$slope, 1)

m <- c(0, 5, 0,  5, maxValue(gewataSub$slope), 1)
rclmat <- matrix(m, ncol = 3, byrow = TRUE)
rc <- reclassify(gewataSub$slope, rclmat)

levelplot(
  rc,
  margin = F,
  col.regions = c("wheat", "gray"),
  colorkey = list(at = c(0, 1, 2), labels = list(at = c(0.5, 1.5), labels = c("<= 5", "> 5")))
)

After the reclassification you can calculate the percentages:

length(rc[rc == 0]) / (length(rc[rc == 0]) + length(rc[rc == 1])) # <= 5 degrees
[1] 0.6628788
length(rc[rc == 1]) / (length(rc[rc == 0]) + length(rc[rc == 1])) # > 5 degrees
[1] 0.3371212


问:
Get return code from an exe using VBScript is not working
I have an command line app that queries some Scheduled Tasks and returns 0 if ready and 1 if not.

I need to get that return code from a VBScript, but I am getting 0 always, even if the app returns 1. This is the code I have:

```<code>StrCommandLine = """C:\Program Files (x86)\App\TaskValidator\TaskValidator.exe"""

Set oshell = CreateObject("WScript.Shell")

iReturn = oShell.run(StrCommandLine,0,true)

wscript.echo iReturn
</code>```

If I run the app from a CMD, it returns 1 if not ready. I think it is because I am getting the last error code from CMD itself.

Any help you can give me?

答:
From Help http://download.microsoft.com/download/winscript56/Install/5.6/W982KMeXP/EN-US/scrdoc56en.exe

You are not setting an error code.

Quit Method (Windows Script Host)

Forces script execution to stop at any time.

object.Quit([intErrorCode])

object

WScript object.

intErrorCode

Optional. Integer value returned as the process's exit code. If you do not include the intErrorCode parameter, no value is returned.

Remarks
The Quit method can return an optional error code. If the Quit method

Body:
I have an command line app that queries some Scheduled Tasks and returns 0 if ready and 1 if not.

I need to get that return code from a VBScript, but I am getting 0 always, even if the app returns 1. This is the code I have:

StrCommandLine = """C:\Program Files (x86)\App\TaskValidator\TaskValidator.exe"""

Set oshell = CreateObject("WScript.Shell")

iReturn = oShell.run(StrCommandLine,0,true)

wscript.echo iReturn

If I run the app from a CMD, it returns 1 if not ready. I think it is because I am getting the last error code from CMD itself.

Any help you can give me?


问:
Cocoa - go to foreground/background programmatically
I have an application with LSUIElement set to 1. It has a built-in editor, so I want the application to appear in Cmd+Tab cycle when the editor is open.

```<code>    -(void)stepIntoForeground
    {
        if (NSAppKitVersionNumber < NSAppKitVersionNumber10_7) return;
        if (counter == 0) {
            ProcessSerialNumber psn = {0, kCurrentProcess};
            OSStatus osstatus = TransformProcessType(&psn, kProcessTransformToForegroundApplication);
            if (osstatus == 0) {
                ++counter;
            } else {
                //...
            }
        }
    }
    -(void)stepIntoBackground
    {
        if (NSAppKitVersionNumber < NSAppKitVersionNumber10_7) return;
        if (counter == 0) return;

        if (counter == 1) {
            ProcessSerialNumber psn = {0, kCurrentProcess};
            OSStatus osstatus = TransformProcessType(&psn, kProcessTransformToUIElementApplication);
            if (osstatus == 0) {
                --counter;
            } else {
                //..
            }
        }
    }
</code>```

The problems are:

there's also a Dock icon (not a big deal);

there's also Menu, that is not a big deal too, but they appear not always.

Is there any way to disable menu at all or to make it appear always in foreground? Thanks in advance.

答:
With swift 4, in applicationDidfinishLaunching(_:Notification)

```<code>NSApplication.shared.setActivationPolicy(.regular)
</code>```

did the trick for me, but I was only trying to get keyboard focus to my programmatically created window. Thanks.

Body:
I have an application with LSUIElement set to 1. It has a built-in editor, so I want the application to appear in Cmd+Tab cycle when the editor is open.

    -(void)stepIntoForeground
    {
        if (NSAppKitVersionNumber < NSAppKitVersionNumber10_7) return;
        if (counter == 0) {
            ProcessSerialNumber psn = {0, kCurrentProcess};
            OSStatus osstatus = TransformProcessType(&psn, kProcessTransformToForegroundApplication);
            if (osstatus == 0) {
                ++counter;
            } else {
                //...
            }
        }
    }
    -(void)stepIntoBackground
    {
        if (NSAppKitVersionNumber < NSAppKitVersionNumber10_7) return;
        if (counter == 0) return;

        if (counter == 1) {
            ProcessSerialNumber psn = {0, kCurrentProcess};
            OSStatus osstatus = TransformProcessType(&psn, kProcessTransformToUIElementApplication);
            if (osstatus == 0) {
                --counter;
            } else {
                //..
            }
        }
    }

The problems are:

there's also a Dock icon (not a big deal);

there's also Menu, that is not a big deal too, but they appear not always.

Is there any way to disable menu at all or to make it appear always in foreground? Thanks in advance.

Body:
With swift 4, in applicationDidfinishLaunching(_:Notification)

NSApplication.shared.setActivationPolicy(.regular)

did the trick for me, but I was only trying to get keyboard focus to my programmatically created window. Thanks.


问:
Connecting to Firebird database in Qt
I have local database, that I want to connect with.
Here is my code, but unfortunately it doesn't work.

```<code>    QString servername = "SYSDBA@localhost";
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setHostName(servername);
    db.setDatabaseName("Driver={InterBase ODBC driver};DATABASE=D:\\baza\\BAZA.fdb;");
    db.setUserName("SYSDBA");
    db.setPassword("masterkey");
    if (db.open())
        qDebug() << "Connected";
    else
        qDebug() << "Nope :(";
</code>```

I would appreciate any help.

答:
I finally got it.
You have to set up your ODBC driver in windows:
https://kb.brainwaregroup.com/operationsmanager/faces/kb/brainwaregroup%20kb/article/AA-00486

Then you can connect it directly using dsn  configured in windows administrative tools:

```<code>QString servername = "localhost";
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setHostName(servername);
db.setDatabaseName("YOUR_DSN_NAME");
db.setUserName("SYSDBA");
db.setPassword("masterkey");
</code>```

Title: Connecting to Firebird database in Qt

Body:
I have local database, that I want to connect with.
Here is my code, but unfortunately it doesn't work.

    QString servername = "SYSDBA@localhost";
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setHostName(servername);
    db.setDatabaseName("Driver={InterBase ODBC driver};DATABASE=D:\\baza\\BAZA.fdb;");
    db.setUserName("SYSDBA");
    db.setPassword("masterkey");
    if (db.open())
        qDebug() << "Connected";
    else
        qDebug() << "Nope :(";

I would appreciate any help.

Body:
I finally got it.
You have to set up your ODBC driver in windows:
https://kb.brainwaregroup.com/operationsmanager/faces/kb/brainwaregroup%20kb/article/AA-00486

Then you can connect it directly using dsn  configured in windows administrative tools:

QString servername = "localhost";
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setHostName(servername);
db.setDatabaseName("YOUR_DSN_NAME");
db.setUserName("SYSDBA");
db.setPassword("masterkey");


问:
Problem understanding output of C program
I have the following program:

```<code>#include<stdio.h>
int main()
{
int i =257;
int *iptr =&i;
printf("%d%d",*((char*)iptr),*((char*)iptr+1));
return 0;
}
</code>```

The output is:

```<code>1 1
</code>```

I am not able to understand why the second value is 1.
Please explain.

答:
257 hexadecimally as 4 bytes = 0x00000101, which on Intel machines is stored in memory
as 01 01 00 00. iptr points to the first 01, and iptr+1 to the second.</p>

Body:
I have the following program:

#include<stdio.h>
int main()
{
int i =257;
int *iptr =&i;
printf("%d%d",*((char*)iptr),*((char*)iptr+1));
return 0;
}

The output is:

1 1

I am not able to understand why the second value is 1.
Please explain.


答:
You only fetch once a single row with $row = mysqli_fetch_assoc($result);.

You need to do that on a while loop like so:

```<code>$eventsquery = ("SELECT * FROM Careerevents JOIN Tickets ON CareerEvents.Event_ID=Tickets.Event_ID JOIN Potential_Employee ON Tickets.User_ID=Potential_Employee.User_ID WHERE Email = '$email'");
$result = mysqli_query($connection, $eventsquery);

// EDIT after your comment 'showing only last row'
// I'd do the following
$events = []; // or $events = Array();
while($row = mysqli_fetch_assoc($result)) {
    $events[] = $row;  // copy the whole row to a new entry in events-array
    //$eventname = $row['Event_Name'];
    //$startdate = $row['Start_Date'];
    //$enddate = $row['End_date'];
    //$description = $row['Event_Description'];
}

// now you have all your events in an array called $events
// and can display them in another loop like so:

foreach($events as $event) {
     echo "Name: ".$event['Event_Name'];
}
</code>```

Title: How to take values from multiple mysql rows?

Body:
I am new to web development, just started php.

Situation and What I'm trying to do: so I have a uni project where a user has a dashboard and has all the events and each event detail listed under neath it. So on the dashboard I want something like this:

Event name

Event Start date

Event description

Event name

Event Start date

Event description

And repeat until all the rows in the database have been outputted.

I have tried to use this code:

$eventsquery = ("SELECT * FROM Careerevents JOIN Tickets ON CareerEvents.Event_ID=Tickets.Event_ID JOIN Potential_Employee ON Tickets.User_ID=Potential_Employee.User_ID WHERE Email = '$email'");
$result = mysqli_query($connection, $eventsquery);
$row = mysqli_fetch_assoc($result);

    for ($i=0; $i < mysqli_num_rows($result); $i++) {
    $eventname = $row['Event_Name'];
    $startdate = $row['Start_Date'];
    $enddate = $row['End_date'];
    $description = $row['Event_Description'];
    }

And after this I just echoed the results in the html part of the page of the dashboard. But only the first row shows up. How would I do it if i want all the row results to show up.

Body:
You only fetch once a single row with $row = mysqli_fetch_assoc($result);.

You need to do that on a while loop like so:

$eventsquery = ("SELECT * FROM Careerevents JOIN Tickets ON CareerEvents.Event_ID=Tickets.Event_ID JOIN Potential_Employee ON Tickets.User_ID=Potential_Employee.User_ID WHERE Email = '$email'");
$result = mysqli_query($connection, $eventsquery);

// EDIT after your comment 'showing only last row'
// I'd do the following
$events = []; // or $events = Array();
while($row = mysqli_fetch_assoc($result)) {
    $events[] = $row;  // copy the whole row to a new entry in events-array
    //$eventname = $row['Event_Name'];
    //$startdate = $row['Start_Date'];
    //$enddate = $row['End_date'];
    //$description = $row['Event_Description'];
}

// now you have all your events in an array called $events
// and can display them in another loop like so:

foreach($events as $event) {
     echo "Name: ".$event['Event_Name'];
}