问:
Nesting arrays in LiveCode $_SESSION
I am developing a LiveCode Server CGI system that acts as a client web portal for an insurance business, by this I mean the client will log in and be able to see a whole host of information about their account. They'll be able to see their policy history, details of cover and download insurance certificates etc.

The basics are currently in place, clients can log in and the system connects to the database and pulls back their data.

HOWEVER, I would like to pre-load most of the important data during log in. For this I'm loading the data into $_SESSION, which works wonderfully for the basic user data (company name etc.)

As soon as I try to store an array of data in $_SESSION it simply doesn't work (e.g. data about each of their policies). If I store this data in a global array variable it works fine for the very next page loaded but it doesn't persist for the rest of the session.

Code below for loading the data from the DB

```<code>//load client info
put $_SESSION ["username"] into var1
put "SELECT * FROM client WHERE client_number_display_text_c = :1" into tQuery
put revQueryDatabase(tDatabaseID, tQuery, "var1") into tCursor

put revDatabaseColumnNamed(tCursor, "_pk_client") into $_SESSION["pk_client"]
put revDatabaseColumnNamed(tCursor, "client_account_status") into $_SESSION["account_status"]
put revDatabaseColumnNamed(tCursor, "client_category_aec") into $_SESSION["category"]
put revDatabaseColumnNamed(tCursor, "client_display_name_c") into $_SESSION["display_name_c"]

//load policy info
put $_SESSION["pk_client"] into var1
put "SELECT * FROM policy WHERE " & quote & "_fk_client" & quote & " = :1" into tQuery
put revQueryDatabase(tDatabaseID, tQuery, "var1") into tCursor

if tCursor is an integer then
   put 1 into i

   put revDatabaseColumnNamed(tCursor, "_fk_broker") into $_SESSION["policies"][i]["fk_broker"]
   put revDatabaseColumnNamed(tCursor, "_pk_policy") into $_SESSION["policies"][i]["pk_policy"]
   put revDatabaseColumnNamed(tCursor, "policy_date_expiry_actual_aec") into $_SESSION["policies"][i]["actual_expiry_date"]
   put revDatabaseColumnNamed(tCursor, "policy_date_inception_aec") into $_SESSION["policies"][i]["inception_date"]
   put revDatabaseColumnNamed(tCursor, "policy_display_cover_products_c") into $_SESSION["policies"][i]["display_products_c"]
   put revDatabaseColumnNamed(tCursor, "policy_total_price_inc_tax_admin_c") into $_SESSION["policies"][i]["total_price_inc_tax_admin_c"]
end if
</code>```

(I'll be using a loop to read all the policy data in once I get this bit working, hence the 'i' variable)

When displaying the main screen I then use the code

```<code>put "<tr>"
put "<td>" & $_SESSION["policies"][1]["display_products_c"] & "</td>"
put "<td>" & $_SESSION["policies"][1]["inception_date"] & "</td>"
put "<td>" & $_SESSION["policies"][1]["actual_expiry_date"] & "</td>"
put "<td>" & $_SESSION["policies"][1]["total_price_inc_tax_admin_c"] & "</td>"
put "</tr>"
</code>```

This simply displays a blank table row. I've tried putting $_SESSION into an array and using Combine but I simply get the top level data and nothing from the nested array

As a test I tried the following code

```<code>put "<tr>"
put "<td>" & $_SESSION["display_name_c"] & "</td>"
put "<td>" & $_SESSION["policies"][1]["inception_date"] & "</td>"
put "<td>" & $_SESSION["policies"][1]["actual_expiry_date"] & "</td>"
put "<td>" & $_SESSION["policies"][1]["total_price_inc_tax_admin_c"] & "</td>"
put "</tr>"
</code>```

In this case the Client's Display Name shows the correct data in the first column - all other columns are blank.

I have used exactly the same code but instead of $_SESSION I simply use gUser (defined as global gUser). When using gUser in place of S_SESSION all data displays exactly as expected - but doesn't persist.

It appears as though $_SESSION isn't able to store nested arrays. If this is the case then I'll simply store a text list of keys (cr delimited probably) in $_SESSION["policy_keys"] - and then use AJAX to load the data on the fly when needed. So I'm aware there are ways around it, but I thought I'd ask before making further changes.

I'm using LiveCode Server 8.1.2, on Windows Server 2016 Datacenter

Any help and guidance is most welcome

答:
First of all: sessions are usually stored in flat files so you will probably not gain much (if anything) by storing a lot of data in the session. Secondly if you have a heavy traffic site it might inflict performance and memory issues on your server.

Apart from that I have no idea why you shouldn't be able to save multidimensional arrays in a session, maybe it is saved in some specific way (maybe someone from the mothership can answer that). But here is a method I used a lot for sending "arrays" over the internet. I have no server reachable now so I can't test it for your specific case. But here goes the theory...

What you could try is to first create your array that you would like to save in a session and then use arrayEncode to store it in a session variable. Then you would at least get a flat session array:

```<code>put "data1" into tArr["key1"]
put "data2" into tArr["key2"]
...
put arrayEncode(tArr) into $_SESSION["myArray"]
</code>```

Then retrieving the array will be the opposite:

```<code>put arrayDecode($_SESSION["myArray"]) into tArr
</code>```

If $_SESSION doesn't like binary data (arrayEncode creates binary data) you can add another layer of encoding by using base64encode / -decode to ensure that you only save standard ascii codes. This is what I have done when sending arrays from one app to another over the net.

```<code>put base64Encode(arrayEncode(tArr)) into $_SESSION["myArray"]
put arrayDecode(base64Decode($_SESSION["myArray"])) into tArr
</code>```

But again I'm not sure you will benefit at all by saving a lot of data into a session as I guess it is faster to repopulate from the DB.

If you build a really complex array based on several different tables in the database and you can't create a single select statement that will retrieve all your data again another solution might be to store your array in a single table using the above method. But I strongly suggest that you do some speed tests before you dive into a lot of extra programming...

Title: Nesting arrays in LiveCode $_SESSION

Body:
I am developing a LiveCode Server CGI system that acts as a client web portal for an insurance business, by this I mean the client will log in and be able to see a whole host of information about their account. They'll be able to see their policy history, details of cover and download insurance certificates etc.

The basics are currently in place, clients can log in and the system connects to the database and pulls back their data.

HOWEVER, I would like to pre-load most of the important data during log in. For this I'm loading the data into $_SESSION, which works wonderfully for the basic user data (company name etc.)

As soon as I try to store an array of data in $_SESSION it simply doesn't work (e.g. data about each of their policies). If I store this data in a global array variable it works fine for the very next page loaded but it doesn't persist for the rest of the session.

Code below for loading the data from the DB

//load client info
put $_SESSION ["username"] into var1
put "SELECT * FROM client WHERE client_number_display_text_c = :1" into tQuery
put revQueryDatabase(tDatabaseID, tQuery, "var1") into tCursor

put revDatabaseColumnNamed(tCursor, "_pk_client") into $_SESSION["pk_client"]
put revDatabaseColumnNamed(tCursor, "client_account_status") into $_SESSION["account_status"]
put revDatabaseColumnNamed(tCursor, "client_category_aec") into $_SESSION["category"]
put revDatabaseColumnNamed(tCursor, "client_display_name_c") into $_SESSION["display_name_c"]

//load policy info
put $_SESSION["pk_client"] into var1
put "SELECT * FROM policy WHERE " & quote & "_fk_client" & quote & " = :1" into tQuery
put revQueryDatabase(tDatabaseID, tQuery, "var1") into tCursor

if tCursor is an integer then
   put 1 into i

   put revDatabaseColumnNamed(tCursor, "_fk_broker") into $_SESSION["policies"][i]["fk_broker"]
   put revDatabaseColumnNamed(tCursor, "_pk_policy") into $_SESSION["policies"][i]["pk_policy"]
   put revDatabaseColumnNamed(tCursor, "policy_date_expiry_actual_aec") into $_SESSION["policies"][i]["actual_expiry_date"]
   put revDatabaseColumnNamed(tCursor, "policy_date_inception_aec") into $_SESSION["policies"][i]["inception_date"]
   put revDatabaseColumnNamed(tCursor, "policy_display_cover_products_c") into $_SESSION["policies"][i]["display_products_c"]
   put revDatabaseColumnNamed(tCursor, "policy_total_price_inc_tax_admin_c") into $_SESSION["policies"][i]["total_price_inc_tax_admin_c"]
end if

(I'll be using a loop to read all the policy data in once I get this bit working, hence the 'i' variable)

When displaying the main screen I then use the code

put "
"
put "" & $_SESSION["policies"][1]["display_products_c"] & "	"
put "" & $_SESSION["policies"][1]["inception_date"] & "	"
put "" & $_SESSION["policies"][1]["actual_expiry_date"] & "	"
put "" & $_SESSION["policies"][1]["total_price_inc_tax_admin_c"] & "	"
put "
"

This simply displays a blank table row. I've tried putting $_SESSION into an array and using Combine but I simply get the top level data and nothing from the nested array

As a test I tried the following code

put "
"
put "" & $_SESSION["display_name_c"] & "	"
put "" & $_SESSION["policies"][1]["inception_date"] & "	"
put "" & $_SESSION["policies"][1]["actual_expiry_date"] & "	"
put "" & $_SESSION["policies"][1]["total_price_inc_tax_admin_c"] & "	"
put "
"

In this case the Client's Display Name shows the correct data in the first column - all other columns are blank.

I have used exactly the same code but instead of $_SESSION I simply use gUser (defined as global gUser). When using gUser in place of S_SESSION all data displays exactly as expected - but doesn't persist.

It appears as though $_SESSION isn't able to store nested arrays. If this is the case then I'll simply store a text list of keys (cr delimited probably) in $_SESSION["policy_keys"] - and then use AJAX to load the data on the fly when needed. So I'm aware there are ways around it, but I thought I'd ask before making further changes.

I'm using LiveCode Server 8.1.2, on Windows Server 2016 Datacenter

Any help and guidance is most welcome

Body:
First of all: sessions are usually stored in flat files so you will probably not gain much (if anything) by storing a lot of data in the session. Secondly if you have a heavy traffic site it might inflict performance and memory issues on your server.

Apart from that I have no idea why you shouldn't be able to save multidimensional arrays in a session, maybe it is saved in some specific way (maybe someone from the mothership can answer that). But here is a method I used a lot for sending "arrays" over the internet. I have no server reachable now so I can't test it for your specific case. But here goes the theory...

What you could try is to first create your array that you would like to save in a session and then use arrayEncode to store it in a session variable. Then you would at least get a flat session array:

put "data1" into tArr["key1"]
put "data2" into tArr["key2"]
...
put arrayEncode(tArr) into $_SESSION["myArray"]

Then retrieving the array will be the opposite:

put arrayDecode($_SESSION["myArray"]) into tArr

If $_SESSION doesn't like binary data (arrayEncode creates binary data) you can add another layer of encoding by using base64encode / -decode to ensure that you only save standard ascii codes. This is what I have done when sending arrays from one app to another over the net.

put base64Encode(arrayEncode(tArr)) into $_SESSION["myArray"]
put arrayDecode(base64Decode($_SESSION["myArray"])) into tArr

But again I'm not sure you will benefit at all by saving a lot of data into a session as I guess it is faster to repopulate from the DB.

If you build a really complex array based on several different tables in the database and you can't create a single select statement that will retrieve all your data again another solution might be to store your array in a single table using the above method. But I strongly suggest that you do some speed tests before you dive into a lot of extra programming...


来源: stackexchange

问:
how to add new entries in struct which is member of class using inheritance
```<code>class A
{
    public:
        typedef struct st
        {
            int x;
            int y;
        }st;
};
</code>```

I have class A which has a structure as public member variable. I want to add some new entries in above struct st. I used inheritance. is it possible to add new entries in that structure without changing it's name (st).

```<code>class B:public A
{
};
</code>```

Please help me out.

答:
If I'm understanding your question correctly, yes, you can extend st inside B.  Add an inner struct in B that inherits from A::st.

https://godbolt.org/g/sWfYWY

```<code>class A
{
public:
    struct St
    {
        int x;
        int y;
    };
    St st;
};

class B : public A
{
public:
    struct St : public A::St
    {
        int z;
    };
    St st;
};

int main()
{
    A a;
    a.st.x = 1;
    a.st.y = 2;

    B b;
    b.st.x = 3;
    b.st.y = 4;
    b.st.z = 5;

    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
class A
{
    public:
        typedef struct st
        {
            int x;
            int y;
        }st;
};

I have class A which has a structure as public member variable. I want to add some new entries in above struct st. I used inheritance. is it possible to add new entries in that structure without changing it's name (st).

class B:public A
{
};

Please help me out.

Body:
If I'm understanding your question correctly, yes, you can extend st inside B.  Add an inner struct in B that inherits from A::st.

https://godbolt.org/g/sWfYWY

class A
{
public:
    struct St
    {
        int x;
        int y;
    };
    St st;
};

class B : public A
{
public:
    struct St : public A::St
    {
        int z;
    };
    St st;
};

int main()
{
    A a;
    a.st.x = 1;
    a.st.y = 2;

    B b;
    b.st.x = 3;
    b.st.y = 4;
    b.st.z = 5;

    return 0;
}


问:
Rails3, oauth2 and canvas facebook application - stay in the fb canvas please
I'm trying to make a canvas facebook app using rails 3 and oauth2.
It kind of works fine following the steps here https://github.com/intridea/oauth2

So when I go to the app in FB, it triggers the methods set by oauth2 BUT, it asks the user to give the permissions OUTSIDE of the canvas, it goes out of FB. Then when the user gives permission it goes where it is supposed to go in the application but again everything OUTSIDE FB.

After giving the permissions if I go to the app inside FB then it shows the app within the canvas.

Anyone familiar with this?

Cheers.

答:
As I know, the page, where you give permissions to app should be outside of app page.
And if you want for than be redirected to your FB app page, you should use

```<code>access_token = client.web_server.get_access_token(params[:code], :redirect_uri => redirect_uri)

def redirect_uri
    uri = URI.parse(request.url)
    uri.path = '/fbcanvas'
    uri.query = nil
    uri.to_s
end
</code>```

redirect_uri method is specially used here, so when you are redirected from your fb app page, you'll return there, and if you are redirected from your site itself, you'll return to your site.

ContentLicense: CC BY-SA 2.5

Body:
As I know, the page, where you give permissions to app should be outside of app page.
And if you want for than be redirected to your FB app page, you should use

access_token = client.web_server.get_access_token(params[:code], :redirect_uri => redirect_uri)

def redirect_uri
    uri = URI.parse(request.url)
    uri.path = '/fbcanvas'
    uri.query = nil
    uri.to_s
end

redirect_uri method is specially used here, so when you are redirected from your fb app page, you'll return there, and if you are redirected from your site itself, you'll return to your site.


问:
Why does `std::make_shared` perform two separate allocations with `-fno-rtti`?
```<code>#include <memory>
struct foo { };
int main() { std::make_shared<foo>(); }
</code>```

The asssembly generated by both g++7 and clang++5 with -fno-exceptions -Ofast for the code above:

Contains a single call to operator new if -fno-rtti is not passed.

Contains two separate calls to operator new if -fno-rtti is passed.

This can be easily verified on gcc.godbolt.org (clang++5 version):

Why is this happening? Why does disabling RTTI prevent make_shared from unifying the object and control block allocations?

答:
Why does disabling RTTI prevent make_shared from unifying the object and control block allocations?

You can see from the assembler (just pasting the text is really preferable to both linking and to taking pictures of it) that the unified version doesn't allocate a simple foo but an std::_Sp_counted_ptr_inplace, and further that that type has a vtable (recall it needs a virtual destructor in general, to cope with custom deleters)

```<code>mov QWORD PTR [rax], OFFSET FLAT:
  vtable for
  std::_Sp_counted_ptr_inplace<foo, std::allocator<foo>,
  (__gnu_cxx::_Lock_policy)2>+16
</code>```

If you disable RTTI, it can't generate the inplace counted pointer because that needs to be virtual.

Note that the non-inplace version still refers to a vtable, but it seems to just be storing the de-virtualized destructor address directly.

Body:
#include <memory>
struct foo { };
int main() { std::make_shared<foo>(); }

The asssembly generated by both g++7 and clang++5 with -fno-exceptions -Ofast for the code above:

Contains a single call to operator new if -fno-rtti is not passed.

Contains two separate calls to operator new if -fno-rtti is passed.

This can be easily verified on gcc.godbolt.org (clang++5 version):

Why is this happening? Why does disabling RTTI prevent make_shared from unifying the object and control block allocations?

Body:
Why does disabling RTTI prevent make_shared from unifying the object and control block allocations?

You can see from the assembler (just pasting the text is really preferable to both linking and to taking pictures of it) that the unified version doesn't allocate a simple foo but an std::_Sp_counted_ptr_inplace, and further that that type has a vtable (recall it needs a virtual destructor in general, to cope with custom deleters)

mov QWORD PTR [rax], OFFSET FLAT:
  vtable for
  std::_Sp_counted_ptr_inplace<foo, std::allocator<foo>,
  (__gnu_cxx::_Lock_policy)2>+16

If you disable RTTI, it can't generate the inplace counted pointer because that needs to be virtual.

Note that the non-inplace version still refers to a vtable, but it seems to just be storing the de-virtualized destructor address directly.


问:
Deleting files in specific sub-directories created at random
I would like to create a script that would delete files older than 5 days from a certain set of subfolders. I'm aware of the following command:

```<code>find /path/to/files* -mtime +5 -exec rm {} \;
</code>```

The problem that i'm facing at this point, needs some clarification of the structure of my folders:

/cassandra/data/data/cpms/basket/snapshots

  /cassandra/data/data/customer/customer/snapshots

  /cassandra/data/data/profile/customer/snapshots

I want my script to only look in the snapshots folders and clear out files only from there, the problem is that at any point, the application can create a new folder under the 'data' directory, or under a current existing directory. i.e.

/cassandra/data/data/cpms/new_basket/snapshots

OR

/cassandra/data/data/new_category/new_folder/snapshots

So to hard code the directories will be irrelevant as soon as the application creates a new structure, it won't work effectively anymore until I update the code.

Is there a way to do a command like this:

```<code>find /cassandra/data/data <look in *this* directory for a folder named snapshots [it might still be 1 or 2 levels down] in the folders below data> & delete only files older than 5 days in snapshot folders found?
</code>```

So to clarify [I hope], my script should go into the /cassandra/data/data directory, find all the folders named 'snapshots' and delete only files from those folders.

答:
Assuming you are in the top level directory where you want to start searching for snapshot folders (note - replaced your '-mtime 5 -exec rm' with just a -ls so you can verify it is finding the folders properly): </p>

```<code>find . -name snapshot -a -type d | while read a ; do find "$a" -ls ; done
</code>```

<p>or, even easier: </p>

```<code>find . -path '*/snapshot/*' -a -type f -a -mtime 5 -exec ls -l {} \;
</code>```

Body:
I would like to create a script that would delete files older than 5 days from a certain set of subfolders. I'm aware of the following command:

find /path/to/files* -mtime +5 -exec rm {} \;

The problem that i'm facing at this point, needs some clarification of the structure of my folders:

/cassandra/data/data/cpms/basket/snapshots

  /cassandra/data/data/customer/customer/snapshots

  /cassandra/data/data/profile/customer/snapshots

I want my script to only look in the snapshots folders and clear out files only from there, the problem is that at any point, the application can create a new folder under the 'data' directory, or under a current existing directory. i.e.

/cassandra/data/data/cpms/new_basket/snapshots

OR

/cassandra/data/data/new_category/new_folder/snapshots

So to hard code the directories will be irrelevant as soon as the application creates a new structure, it won't work effectively anymore until I update the code.

Is there a way to do a command like this:

find /cassandra/data/data <look in *this* directory for a folder named snapshots [it might still be 1 or 2 levels down] in the folders below data> & delete only files older than 5 days in snapshot folders found?

So to clarify [I hope], my script should go into the /cassandra/data/data directory, find all the folders named 'snapshots' and delete only files from those folders.

Body:
Assuming you are in the top level directory where you want to start searching for snapshot folders (note - replaced your '-mtime 5 -exec rm' with just a -ls so you can verify it is finding the folders properly):

find . -name snapshot -a -type d | while read a ; do find "$a" -ls ; done

or, even easier:

find . -path '*/snapshot/*' -a -type f -a -mtime 5 -exec ls -l {} \;


问:
Getting the public path on online server in laravel project
I Need to get the public path of my project laravel online , it's working with this line fine at local server but online it's not :

```<code>(public_path().'/website/'.$path);
</code>```

So the problem is with that : (public_path()) , how to make it working fine on online server too .

答:
First you define below code in controller.php :

```<code>   class myproject extends Controller
   {

     function __construct()
    {
            define('HTTP_ROOT', asset('/') . 'public/');
    }
  }

 new myproject();
</code>```

and then you use HTTP_ROOT in place of public_path().

Body:
I Need to get the public path of my project laravel online , it's working with this line fine at local server but online it's not :

(public_path().'/website/'.$path);

So the problem is with that : (public_path()) , how to make it working fine on online server too .

Body:
First you define below code in controller.php :

   class myproject extends Controller
   {

     function __construct()
    {
            define('HTTP_ROOT', asset('/') . 'public/');
    }
  }

 new myproject();

and then you use HTTP_ROOT in place of public_path().


问:
With highcharts, is it possible to adapt tooltip text with column color ?
I would like to know it is possible to adapt tooltip text with column color ?

For example, if my column is blue, so my tooltip title will be "Blue Title" and if it's orange, then the tooltip title will be "Orange Title".

Is that possible ?

Thanks in advance !

答:
It is possible, you can use tooltip formatter, get color from series and return a span with custom style containing color value from series.

```<code>const options = {
  chart: { type: 'column' },
  series: [...Array(5)].map(() => ({ data: [...Array(3)].map(Math.random) })),
  tooltip: {
    formatter () {
        return `<span style="color: ${this.series.color}">
        My new tooltip
            x: ${this.x} y: ${this.y}
      </span>`
    }
  }
}

const chart = Highcharts.chart('container', options)
</code>```

https://jsfiddle.net/4p12sf2k/

Body:
It is possible, you can use tooltip formatter, get color from series and return a span with custom style containing color value from series.

const options = {
  chart: { type: 'column' },
  series: [...Array(5)].map(() => ({ data: [...Array(3)].map(Math.random) })),
  tooltip: {
    formatter () {
        return `<span style="color: ${this.series.color}">
        My new tooltip
            x: ${this.x} y: ${this.y}
      </span>`
    }
  }
}

const chart = Highcharts.chart('container', options)

https://jsfiddle.net/4p12sf2k/


问:
On coursera R-programming course Assignment 2 Lexical Scoping
I'm Using Win7 64x Rstudio Version 3.3.2.

The following functions is assignmet2 solution that other people submitted.

```<code>makeCacheMatrix <- function(x = matrix()) {
    inv <- NULL
    set <- function(y) {
            x <<- y
            inv <<- NULL
    }
    get <- function() x
    setInverse <- function(inverse) inv <<- inverse
    getInverse <- function() inv
    list(set = set,
         get = get,
         setInverse = setInverse,
         getInverse = getInverse)
}
</code>```

First in the function makeCacheMatrix, why does 'set function' use variable 'y'?

Is it simply used to tell us how to use '<<-'?

Secondly, In 'get function', why is variable 'x' followed by the parentheses of the function? ( 'setInverse function - inv<<-inverse' , 'getInverse function - inv' are the same. )

答:
x <<- y creates x, which is then retrieved by get(). Note that get is also a base function and is being overwritten here. I would advocate in avoiding this, even though it's confined to a function. An ad hoc solution would be to reach base get function through base::get.

Line get <- function() x is a "short" version of

```<code>get <- function() {
  x
}
</code>```

Short version will work if you have only one line or separate statements using ;. The biggest beef I have with this piece of code is no use of argument. This may be fine with Java or some other language, but I don't consider that an R way. Modifying objects like this can lead to unintended behavior which could lead to painstaking debugging.

setInverse and getInverse are not the same. What they do is set inverse or get it.

Body:
I'm Using Win7 64x Rstudio Version 3.3.2.

The following functions is assignmet2 solution that other people submitted.

makeCacheMatrix <- function(x = matrix()) {
    inv <- NULL
    set <- function(y) {
            x <<- y
            inv <<- NULL
    }
    get <- function() x
    setInverse <- function(inverse) inv <<- inverse
    getInverse <- function() inv
    list(set = set,
         get = get,
         setInverse = setInverse,
         getInverse = getInverse)
}

First in the function makeCacheMatrix, why does 'set function' use variable 'y'?

Is it simply used to tell us how to use '<<-'?

Secondly, In 'get function', why is variable 'x' followed by the parentheses of the function? ( 'setInverse function - inv<<-inverse' , 'getInverse function - inv' are the same. )

Body:
x <<- y creates x, which is then retrieved by get(). Note that get is also a base function and is being overwritten here. I would advocate in avoiding this, even though it's confined to a function. An ad hoc solution would be to reach base get function through base::get.

Line get <- function() x is a "short" version of

get <- function() {
  x
}

Short version will work if you have only one line or separate statements using ;. The biggest beef I have with this piece of code is no use of argument. This may be fine with Java or some other language, but I don't consider that an R way. Modifying objects like this can lead to unintended behavior which could lead to painstaking debugging.

setInverse and getInverse are not the same. What they do is set inverse or get it.


问:
CodeIgniter - I want to define array like config array in config.php file
I want to define my array like config array in config.php file. So I can access this array any where in my view.

config.php

```<code>$config['base_url'] = '';
$my_array['app_admin_panel'] = '';
$my_array['app_admin_panel_assets'] = '';
</code>```

答:
One of the simplest way to define array as a config item is like below:

```<code>$config['myArray'] = array(
'name'=>'test',
'rank'=>22,
'division'=>'first');
</code>```

Then fetch the config item using:

```<code>$data = $this->config->item('myArray');
print_r($data);// it prints your array you define in config file
echo $data['rank']; //prints 22
</code>```

Body:
I want to define my array like config array in config.php file. So I can access this array any where in my view.

config.php

$config['base_url'] = '';
$my_array['app_admin_panel'] = '';
$my_array['app_admin_panel_assets'] = '';

Body:
One of the simplest way to define array as a config item is like below:

$config['myArray'] = array(
'name'=>'test',
'rank'=>22,
'division'=>'first');

Then fetch the config item using:

$data = $this->config->item('myArray');
print_r($data);// it prints your array you define in config file
echo $data['rank']; //prints 22


问:
Check if column value is in other columns in pandas
I have the following dataframe in pandas

```<code>  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge
</code>```

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

答:
OneHotEncoder approach:

```<code>In [165]: x = pd.get_dummies(df.drop('target',1), prefix='', prefix_sep='')

In [166]: x
Out[166]:
   bridge  cat  dog  cat  shoe  bridge  brush  shoe
0       1    0    0    1     0       0      1     0
1       0    0    1    1     0       0      0     1
2       0    1    0    0     1       1      0     0

In [167]: x[df['target']].eq(1).any(1)
Out[167]:
0    True
1    True
2    True
dtype: bool
</code>```

Explanation:

```<code>In [168]: x[df['target']]
Out[168]:
   cat  cat  brush  bridge  bridge
0    0    1      1       1       0
1    0    1      0       0       0
2    1    0      0       0       1
</code>```

Body:
I have the following dataframe in pandas

  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

Body:
OneHotEncoder approach:

In [165]: x = pd.get_dummies(df.drop('target',1), prefix='', prefix_sep='')

In [166]: x
Out[166]:
   bridge  cat  dog  cat  shoe  bridge  brush  shoe
0       1    0    0    1     0       0      1     0
1       0    0    1    1     0       0      0     1
2       0    1    0    0     1       1      0     0

In [167]: x[df['target']].eq(1).any(1)
Out[167]:
0    True
1    True
2    True
dtype: bool

Explanation:

In [168]: x[df['target']]
Out[168]:
   cat  cat  brush  bridge  bridge
0    0    1      1       1       0
1    0    1      0       0       0
2    1    0      0       0       1


问:
PHP Google_Client insert youtube playlistItem (2-leg-oauth)
My web using the PHP Google_Client to insert the youtube playlistItem in my playlist (2-leg-oauth),
and get the error
Client is unauthorized to retrieve access tokens using this method.
Where can I setting the server using my-account@gmail.com to have the same permission to access google api
such like insert playlistItem,
or is there having another way without using my-account@gmail.com to get same permission?

PHP Code:

```<code>putenv('GOOGLE_APPLICATION_CREDENTIALS=client_secret.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/youtube');
$client->setSubject('my-account@gmail.com');
</code>```

答:
If you have delegated domain-wide access to the service account and
  you want to impersonate a user account, specify the email address of
  the user account use

```<code>$client->setSubject($user_to_impersonate);
</code>```

The YouTube API doesn't support delegated domain-wide access or service accounts.  You will need to authenticate with Oauth2.

see PHP Code Samples

Body:
My web using the PHP Google_Client to insert the youtube playlistItem in my playlist (2-leg-oauth),
and get the error
Client is unauthorized to retrieve access tokens using this method.
Where can I setting the server using my-account@gmail.com to have the same permission to access google api
such like insert playlistItem,
or is there having another way without using my-account@gmail.com to get same permission?

PHP Code:

putenv('GOOGLE_APPLICATION_CREDENTIALS=client_secret.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/youtube');
$client->setSubject('my-account@gmail.com');

Body:
If you have delegated domain-wide access to the service account and
  you want to impersonate a user account, specify the email address of
  the user account use

$client->setSubject($user_to_impersonate);

The YouTube API doesn't support delegated domain-wide access or service accounts.  You will need to authenticate with Oauth2.

see PHP Code Samples


问:
mbed Region m_data_2 overflowed with stack and heap
I am writing an application for Mbed OS that will run on a K64F board. I have different threads running, using the RTOS capabilities of the system.

I need to handle a relatively big string for showing results in a JSON format. I have definned it as a char array. Initially it was defined to be 256 chars long and was working correclty, but when I have increased the size to 2048 to actually fit the needs of the app

char rData[2048];

I get this error on compilation:

```<code>c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: ./BUILD/K64F/GCC_ARM/02_device.elf section `.heap' will not fit in region `m_data_2'
c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: Region m_data_2 overflowed with stack and heap
c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: region `m_data_2' overflowed by 22944 bytes
collect2.exe: error: ld returned 1 exit status
[ERROR] c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: ./BUILD/K64F/GCC_ARM/02_device.elf section `.heap' will not fit in region `m_data_2'
c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: Region m_data_2 overflowed with stack and heap
c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: region `m_data_2' overflowed by 22944 bytes
collect2.exe: error: ld returned 1 exit status
</code>```

I have not found any reference on how to increase the space reserved for this need.

What am I missing?

答:
Declare the variable on the heap, not on the stack:

```<code>char* rData = (char*)malloc(2048);
// potentially, don't always malloc 2048 bytes, but only the amount you need
</code>```

Don't forget to call free(rData) when you're done.

Body:
I am writing an application for Mbed OS that will run on a K64F board. I have different threads running, using the RTOS capabilities of the system.

I need to handle a relatively big string for showing results in a JSON format. I have definned it as a char array. Initially it was defined to be 256 chars long and was working correclty, but when I have increased the size to 2048 to actually fit the needs of the app

char rData[2048];

I get this error on compilation:

c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: ./BUILD/K64F/GCC_ARM/02_device.elf section `.heap' will not fit in region `m_data_2'
c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: Region m_data_2 overflowed with stack and heap
c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: region `m_data_2' overflowed by 22944 bytes
collect2.exe: error: ld returned 1 exit status
[ERROR] c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: ./BUILD/K64F/GCC_ARM/02_device.elf section `.heap' will not fit in region `m_data_2'
c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: Region m_data_2 overflowed with stack and heap
c:/program files (x86)/gnu tools arm embedded/6.2 2016q4/bin/../lib/gcc/arm-none-eabi/6.2.1/../../../../arm-none-eabi/bin/ld.exe: region `m_data_2' overflowed by 22944 bytes
collect2.exe: error: ld returned 1 exit status

I have not found any reference on how to increase the space reserved for this need.

What am I missing?

Body:
Declare the variable on the heap, not on the stack:

char* rData = (char*)malloc(2048);
// potentially, don't always malloc 2048 bytes, but only the amount you need

Don't forget to call free(rData) when you're done.


问:
Django Rest Api with Pandas
I am using django-rest-framework to make an api of my data. I am making an app that takes into account user data and remove outliers from that data using Pandas. I am able to present my data on frontend using django templates but somehow I am not able to make an API containing the statistical data using django-rest-framework . Can someone explain it and please help me to rectify my errors and also provide the necessary code

Here is my code

```<code>class Data(models.Model):
    Name = models.CharField(max_length=30,null=True,blank=True)
    Age = models.IntegerField(null=True,blank=True)
    Weight = models.FloatField(null=True,blank=True)
    Height = models.FloatField(null=True,blank=True)
    Sugar = models.FloatField(null=True,blank=True)
    def __unicode__(self):
        return self.Name
</code>```

My Serializer Class

```<code>class DataSerializer(serializers.ModelSerializer):
    class Meta:
        model = Data
        fields = '__all__'
</code>```

my views.py

```<code>def my_view(request):
    con = sqlite3.connect("db.sqlite3")
    df = pd.read_sql_query("SELECT * from visualapp_health", con)
    a = df.fillna(0)
    a['x-Mean'] = abs(a['Age'] - a['Age'].mean())
    a['1.96*std'] = 1.96*a['Age'].std()
    a['Outlier'] = abs(a['Age'] - a['Age'].mean()) > 1.96*a['Age'].std()
    con.close()
    return render(request, 'visual.html', {'visual': a})
</code>```

I am able to get all the Data when using Django templates but somehow I don't able to understand how to make an API of all the data using django-rest- framework.

答: I finally got it I used django-pandas library and it worked and there is no need to connect to the database just convert your django queryset to pandas dataframe.</p>

Title: Django Rest Api with Pandas

Body:
I am using django-rest-framework to make an api of my data. I am making an app that takes into account user data and remove outliers from that data using Pandas. I am able to present my data on frontend using django templates but somehow I am not able to make an API containing the statistical data using django-rest-framework . Can someone explain it and please help me to rectify my errors and also provide the necessary code

Here is my code

class Data(models.Model):
    Name = models.CharField(max_length=30,null=True,blank=True)
    Age = models.IntegerField(null=True,blank=True)
    Weight = models.FloatField(null=True,blank=True)
    Height = models.FloatField(null=True,blank=True)
    Sugar = models.FloatField(null=True,blank=True)
    def __unicode__(self):
        return self.Name

My Serializer Class

class DataSerializer(serializers.ModelSerializer):
    class Meta:
        model = Data
        fields = '__all__'

my views.py

def my_view(request):
    con = sqlite3.connect("db.sqlite3")
    df = pd.read_sql_query("SELECT * from visualapp_health", con)
    a = df.fillna(0)
    a['x-Mean'] = abs(a['Age'] - a['Age'].mean())
    a['1.96*std'] = 1.96*a['Age'].std()
    a['Outlier'] = abs(a['Age'] - a['Age'].mean()) > 1.96*a['Age'].std()
    con.close()
    return render(request, 'visual.html', {'visual': a})

I am able to get all the Data when using Django templates but somehow I don't able to understand how to make an API of all the data using django-rest- framework.


问:
Displaying the App version in a TextView
I want to display my current app version in a TextView, the activity the Textview is in is not my MainACtivity.
I used the folowing code:

```<code>public class informatie extends ActionBarActivity {

    public String versionName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_informatie);

        try {
           versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Typeface impact = Typeface.createFromAsset(getAssets(), "fonts/Impact.ttf");

        TextView versieVak = (TextView) findViewById(R.id.versieView);
        versieVak.setText(versionName);
        Toast.makeText(getApplicationContext(), "KLIK", Toast.LENGTH_LONG).show();
        versieVak.setTypeface(impact);
        versieVak.setTextColor(getResources().getColor(R.color.antraciet));
        versieVak.setTextSize(10, TypedValue.COMPLEX_UNIT_SP);

    }
</code>```

The Layout.xml

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.KnapperDev.knapper.jrw.informatie">

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/imageView"
            android:src="@drawable/overeenkomst"
            android:layout_marginBottom="249dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:id="@+id/versieView"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="155dp" />
    </RelativeLayout>
</code>```

But when i open the activity on my phone there is nothing in the TextView.
I made a Toast to check if versieVak.setText(versionName); was used.
it just doesn't display anything. Any idea what i am doing wrong?

答:
Try this :</p>
```<code>    // Import the BuildConfig at the top of the file
    import yourpackagename.BuildConfig

    ...

    // in your method, just use:
    TextView versionName = findViewById(R.id.textName);
    versionName.setText("version : " + BuildConfig.VERSION_NAME);
</code>```

Body:
I want to display my current app version in a TextView, the activity the Textview is in is not my MainACtivity.
I used the folowing code:

public class informatie extends ActionBarActivity {

    public String versionName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_informatie);

        try {
           versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        Typeface impact = Typeface.createFromAsset(getAssets(), "fonts/Impact.ttf");

        TextView versieVak = (TextView) findViewById(R.id.versieView);
        versieVak.setText(versionName);
        Toast.makeText(getApplicationContext(), "KLIK", Toast.LENGTH_LONG).show();
        versieVak.setTypeface(impact);
        versieVak.setTextColor(getResources().getColor(R.color.antraciet));
        versieVak.setTextSize(10, TypedValue.COMPLEX_UNIT_SP);

    }

The Layout.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.KnapperDev.knapper.jrw.informatie">

        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/imageView"
            android:src="@drawable/overeenkomst"
            android:layout_marginBottom="249dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:id="@+id/versieView"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="155dp" />
    </RelativeLayout>

But when i open the activity on my phone there is nothing in the TextView.
I made a Toast to check if versieVak.setText(versionName); was used.
it just doesn't display anything. Any idea what i am doing wrong?

Body:
Try this :

    // Import the BuildConfig at the top of the file
    import yourpackagename.BuildConfig

    ...

    // in your method, just use:
    TextView versionName = findViewById(R.id.textName);
    versionName.setText("version : " + BuildConfig.VERSION_NAME);

ContentLicense: CC BY-SA 4.0


问:
Show user details using ClickHandler
I have a list of users, how do I click through to the details for each user?

Do I need to do the api call in this component?

Any help much appreciated

Here is my user list:

```<code>import React, { Component } from 'react';
import { Table } from 'react-bootstrap';

export default class Users extends Component {

showDetails(){

// navigate to details page

}

render() {
    return (
        <Table responsive>
        <thead>
          <tr>
            <th>id</th>
            <th>name</th>
            <th>Username</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
         {this.props.users.map((user, index) => (
            <tr onClick={showDetails}>
                <td>{user.id}</td>
                <td>{user.name}</td>
                <td>{user.username}</td>
                <td>{user.email}</td>
            </tr>
        ))}
        </tbody>
      </Table>
    );
}
}
</code>```

Here my component that gets the users, do I need to:

```<code>class App extends Component {

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

getUsers(){
 axios.get('http://jsonplaceholder.typicode.com/users')
 .then((response) => {
     this.setState({ users: response.data });
 })
 .catch((error) => {
     console.log(error);
 });
}

componentDidMount(){
  this.getUsers();
}

  render() {
      return (<div>

    <Users users={this.state.users} />

  </div>);
  }
}

export default App;
</code>```

答:
To navigate to user details page you can use react router like this

```<code>import { browserHistory } from "react-router";
...
<tr onClick={() => browserHistory.push(`/user-info/${user.id}`)}>
...
</code>```

Then to get info about users you need to use 'redux' so that you load users info to common storage and since be able to recieve it from any component.

Title: Show user details using ClickHandler

Body:
I have a list of users, how do I click through to the details for each user?

Do I need to do the api call in this component?

Any help much appreciated

Here is my user list:

import React, { Component } from 'react';
import { Table } from 'react-bootstrap';

export default class Users extends Component {

showDetails(){

// navigate to details page

}

render() {
    return (

            id
            name
            Username
            Email

         {this.props.users.map((user, index) => (

                {user.id}
                {user.name}
                {user.username}
                {user.email}

        ))}

    );
}
}

Here my component that gets the users, do I need to:

class App extends Component {

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

getUsers(){
 axios.get('http://jsonplaceholder.typicode.com/users')
 .then((response) => {
     this.setState({ users: response.data });
 })
 .catch((error) => {
     console.log(error);
 });
}

componentDidMount(){
  this.getUsers();
}

  render() {
      return (

    <Users users={this.state.users} />

);
  }
}

export default App;

Body:
To navigate to user details page you can use react router like this

import { browserHistory } from "react-router";
...
<tr onClick={() => browserHistory.push(`/user-info/${user.id}`)}>
...

Then to get info about users you need to use 'redux' so that you load users info to common storage and since be able to recieve it from any component.


问:
My highscore doesn't match my points at sometimes
When I get my points(poang) to highscore when I hit the blocks with 5 points. They will not update the same, sometimes points(poang) will be 18 and highscore will be 20.

(Sorry about my bad english)

poang = points

linje = line

liv = lives

boll = ball

poang = points

blockröd = blockred

blockgrön = blockgreen

```<code>public class Game1 : Game
{
 GraphicsDeviceManager graphics;
 SpriteBatch spriteBatch;
 SpriteFont spritefont;
 Texture2D linje_texture;
 Texture2D linjeliten_texture;
 Texture2D boll_texture;
 Texture2D blockröd_texture;
 Texture2D blockgrön_texture;
 Texture2D gameover_texture;
 Rectangle linje_rect;
 Rectangle linjeliten_rect;
 Rectangle boll_rect;
 Rectangle blockröd_rect;
 Rectangle blockgrön_rect;
 Rectangle gameover_rect;

 Vector2 linje_speed;
 Vector2 linjeliten_speed;
 Vector2 boll_speed;

 Random random;

 StreamReader sr;
 StreamWriter sw;

 int liv = 3;
 int poang = 0;
 int highscore;

 List<Rectangle> block = new List<Rectangle>();
 List<Rectangle> block2 = new List<Rectangle>();

 bool Start = false;
 bool holdingleft = false;
 bool holdingright = false;
 bool resetballspeed = false;

 public Game1()
 {
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";

    graphics.PreferredBackBufferWidth = 760;
    graphics.PreferredBackBufferHeight = 620;
}

protected override void Initialize()
{
    random = new Random();
    linje_speed.X = 6f;
    linjeliten_speed.X = 6f;
    boll_speed.X = random.Next(-1, 1);
    boll_speed.Y = 7f;

    sr = new StreamReader("highscore.txt");
    highscore = int.Parse(sr.ReadLine());
    sr.Close();

    base.Initialize();
}

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    spritefont = Content.Load<SpriteFont>("Fonts/Myfont");
    linje_texture = Content.Load<Texture2D>("Pics/linje-lång");
    linjeliten_texture = Content.Load<Texture2D>("Pics/linje");
    boll_texture = Content.Load<Texture2D>("Pics/boll");
    blockgrön_texture = Content.Load<Texture2D>("Pics/block-grön");
    blockröd_texture = Content.Load<Texture2D>("Pics/block-röd");
    gameover_texture = Content.Load<Texture2D>("Pics/GameOver");
    linje_rect = new Rectangle((Window.ClientBounds.Width - linje_texture.Width) / 2, 580, linje_texture.Width, linje_texture.Height);
    linjeliten_rect = new Rectangle((Window.ClientBounds.Width - linjeliten_texture.Width) / 2, 580, linjeliten_texture.Width, linjeliten_texture.Height);
    boll_rect = new Rectangle((Window.ClientBounds.Width - boll_texture.Width) / 2, 556, boll_texture.Width, boll_texture.Height);
    gameover_rect = new Rectangle((Window.ClientBounds.Width / 2) - (gameover_texture.Width / 2), (Window.ClientBounds.Height / 2) - gameover_texture.Height / 2, gameover_texture.Width, gameover_texture.Height);

    block.Add(blockgrön_rect);
    block2.Add(blockröd_rect);
    for (int i = 1; i < 2; i++)
    {
        for (int g = 1; g < 13; g++)
        {
            block2.Add(new Rectangle((g * 63) - 60, (i * 20), blockröd_texture.Width, blockröd_texture.Height));
        }
    }
    for (int i = 1; i < 4; i++)
    {
        for (int g = 1; g < 13; g++)
        {
            block.Add(new Rectangle((g * 63) - 60, (i * 20) + 20, blockgrön_texture.Width, blockgrön_texture.Height));
        }
    }
}

protected override void UnloadContent()
{
    // TODO: Unload any non ContentManager content here
}

protected override void Update(GameTime gameTime)
{
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
    {
        if (poang == highscore)
        {
            sw = new StreamWriter("highscore.txt");
            sw.WriteLine(poang);
            sw.Close();
        }
        Exit();
    }
    if (Start == true)
    {
        boll_rect.X += (int)boll_speed.X;
        boll_rect.Y += (int)boll_speed.Y;
    }

    if (Start == false)
    {
        boll_rect.X = linje_rect.X + ((linje_texture.Width / 2) - (boll_texture.Width / 2)); //how the ball condition is to the long line
        boll_rect.X = linjeliten_rect.X + ((linjeliten_texture.Width / 2) - (boll_texture.Width / 2)); //the same but ball condition to small line
    }
    if (boll_rect.X > Window.ClientBounds.Width - boll_texture.Width || boll_rect.X < 0)
        boll_speed.X *= -1;

    if (boll_rect.Y > Window.ClientBounds.Height - boll_texture.Height || boll_rect.Y < 0)
        boll_speed.Y *= -1;

    if (boll_rect.Y > Window.ClientBounds.Height - boll_texture.Height)
    {
        liv -= 1;
        Start = false;
        boll_rect.X = (Window.ClientBounds.Width - boll_texture.Width) / 2;
        boll_rect.Y = 556;
        linje_rect.X = (Window.ClientBounds.Width - linje_texture.Width) / 2;
        linje_rect.Y = 580;
        linjeliten_rect.X = (Window.ClientBounds.Width - linjeliten_texture.Width) / 2;
        linjeliten_rect.Y = 580;
    }

    KeyboardState ks = Keyboard.GetState();
    if (ks.IsKeyDown(Keys.Left))
    {
        linje_rect.X -= (int)linje_speed.X;
        linjeliten_rect.X -= (int)linjeliten_speed.X;
        holdingleft = true;
    }
    else if (ks.IsKeyDown(Keys.Right))
    {
        linje_rect.X += (int)linje_speed.X;
        linjeliten_rect.X += (int)linjeliten_speed.X;
        holdingright = true;
    }
    else if (ks.IsKeyDown(Keys.Space))
    {
        Start = true;
    }

    if (ks.Equals(new KeyboardState()))
    {
        resetballspeed = true;
    }

    if (linje_rect.X > Window.ClientBounds.Width - linje_texture.Width)
        linje_rect.X = (Window.ClientBounds.Width - linje_texture.Width);

    if (linjeliten_rect.X > Window.ClientBounds.Width - linjeliten_texture.Width)
        linjeliten_rect.X = (Window.ClientBounds.Width - linjeliten_texture.Width);

    if (linje_rect.X < 0)
        linje_rect.X = 0;

    if (linjeliten_rect.X < 0)
        linjeliten_rect.X = 0;

    if (linje_rect.Intersects(boll_rect))
    {
        boll_speed.Y *= -1;
        boll_rect.Y += (int)boll_speed.Y;
        if (holdingleft == true)
        {
            boll_speed.X -= 2;
        }
        else if (holdingright == true)
        {
            boll_speed.X += 2;
        }
        else if (resetballspeed == true)
        {
            boll_speed.X = 1;
        }
    }

    if (linjeliten_rect.Intersects(boll_rect))
    {
        boll_speed.Y *= -1;
        boll_rect.Y += (int)boll_speed.Y;
        if (holdingleft == true)
        {
            boll_speed.X -= 1;
        }
        else if (holdingright == true)
        {
            boll_speed.X += 1;
        }
        else if (resetballspeed == true)
        {
            boll_speed.X = 1;
        }
    }

    for (int j = 1; j < block.Count; j++)
    {
        if (boll_rect.Intersects(block[j]))
        {
            boll_speed.Y *= -1;
            poang += 1;
            block.RemoveAt(j);
            if (poang > highscore)
            {
                highscore++;
            }
        }
    }
    for (int k = 1; k < block2.Count; k++)
    {
        if (boll_rect.Intersects(block2[k]))
        {
            boll_speed.Y *= -1;
            poang += 5;
            block2.RemoveAt(k);
            if (poang > highscore)
            {
                highscore += 5;
            }
        }
    }

    holdingleft = false;
    holdingright = false;

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);

    spriteBatch.Begin();
    if (liv > 0)
    {
        if (poang < 10)
        {
            spriteBatch.Draw(linje_texture, linje_rect, Color.White);
        }
        else if (poang > 9)
        {
            spriteBatch.Draw(linjeliten_texture, linjeliten_rect, Color.White);
        }
        spriteBatch.Draw(boll_texture, boll_rect, Color.White);
        spriteBatch.DrawString(spritefont, "Lives left: " + liv, Vector2.Zero, Color.White);
        spriteBatch.DrawString(spritefont, "Points: " + poang, new Vector2(350, 0), Color.White);
        spriteBatch.DrawString(spritefont, "Highscore: " + highscore, new Vector2(660, 0), Color.White);
        foreach (Rectangle g in block)
        {
            spriteBatch.Draw(blockgrön_texture, g, Color.White);
        }
        foreach (Rectangle t in block2)
        {
            spriteBatch.Draw(blockröd_texture, t, Color.White);
        }
    }
    else if (liv == 0)
    {
        spriteBatch.Draw(gameover_texture, gameover_rect, Color.White);
        if (poang == highscore)
        {
            sw = new StreamWriter("highscore.txt");
            sw.WriteLine(poang);
            sw.Close();
        }
    }

    spriteBatch.End();

    base.Draw(gameTime);
}
}
</code>```

Having trouble with these parts:

```<code>        for (int j = 1; j < block.Count; j++) //loopar igenom alla block
        {
            if (boll_rect.Intersects(block[j])) //om bollen träffar rutorna
            {
                boll_speed.Y *= -1;
                poang += 1;
                block.RemoveAt(j); //tar bort gröna blocket man träffar
                if (poang > 9)
                {
                    linje_rect.Width = 60;
                }
                if (poang > highscore)
                {
                    highscore++;
                }
            }
        }
</code>```

```<code>        for (int k = 1; k < block2.Count; k++)
        {
            if (boll_rect.Intersects(block2[k]))
            {
                boll_speed.Y *= -1;
                poang += 5;
                block2.RemoveAt(k);
                if (poang > highscore)
                {
                    highscore += 5;
                }
                block2.RemoveAt(k);
            }
        }
</code>```

答:
Replace highscore++; with highscore = poang;

and highscore += 5; with highscore = poang;

to avoid mismatches between highscore and current score.

Body:
When I get my points(poang) to highscore when I hit the blocks with 5 points. They will not update the same, sometimes points(poang) will be 18 and highscore will be 20.

(Sorry about my bad english)

poang = points

linje = line

liv = lives

boll = ball

poang = points

blockröd = blockred

blockgrön = blockgreen

public class Game1 : Game
{
 GraphicsDeviceManager graphics;
 SpriteBatch spriteBatch;
 SpriteFont spritefont;
 Texture2D linje_texture;
 Texture2D linjeliten_texture;
 Texture2D boll_texture;
 Texture2D blockröd_texture;
 Texture2D blockgrön_texture;
 Texture2D gameover_texture;
 Rectangle linje_rect;
 Rectangle linjeliten_rect;
 Rectangle boll_rect;
 Rectangle blockröd_rect;
 Rectangle blockgrön_rect;
 Rectangle gameover_rect;

 Vector2 linje_speed;
 Vector2 linjeliten_speed;
 Vector2 boll_speed;

 Random random;

 StreamReader sr;
 StreamWriter sw;

 int liv = 3;
 int poang = 0;
 int highscore;

 List<Rectangle> block = new List<Rectangle>();
 List<Rectangle> block2 = new List<Rectangle>();

 bool Start = false;
 bool holdingleft = false;
 bool holdingright = false;
 bool resetballspeed = false;

 public Game1()
 {
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";

    graphics.PreferredBackBufferWidth = 760;
    graphics.PreferredBackBufferHeight = 620;
}

protected override void Initialize()
{
    random = new Random();
    linje_speed.X = 6f;
    linjeliten_speed.X = 6f;
    boll_speed.X = random.Next(-1, 1);
    boll_speed.Y = 7f;

    sr = new StreamReader("highscore.txt");
    highscore = int.Parse(sr.ReadLine());
    sr.Close();

    base.Initialize();
}

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    spritefont = Content.Load<SpriteFont>("Fonts/Myfont");
    linje_texture = Content.Load<Texture2D>("Pics/linje-lång");
    linjeliten_texture = Content.Load<Texture2D>("Pics/linje");
    boll_texture = Content.Load<Texture2D>("Pics/boll");
    blockgrön_texture = Content.Load<Texture2D>("Pics/block-grön");
    blockröd_texture = Content.Load<Texture2D>("Pics/block-röd");
    gameover_texture = Content.Load<Texture2D>("Pics/GameOver");
    linje_rect = new Rectangle((Window.ClientBounds.Width - linje_texture.Width) / 2, 580, linje_texture.Width, linje_texture.Height);
    linjeliten_rect = new Rectangle((Window.ClientBounds.Width - linjeliten_texture.Width) / 2, 580, linjeliten_texture.Width, linjeliten_texture.Height);
    boll_rect = new Rectangle((Window.ClientBounds.Width - boll_texture.Width) / 2, 556, boll_texture.Width, boll_texture.Height);
    gameover_rect = new Rectangle((Window.ClientBounds.Width / 2) - (gameover_texture.Width / 2), (Window.ClientBounds.Height / 2) - gameover_texture.Height / 2, gameover_texture.Width, gameover_texture.Height);

    block.Add(blockgrön_rect);
    block2.Add(blockröd_rect);
    for (int i = 1; i < 2; i++)
    {
        for (int g = 1; g < 13; g++)
        {
            block2.Add(new Rectangle((g * 63) - 60, (i * 20), blockröd_texture.Width, blockröd_texture.Height));
        }
    }
    for (int i = 1; i < 4; i++)
    {
        for (int g = 1; g < 13; g++)
        {
            block.Add(new Rectangle((g * 63) - 60, (i * 20) + 20, blockgrön_texture.Width, blockgrön_texture.Height));
        }
    }
}

protected override void UnloadContent()
{
    // TODO: Unload any non ContentManager content here
}

protected override void Update(GameTime gameTime)
{
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
    {
        if (poang == highscore)
        {
            sw = new StreamWriter("highscore.txt");
            sw.WriteLine(poang);
            sw.Close();
        }
        Exit();
    }
    if (Start == true)
    {
        boll_rect.X += (int)boll_speed.X;
        boll_rect.Y += (int)boll_speed.Y;
    }

    if (Start == false)
    {
        boll_rect.X = linje_rect.X + ((linje_texture.Width / 2) - (boll_texture.Width / 2)); //how the ball condition is to the long line
        boll_rect.X = linjeliten_rect.X + ((linjeliten_texture.Width / 2) - (boll_texture.Width / 2)); //the same but ball condition to small line
    }
    if (boll_rect.X > Window.ClientBounds.Width - boll_texture.Width || boll_rect.X < 0)
        boll_speed.X *= -1;

    if (boll_rect.Y > Window.ClientBounds.Height - boll_texture.Height || boll_rect.Y < 0)
        boll_speed.Y *= -1;

    if (boll_rect.Y > Window.ClientBounds.Height - boll_texture.Height)
    {
        liv -= 1;
        Start = false;
        boll_rect.X = (Window.ClientBounds.Width - boll_texture.Width) / 2;
        boll_rect.Y = 556;
        linje_rect.X = (Window.ClientBounds.Width - linje_texture.Width) / 2;
        linje_rect.Y = 580;
        linjeliten_rect.X = (Window.ClientBounds.Width - linjeliten_texture.Width) / 2;
        linjeliten_rect.Y = 580;
    }

    KeyboardState ks = Keyboard.GetState();
    if (ks.IsKeyDown(Keys.Left))
    {
        linje_rect.X -= (int)linje_speed.X;
        linjeliten_rect.X -= (int)linjeliten_speed.X;
        holdingleft = true;
    }
    else if (ks.IsKeyDown(Keys.Right))
    {
        linje_rect.X += (int)linje_speed.X;
        linjeliten_rect.X += (int)linjeliten_speed.X;
        holdingright = true;
    }
    else if (ks.IsKeyDown(Keys.Space))
    {
        Start = true;
    }

    if (ks.Equals(new KeyboardState()))
    {
        resetballspeed = true;
    }

    if (linje_rect.X > Window.ClientBounds.Width - linje_texture.Width)
        linje_rect.X = (Window.ClientBounds.Width - linje_texture.Width);

    if (linjeliten_rect.X > Window.ClientBounds.Width - linjeliten_texture.Width)
        linjeliten_rect.X = (Window.ClientBounds.Width - linjeliten_texture.Width);

    if (linje_rect.X < 0)
        linje_rect.X = 0;

    if (linjeliten_rect.X < 0)
        linjeliten_rect.X = 0;

    if (linje_rect.Intersects(boll_rect))
    {
        boll_speed.Y *= -1;
        boll_rect.Y += (int)boll_speed.Y;
        if (holdingleft == true)
        {
            boll_speed.X -= 2;
        }
        else if (holdingright == true)
        {
            boll_speed.X += 2;
        }
        else if (resetballspeed == true)
        {
            boll_speed.X = 1;
        }
    }

    if (linjeliten_rect.Intersects(boll_rect))
    {
        boll_speed.Y *= -1;
        boll_rect.Y += (int)boll_speed.Y;
        if (holdingleft == true)
        {
            boll_speed.X -= 1;
        }
        else if (holdingright == true)
        {
            boll_speed.X += 1;
        }
        else if (resetballspeed == true)
        {
            boll_speed.X = 1;
        }
    }

    for (int j = 1; j < block.Count; j++)
    {
        if (boll_rect.Intersects(block[j]))
        {
            boll_speed.Y *= -1;
            poang += 1;
            block.RemoveAt(j);
            if (poang > highscore)
            {
                highscore++;
            }
        }
    }
    for (int k = 1; k < block2.Count; k++)
    {
        if (boll_rect.Intersects(block2[k]))
        {
            boll_speed.Y *= -1;
            poang += 5;
            block2.RemoveAt(k);
            if (poang > highscore)
            {
                highscore += 5;
            }
        }
    }

    holdingleft = false;
    holdingright = false;

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);

    spriteBatch.Begin();
    if (liv > 0)
    {
        if (poang < 10)
        {
            spriteBatch.Draw(linje_texture, linje_rect, Color.White);
        }
        else if (poang > 9)
        {
            spriteBatch.Draw(linjeliten_texture, linjeliten_rect, Color.White);
        }
        spriteBatch.Draw(boll_texture, boll_rect, Color.White);
        spriteBatch.DrawString(spritefont, "Lives left: " + liv, Vector2.Zero, Color.White);
        spriteBatch.DrawString(spritefont, "Points: " + poang, new Vector2(350, 0), Color.White);
        spriteBatch.DrawString(spritefont, "Highscore: " + highscore, new Vector2(660, 0), Color.White);
        foreach (Rectangle g in block)
        {
            spriteBatch.Draw(blockgrön_texture, g, Color.White);
        }
        foreach (Rectangle t in block2)
        {
            spriteBatch.Draw(blockröd_texture, t, Color.White);
        }
    }
    else if (liv == 0)
    {
        spriteBatch.Draw(gameover_texture, gameover_rect, Color.White);
        if (poang == highscore)
        {
            sw = new StreamWriter("highscore.txt");
            sw.WriteLine(poang);
            sw.Close();
        }
    }

    spriteBatch.End();

    base.Draw(gameTime);
}
}

Having trouble with these parts:

        for (int j = 1; j < block.Count; j++) //loopar igenom alla block
        {
            if (boll_rect.Intersects(block[j])) //om bollen träffar rutorna
            {
                boll_speed.Y *= -1;
                poang += 1;
                block.RemoveAt(j); //tar bort gröna blocket man träffar
                if (poang > 9)
                {
                    linje_rect.Width = 60;
                }
                if (poang > highscore)
                {
                    highscore++;
                }
            }
        }

        for (int k = 1; k < block2.Count; k++)
        {
            if (boll_rect.Intersects(block2[k]))
            {
                boll_speed.Y *= -1;
                poang += 5;
                block2.RemoveAt(k);
                if (poang > highscore)
                {
                    highscore += 5;
                }
                block2.RemoveAt(k);
            }
        }


问:
EntityManager refresh
I have web application using JPA. This entity manager keeps bunch of entites and suddenly I update the database from other side. I use MySQL and I use PhpMyAdmin and change some row.

How to tell entity manager to re-synchronize, e.g. to forgot all the entites in cache?

I know there is refresh(Object) method, but is there any possibility how to do refreshAll() or something what results in this?

It is sure this is expensive operation but if it has to be done.

答:
If you are using EclipseLink instead of Hibernate the hint is:</p>

```<code>em.createNamedQuery("SomeEntity.SomeNamedQuery")
.setHint(QueryHints.REFRESH, true)
.getResultList();
</code>```

Title: EntityManager refresh

Body:
If you are using EclipseLink instead of Hibernate the hint is:

em.createNamedQuery("SomeEntity.SomeNamedQuery")
.setHint(QueryHints.REFRESH, true)
.getResultList();


问:
PHP Warning at startup while trying to load php_oci8.dll
I'm using XAMPP and trying to configure Oracle connection for sql.

I uncommented the line extension=php_oci8.dll and at first it ended up with an error (that oci.dll is missing), but later I downloaded instantclient from Oracle web pages. I tried with versions 10.2, 11.2, and 12.1 but neither worked. Obviously I've added the path to those libraries to my PATH env variable.

The warning I'm getting at the startup of Apache is: PHP Warning:  PHP Startup:  in Unknown on line 0

The error when I'm trying to connect is: PHP Fatal error:  Call to undefined function oci_connect() in ...

I've tried with php_oci8.dll and php_oci8_11g.dll. Those files are in my php/ext directory (they were included in xampp), my instantclient is added to PATH and the warning doesn't show up if I disable those modules. I've tried restarting services and computer.

Can you help me find a solution how to configure it correctly? I'm using Windows 8.1 with administrative privileges.

BTW. My phpinfo() says that OCI8 is activated (but functions like oci_connect still don't work).

EDIT: When I tried running PHP manually I finally got the error to display what was wrong: Unable to load dynamic library 'C:\Program Files (x86)\PHP\ext\php_oci8_11g.dll' - %1 is not a valid Win32 application. in Unknown on line 0 Can you help me find out where can I download a correct version?

答:
There's an alternate way to solve this: Install the full Oracle Client, not the basic zip, you can get it at oracle site (about 1Gb):

http://www.oracle.com/technetwork/database/enterprise-edition/downloads/oracle12c-windows-3633015.html

Im using Windows 10, Apache 2.4, PHP 7.1 (all x64) and it works. Also tryed PHP 5.6 and it works too. Still use the php_oci8_11g.dll from the basic client zip to match your php and system version.

You can search the site to find older client versions (11g, 32bits, etc) but Im working with de 12c client and accessing an Oracle 11g enterprise server.

I found a lot of occurrencies of this same error all around, but none gave me this solution. Hope taht helps.


问:
How I can set FileName after click Upload a File from local PC?
I have some short code:

```<code>private void buttonSave_Click(object sender, EventArgs e)
{

    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "NHC|*.nhc";
    openFileDialog1.Title = @"test.nhc";

    OpenFileDialog openfiledialog = new OpenFileDialog();
    openfiledialog.ShowHelp = true;
    openfiledialog.FileName = "test.nhc";
    openfiledialog.ShowDialog();
}
</code>```

I want to set the FileName in OpenFileDialog.

For example: I have a web app and I click Upload to upload a file from the local PC. The OpenFileDialog PopUp does open. Now I want to set the FileName to test.nhc in the field FileName (Windows window) and click "Open".

But it doesn't work.

答:
Do you want to set the name before or after clicking?
You should define this name in PageLoad, for example. Not at Click.</p>

```<code>OpenFileDialog openfiledialog = new OpenFileDialog();

protected void Page_Load(object sender, EventArgs e)
{
         if (!IsPostBack)
         {
            openfiledialog.FileName = "test.nhc";
         }
}

private void buttonSave_Click(object sender, EventArgs e)
{
          openfiledialog.ShowDialog();
}
</code>```

Body:
I have some short code:

private void buttonSave_Click(object sender, EventArgs e)
{

    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "NHC|*.nhc";
    openFileDialog1.Title = @"test.nhc";

    OpenFileDialog openfiledialog = new OpenFileDialog();
    openfiledialog.ShowHelp = true;
    openfiledialog.FileName = "test.nhc";
    openfiledialog.ShowDialog();
}

I want to set the FileName in OpenFileDialog.

For example: I have a web app and I click Upload to upload a file from the local PC. The OpenFileDialog PopUp does open. Now I want to set the FileName to test.nhc in the field FileName (Windows window) and click "Open".

But it doesn't work.

Body:
Do you want to set the name before or after clicking?
You should define this name in PageLoad, for example. Not at Click.

OpenFileDialog openfiledialog = new OpenFileDialog();

protected void Page_Load(object sender, EventArgs e)
{
         if (!IsPostBack)
         {
            openfiledialog.FileName = "test.nhc";
         }
}

private void buttonSave_Click(object sender, EventArgs e)
{
          openfiledialog.ShowDialog();
}


问:
how to add new entries in struct which is member of class using inheritance
```<code>class A
{
    public:
        typedef struct st
        {
            int x;
            int y;
        }st;
};
</code>```

I have class A which has a structure as public member variable. I want to add some new entries in above struct st. I used inheritance. is it possible to add new entries in that structure without changing it's name (st).

```<code>class B:public A
{
};
</code>```

Please help me out.

答:
A type always remains the same throughout the entire program. A::st has members x and y. No more, no less - regardless of any subclasses that A might have. And no type can have the same name as another type (within the same namespace).

However, just as you can extend the class A by creating a subclass B, you can also extend the class A::st by creating a subclass. If you wish, you can declare the subclass of A::st as a member class of B like so:

```<code>class B:public A
{
    struct st : A::st
    {
        int z;
    };
};
</code>```

Now, B::st is a subclass of A::st, and hides B::A::st within the namespace of B.

Body:
class A
{
    public:
        typedef struct st
        {
            int x;
            int y;
        }st;
};

I have class A which has a structure as public member variable. I want to add some new entries in above struct st. I used inheritance. is it possible to add new entries in that structure without changing it's name (st).

class B:public A
{
};

Please help me out.

Body:
A type always remains the same throughout the entire program. A::st has members x and y. No more, no less - regardless of any subclasses that A might have. And no type can have the same name as another type (within the same namespace).

However, just as you can extend the class A by creating a subclass B, you can also extend the class A::st by creating a subclass. If you wish, you can declare the subclass of A::st as a member class of B like so:

class B:public A
{
    struct st : A::st
    {
        int z;
    };
};

Now, B::st is a subclass of A::st, and hides B::A::st within the namespace of B.


问:
creating an array of structures from a file in C
i am trying to create an array of structures in C. it is as simple as reading in the information from a file into a structure, but I keep getting two warning messages about reading in my two character (number/colour) as well as that the program seems to just read zero for every value.</p>

```<code>#include<stdio.h>
#include<string.h>

typedef struct car
{
    int year;
    char number[9];
    char colour[10];
    float engine;
} car_type[6];

int main()
{
    car_type car;
    int i;
    FILE*fptr;

    fptr = fopen("indata.txt", "r");

    while (!feof(fptr))
    {
        fscanf(fptr, "%d %c %c %f", &car[i].year, &car[i].number,
                &car[i].colour, &car[i].engine);
        i++;
    }

    fclose(fptr);

    return 0;
}
</code>```

答:
I did not test this "code". The correct strategy you should apply is:

1) find the filesize

2) allocate the buffer

3) read whole file in it

4) know how many strings ('\n') it contains (in while loop)

5) in for cycle handle the buffer (i = 0; i < num_lines; i++) ...

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUF 64
typedef struct _CarType
{
    int year;
    int number;
    int colour;
    double engine;
} CarType;

int main(int argc, char argv[])
{
    CarType car[6];

    FILE* fp = fopen("indata.txt","r");
    if(fp != NULL)
    {
        int i = 0;
        while(!feof(fp))
        {
            char year[BUF], colour[BUF], engine1[BUF], engine1[BUF], number[BUF];
            memset(year,     '\0', BUF);
            memset(colour,   '\0', BUF);
            memset(engine1,  '\0', BUF);
            memset(engine2,  '\0', BUF);
            memset(number,   '\0', BUF);

            fscanf(fp, "%s %s %s %s.%s", year, number, colour, engine1, engine2);
            car[i].year      =    atoi(year);
            car[i].number    =    atoi(number);
            car[i].colour    =    atoi(colour);
            car[i].engine    =    atoi(engine1);
            car[i].engine    +=   (atoi(engine2)) / (10 * strlen(engine2));

            i++;
        }
        fclose(fp);
    }
    return 0;
}
</code>```

Body:
i am trying to create an array of structures in C. it is as simple as reading in the information from a file into a structure, but I keep getting two warning messages about reading in my two character (number/colour) as well as that the program seems to just read zero for every value.

#include<stdio.h>
#include<string.h>

typedef struct car
{
    int year;
    char number[9];
    char colour[10];
    float engine;
} car_type[6];

int main()
{
    car_type car;
    int i;
    FILE*fptr;

    fptr = fopen("indata.txt", "r");

    while (!feof(fptr))
    {
        fscanf(fptr, "%d %c %c %f", &car[i].year, &car[i].number,
                &car[i].colour, &car[i].engine);
        i++;
    }

    fclose(fptr);

    return 0;
}

Body:
I did not test this "code". The correct strategy you should apply is:

1) find the filesize

2) allocate the buffer

3) read whole file in it

4) know how many strings ('\n') it contains (in while loop)

5) in for cycle handle the buffer (i = 0; i < num_lines; i++) ...

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUF 64
typedef struct _CarType
{
    int year;
    int number;
    int colour;
    double engine;
} CarType;

int main(int argc, char argv[])
{
    CarType car[6];

    FILE* fp = fopen("indata.txt","r");
    if(fp != NULL)
    {
        int i = 0;
        while(!feof(fp))
        {
            char year[BUF], colour[BUF], engine1[BUF], engine1[BUF], number[BUF];
            memset(year,     '\0', BUF);
            memset(colour,   '\0', BUF);
            memset(engine1,  '\0', BUF);
            memset(engine2,  '\0', BUF);
            memset(number,   '\0', BUF);

            fscanf(fp, "%s %s %s %s.%s", year, number, colour, engine1, engine2);
            car[i].year      =    atoi(year);
            car[i].number    =    atoi(number);
            car[i].colour    =    atoi(colour);
            car[i].engine    =    atoi(engine1);
            car[i].engine    +=   (atoi(engine2)) / (10 * strlen(engine2));

            i++;
        }
        fclose(fp);
    }
    return 0;
}


问:
how to create a list of lists using list comprehension
I want to create a list of lists using list comprehension.
ex
[range(3),range(3),range(3)]
i.e all possible coordinates of a 3d system from 0 to 3
How to do this using only list comprehension and nothing else

I tried doing

```<code>coordinates=[x for x in range(3)[y for y in range(3)[z for z in range(3)]]]
</code>```

答:
your syntax is slightly off</p>

```<code>coordinates=[[x,y,z] for x in range(4) for y in range(4) for z in range(4)]
</code>```

Body:
I want to create a list of lists using list comprehension.
ex
[range(3),range(3),range(3)]
i.e all possible coordinates of a 3d system from 0 to 3
How to do this using only list comprehension and nothing else

I tried doing

coordinates=[x for x in range(3)[y for y in range(3)[z for z in range(3)]]]

Body:
your syntax is slightly off

coordinates=[[x,y,z] for x in range(4) for y in range(4) for z in range(4)]


问:
iOS UIImagePickerController result image orientation after upload
I am testing my iPhone application on an iOS 3.1.3 iPhone.  I am selecting/capturing an image using a UIImagePickerController:

```<code>UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[imagePicker setDelegate:self];
[self.navigationController presentModalViewController:imagePicker animated:YES];
[imagePicker release];

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    imageView.image = self.image;
    [self.navigationController dismissModalViewControllerAnimated:YES];
    submitButton.enabled = YES;
}
</code>```

I then at some point send it to my web server using the ASI classes:

```<code>ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://example.com/myscript.php"]];
[request setDelegate:self];
[request setStringEncoding:NSUTF8StringEncoding];
[request setShouldContinueWhenAppEntersBackground:YES];
//other post keys/values
[request setFile:UIImageJPEGRepresentation(self.image, 100.0f) withFileName:[NSString stringWithFormat:@"%d.jpg", [[NSDate date] timeIntervalSinceNow]] andContentType:@"image/jpg" forKey:@"imageFile"];
[request startAsynchronous];
</code>```

the problem:
when i take a picture with the iphone while holding it landscape, the image gets uploaded to the server and it viewed like you would expect.  when taking a picture holding the phone in portrait, the image is uploaded and viewed as it had been rotated 90 degrees.

my application is set to only work in portrait modes(upsidedown and regular).

How can i make the image always show the correct orientation after uploading?

the image appears to be correct as displayed in an UIImageView(directly after taking the picture), but viewing on the server says otherwise.

答:
Update for Swift 3.1 based on Sourabh Sharma's  answer, with code clean up.

```<code>extension UIImage {
    func fixedOrientation() -> UIImage {
        if imageOrientation == .up { return self }

        var transform:CGAffineTransform = .identity
        switch imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: size.width, y: size.height).rotated(by: .pi)
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: size.width, y: 0).rotated(by: .pi/2)
        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: size.height).rotated(by: -.pi/2)
        default: break
        }

        switch imageOrientation {
        case .upMirrored, .downMirrored:
            transform = transform.translatedBy(x: size.width, y: 0).scaledBy(x: -1, y: 1)
        case .leftMirrored, .rightMirrored:
            transform = transform.translatedBy(x: size.height, y: 0).scaledBy(x: -1, y: 1)
        default: break
        }

        let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height),
                                       bitsPerComponent: cgImage!.bitsPerComponent, bytesPerRow: 0,
                                       space: cgImage!.colorSpace!, bitmapInfo: cgImage!.bitmapInfo.rawValue)!
        ctx.concatenate(transform)

        switch imageOrientation {
        case .left, .leftMirrored, .right, .rightMirrored:
            ctx.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height,height: size.width))
        default:
            ctx.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width,height: size.height))
        }
        return UIImage(cgImage: ctx.makeImage()!)
    }
}
</code>```

Picker delegate method example:

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    guard let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
    let fixedImage = originalImage.fixedOrientation()
    // do your work
}
</code>```

Body:
I am testing my iPhone application on an iOS 3.1.3 iPhone.  I am selecting/capturing an image using a UIImagePickerController:

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[imagePicker setDelegate:self];
[self.navigationController presentModalViewController:imagePicker animated:YES];
[imagePicker release];

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    imageView.image = self.image;
    [self.navigationController dismissModalViewControllerAnimated:YES];
    submitButton.enabled = YES;
}

I then at some point send it to my web server using the ASI classes:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://example.com/myscript.php"]];
[request setDelegate:self];
[request setStringEncoding:NSUTF8StringEncoding];
[request setShouldContinueWhenAppEntersBackground:YES];
//other post keys/values
[request setFile:UIImageJPEGRepresentation(self.image, 100.0f) withFileName:[NSString stringWithFormat:@"%d.jpg", [[NSDate date] timeIntervalSinceNow]] andContentType:@"image/jpg" forKey:@"imageFile"];
[request startAsynchronous];

the problem:
when i take a picture with the iphone while holding it landscape, the image gets uploaded to the server and it viewed like you would expect.  when taking a picture holding the phone in portrait, the image is uploaded and viewed as it had been rotated 90 degrees.

my application is set to only work in portrait modes(upsidedown and regular).

How can i make the image always show the correct orientation after uploading?

the image appears to be correct as displayed in an UIImageView(directly after taking the picture), but viewing on the server says otherwise.

Body:
Update for Swift 3.1 based on Sourabh Sharma's  answer, with code clean up.

extension UIImage {
    func fixedOrientation() -> UIImage {
        if imageOrientation == .up { return self }

        var transform:CGAffineTransform = .identity
        switch imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: size.width, y: size.height).rotated(by: .pi)
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: size.width, y: 0).rotated(by: .pi/2)
        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: size.height).rotated(by: -.pi/2)
        default: break
        }

        switch imageOrientation {
        case .upMirrored, .downMirrored:
            transform = transform.translatedBy(x: size.width, y: 0).scaledBy(x: -1, y: 1)
        case .leftMirrored, .rightMirrored:
            transform = transform.translatedBy(x: size.height, y: 0).scaledBy(x: -1, y: 1)
        default: break
        }

        let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height),
                                       bitsPerComponent: cgImage!.bitsPerComponent, bytesPerRow: 0,
                                       space: cgImage!.colorSpace!, bitmapInfo: cgImage!.bitmapInfo.rawValue)!
        ctx.concatenate(transform)

        switch imageOrientation {
        case .left, .leftMirrored, .right, .rightMirrored:
            ctx.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height,height: size.width))
        default:
            ctx.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width,height: size.height))
        }
        return UIImage(cgImage: ctx.makeImage()!)
    }
}

Picker delegate method example:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    guard let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
    let fixedImage = originalImage.fixedOrientation()
    // do your work
}


问:
Block user account automatically if user doesn't verify his/her email within 24 hours of registration
I am working on a project using symfony and I need to track, wether user has verified his/her email withing the 24 hours of creating a new account.

How can I update the values in database automatically, so I can track this?

答:
Create a php script which check the unverified members, and if the date is greater than 24 hours, remove him.

Then just call your php script every hours or every days with a crontab.

See "What is a crontab?"
https://kb.iu.edu/d/afiz


问:
jquery - .split is not a function
I am using the same code in some other place, which is working fine. but now i am using it, but is throwing me error i.e. .split is not a function

Below is code i am using:

```<code>var classList = $(this).attr('class').split(/\s+/);
</code>```

I have checked in Console, class name is coming like Cls_abc-XYZ and i want to get "abc-XYZ" from it.
Any suggestion

答:
fixed it as below:</p>

```<code>$('body').attr('class').toString().split(/\s+/);
</code>```

Title: jquery - .split is not a function

Body:
I am using the same code in some other place, which is working fine. but now i am using it, but is throwing me error i.e. .split is not a function

Below is code i am using:

var classList = $(this).attr('class').split(/\s+/);

I have checked in Console, class name is coming like Cls_abc-XYZ and i want to get "abc-XYZ" from it.
Any suggestion

Body:
fixed it as below:

$('body').attr('class').toString().split(/\s+/);


问:
Child div should be as high as parent div
I need a child div to be as high as its parent, but I do not know the parent's height. It can change.
Setting "height: 100%" does not work, as the div will take the height of the entire page.

This is the layout of the divs:

```<code><div id="deelnemersballoon">
    <div class="balloonarrow"></div>

    <div class="balloonborder">

        <div class="ballooncontent">
            <div id="aantaldeelnemers">1</div>
            <div id="deelnemertekst">deelnemer werd toegevoegd.</div>
            <div class="clear">
                <button>Add something</button>
            </div>
        </div>

    </div>

</div>
</code>```

.balloonarrow should be as high as #deelnemersballoon

答:
A child div will not take up 100% of its parent if it has something in the markup before it:

Html:

```<code><div id='parent'>Parent (Mark up before child)<div id='child'>Child</div></div>
</code>```

css:

```<code>   #parent {background:blue; height:500px; color:white}
    #child {background:red; height:100%}
</code>```

You can find a working example here. (Removing the text from the #parent div will make the child fill it 100%)

http://jsfiddle.net/wcprA/2/

The same thing applies if you have markup after the 100% child aswell, as seen here

http://jsfiddle.net/wcprA/5/

Body:
I need a child div to be as high as its parent, but I do not know the parent's height. It can change.
Setting "height: 100%" does not work, as the div will take the height of the entire page.

This is the layout of the divs:

1

deelnemer werd toegevoegd.

                <button>Add something</button>

.balloonarrow should be as high as #deelnemersballoon

Body:
A child div will not take up 100% of its parent if it has something in the markup before it:

Html:

<div id='parent'>Parent (Mark up before child)<div id='child'>Child</div></div>

css:

   #parent {background:blue; height:500px; color:white}
    #child {background:red; height:100%}

You can find a working example here. (Removing the text from the #parent div will make the child fill it 100%)

http://jsfiddle.net/wcprA/2/

The same thing applies if you have markup after the 100% child aswell, as seen here

http://jsfiddle.net/wcprA/5/


答:
You are not handling the event for open file ok button. First you need to create a Stream object and then an event that will happen in DialogResult.OK situation.

Here is an example from microsoft

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "NHC|*.nhc";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Title = @"test.nhc";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            // Insert code to read the stream here.
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        }
    }```

Title: How I can set FileName after click Upload a File from local PC?