问:
Finding prime numbers and then putting the prime numbers into an output file
So I have an assignment for class in which I have to ask the user for an integer in between 1 and 3000. Then my program should be able to tell if the integer is a prime number or not. Lastly, I would have to put that integer into a file, but only if it is a prime number. But my issue is my syntax, I am not sure if it's right(well actually obviously it's not because I keep getting errors). Is it possible to open a file in a function? and if so does it become a parameter?
I have been going through my textbook and googling as much as possible for some guidance but I'm still feeling lost. Any advice would help.

Edit: My logic as far as the numbers work, however when I add the code to write to a file, I'm now getting errors.

The two errors are

C2440 initializing: cannot convert from constant char to int (line 18)

C2079 myfile: uses undefined class'std::basic_fstream <>char,std::char_traits>'

Here's my code so far!

```<code>    // Project 5.cpp : Defines the entry point for the console application.
    //

#include <fstream>
#include "stdafx.h"
#include <iostream>

using namespace std;

//functions

void prime(int x);

//variables
int x=0;
int i;
char answer;
fstream myfile("castor_primes.txt");

int main()

{

    do
    {
        cout << "Enter an integer between 1 and 3000 \n";
        cin >> x;
        if (x == 1)
        {
            cout << x << " is not a prime number.\n";
        }
       else if (x < 1 || x>3000)
        {
            cout << x << " is an invalid number. \n";
        }
        else
        {

            prime(x);
        }

        cout << "Do you want to enter another number? Y/N \n";
        cin >> answer;
    } while (answer == 'y' || answer == 'Y');

    myfile.close();

    return 0;
}

void prime(int x)
{

    if (x == 2)
    {
        cout << "Yes, " << x << " is Prime\n";
    }
    else
    {
        for (i = 2; i < x; i++)
        {
            if (x%i == 0)
            {
                cout << x << " is not a prime number\n";
                break;
            }
        }
        if (x == i)
        {
            cout << "Yes, " << x << " is Prime\n";
            myfile << x ;

        }
    }
}
</code>```

答:
#include "stdafx.h" includes a pre-compiled header file when using Microsoft Visual Studio. Check to see if that file exists and if it is correct (depending on the errors you see).

There is no reason to pass the outputFile into the prime() function since you are opening and closing it in the function. Although it works just fine if you do.

It is a parameter of the function call (if that is your question) and is a global variable since it is defined outside the main() function.

As some one else suggested the code functions if the aforementioned #include "stdafx.h" is removed, but I am not sure how that affects the compilation in Visual Studio.

Body:
So I have an assignment for class in which I have to ask the user for an integer in between 1 and 3000. Then my program should be able to tell if the integer is a prime number or not. Lastly, I would have to put that integer into a file, but only if it is a prime number. But my issue is my syntax, I am not sure if it's right(well actually obviously it's not because I keep getting errors). Is it possible to open a file in a function? and if so does it become a parameter?
I have been going through my textbook and googling as much as possible for some guidance but I'm still feeling lost. Any advice would help.

Edit: My logic as far as the numbers work, however when I add the code to write to a file, I'm now getting errors.

The two errors are

C2440 initializing: cannot convert from constant char to int (line 18)

C2079 myfile: uses undefined class'std::basic_fstream <>char,std::char_traits>'

Here's my code so far!

    // Project 5.cpp : Defines the entry point for the console application.
    //

#include <fstream>
#include "stdafx.h"
#include <iostream>

using namespace std;

//functions

void prime(int x);

//variables
int x=0;
int i;
char answer;
fstream myfile("castor_primes.txt");

int main()

{

    do
    {
        cout << "Enter an integer between 1 and 3000 \n";
        cin >> x;
        if (x == 1)
        {
            cout << x << " is not a prime number.\n";
        }
       else if (x < 1 || x>3000)
        {
            cout << x << " is an invalid number. \n";
        }
        else
        {

            prime(x);
        }

        cout << "Do you want to enter another number? Y/N \n";
        cin >> answer;
    } while (answer == 'y' || answer == 'Y');

    myfile.close();

    return 0;
}

void prime(int x)
{

    if (x == 2)
    {
        cout << "Yes, " << x << " is Prime\n";
    }
    else
    {
        for (i = 2; i < x; i++)
        {
            if (x%i == 0)
            {
                cout << x << " is not a prime number\n";
                break;
            }
        }
        if (x == i)
        {
            cout << "Yes, " << x << " is Prime\n";
            myfile << x ;

        }
    }
}


来源: stackexchange

问:
Socket recv (blocking) fails with errno EAGAIN - resource temporarily unavailable
I am implementing a UNIX domain socket Inter Process communication code and I hit this error randomly - "errno 11: Resource temporarily unavailable" while trying to read from the socket. I use MSG_PEEK to read the number of bytes from the socket, and allocate bytes for receive buffer, and read the actual data.

The socket is a blocking socket and I do not have any code to have non-blocking (in all, accept/read/write). Any pointers on what could cause this on a blocking socket read? From the man page of MSG_PEEK, it seems like EAGAIN could be returned when socket is marked as non-blocking, using O_NONBLOCK.

The failure happens on the recv call below.

```<code>        char temp_buffer[BUFFER_MAX];
        num_bytes = recv(_connection_fd, &temp_buffer, BUFFER_SIZE_MAX, MSG_PEEK | MSG_TRUNC);
        if (num_bytes < 0) {
            LogError("Error reading from socket. %s", strerror(errno));
            close(_connection_fd);
            return -1;
        }
        .....
        <Allocate memory>
        .....
        // Read actual data
        num_bytes = read(_connection_fd, buffer, num_bytes);
        ...
        <Send response back to client>
        <Close socket descriptor>
</code>```

答: It may also happen to blocking socket and blocking recv, if socket has timeout SO_RCVTIMEO option set (default is 0). BTW, did you consider select() before recv()?</p>

ContentLicense: CC BY-SA 3.0

Body:
I am implementing a UNIX domain socket Inter Process communication code and I hit this error randomly - "errno 11: Resource temporarily unavailable" while trying to read from the socket. I use MSG_PEEK to read the number of bytes from the socket, and allocate bytes for receive buffer, and read the actual data.

The socket is a blocking socket and I do not have any code to have non-blocking (in all, accept/read/write). Any pointers on what could cause this on a blocking socket read? From the man page of MSG_PEEK, it seems like EAGAIN could be returned when socket is marked as non-blocking, using O_NONBLOCK.

The failure happens on the recv call below.

        char temp_buffer[BUFFER_MAX];
        num_bytes = recv(_connection_fd, &temp_buffer, BUFFER_SIZE_MAX, MSG_PEEK | MSG_TRUNC);
        if (num_bytes < 0) {
            LogError("Error reading from socket. %s", strerror(errno));
            close(_connection_fd);
            return -1;
        }
        .....
        <Allocate memory>
        .....
        // Read actual data
        num_bytes = read(_connection_fd, buffer, num_bytes);
        ...
        <Send response back to client>
        <Close socket descriptor>


问:
start Android gps service
is there any way to turn on gps service through code?</p>

答:
There's a good example on HelloAndroid

Check for the GPS

```<code>LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
</code>```

If isGPS is false open the settings

```<code>startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
</code>```

Don't forget to check the GPS is enabled when the user returns, they might not enable it.

ContentLicense: CC BY-SA 2.5

Title: start Android gps service

Body:
There's a good example on HelloAndroid

Check for the GPS

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);

If isGPS is false open the settings

startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);

Don't forget to check the GPS is enabled when the user returns, they might not enable it.


问:
SPARQL: get biggest city with female mayor
I try to get all cities with a female mayor, but my problem is, that the most mayors if they are in marked in data they are mostly not linked to a person, they are only given as string. So how can I get the gender.

My command to get all mayors is:

```<code>SELECT * WHERE {
 ?city a dbo:City .
 ?city dbo:populationTotal ?pop .
 ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader) ?mayor

}
ORDER BY DESC(?pop)
</code>```

I am not sure if I get all mayors, because there are only 500 mayors versus 19584 cities with given population that sounds less.

For the reason I did not get gender on this way I did a second request to get all female people in DBpedia and try to compare both results, but mostly ends in timeout or "no result"

On example command runs in timeout was:

```<code>SELECT ?name ?sayor WHERE {
 ?person a dbo:Person .
 ?person foaf:gender ?gender .
 FILTER regex(?gender, "^female$", "i") .
 ?person rdfs:label ?name .
 {
  SELECT str(?mayor) AS ?sayor WHERE {
   ?city a dbo:City .
   ?city (dbp:mayor | dbp:leader) ?mayor .
   FILTER (str(?mayor) = str(?name))
  }
 }
}
</code>```

Has anyone an idea to get all cities with female mayor? I am also happy with getting some stimulation's.

答:
Part of the problem is that DBPedia, for quite a lot of cities, doesn't record enough information to do this. If we take a look at the result of your original query, it looks like this:

```<code>city    pop     mayor
http://dbpedia.org/resource/Berlin  3610156 "Michael Müller"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#langString>
http://dbpedia.org/resource/Hamburg     1774242 http://dbpedia.org/resource/Olaf_Scholz
http://dbpedia.org/resource/Pekanbaru   1093416 "Prof. Dr. Andre Syahputra, M.Sc"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#langString>
</code>```

see result live

The result on the second row has a URI (http://dbpedia.org/resource/Olaf_Scholz) as the result for mayor, which means there is more information available about that particular mayor (such as the gender). But in rows 1 and 3 (and, if you look at the full query result, most rows), the value for mayor is simply a string literal, not a resource URI - in these cases only the name of the mayor is recorded, but no further information.

Apart from that your second query is unnecessarily complex. There is no need to use subqueries or regular expressions to query the gender of mayors (for the ones that have a gender, at least), and using these complex query patterns is what makes your query time out. You can simply do this:

```<code>SELECT * WHERE {
 ?city a dbo:City .
 ?city dbo:populationTotal ?pop .
 ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader) ?mayor .
 ?mayor foaf:gender "female"@en
}
Order by DESC(?pop)
</code>```

Unfortunately it appears that this only gives you 2 or 3 results - the gender info on DBPedia is quite sparse. You can verify that this is the case by doing this query:

```<code>SELECT * WHERE {
  ?city a dbo:City .
  ?city dbo:populationTotal ?pop .
  ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader) ?mayor .
  ?mayor foaf:gender ?gender
 }
 Order by DESC(?pop)
</code>```

which gives you back all mayors for which a gender is known. As you can see the result is only 8 or so (2 female, 6 male).

Body:
I try to get all cities with a female mayor, but my problem is, that the most mayors if they are in marked in data they are mostly not linked to a person, they are only given as string. So how can I get the gender.

My command to get all mayors is:

SELECT * WHERE {
 ?city a dbo:City .
 ?city dbo:populationTotal ?pop .
 ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader) ?mayor

}
ORDER BY DESC(?pop)

I am not sure if I get all mayors, because there are only 500 mayors versus 19584 cities with given population that sounds less.

For the reason I did not get gender on this way I did a second request to get all female people in DBpedia and try to compare both results, but mostly ends in timeout or "no result"

On example command runs in timeout was:

SELECT ?name ?sayor WHERE {
 ?person a dbo:Person .
 ?person foaf:gender ?gender .
 FILTER regex(?gender, "^female$", "i") .
 ?person rdfs:label ?name .
 {
  SELECT str(?mayor) AS ?sayor WHERE {
   ?city a dbo:City .
   ?city (dbp:mayor | dbp:leader) ?mayor .
   FILTER (str(?mayor) = str(?name))
  }
 }
}

Has anyone an idea to get all cities with female mayor? I am also happy with getting some stimulation's.

Body:
Part of the problem is that DBPedia, for quite a lot of cities, doesn't record enough information to do this. If we take a look at the result of your original query, it looks like this:

city    pop     mayor
http://dbpedia.org/resource/Berlin  3610156 "Michael Müller"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#langString>
http://dbpedia.org/resource/Hamburg     1774242 http://dbpedia.org/resource/Olaf_Scholz
http://dbpedia.org/resource/Pekanbaru   1093416 "Prof. Dr. Andre Syahputra, M.Sc"^^<http://www.w3.org/1999/02/22-rdf-syntax-ns#langString>

see result live

The result on the second row has a URI (http://dbpedia.org/resource/Olaf_Scholz) as the result for mayor, which means there is more information available about that particular mayor (such as the gender). But in rows 1 and 3 (and, if you look at the full query result, most rows), the value for mayor is simply a string literal, not a resource URI - in these cases only the name of the mayor is recorded, but no further information.

Apart from that your second query is unnecessarily complex. There is no need to use subqueries or regular expressions to query the gender of mayors (for the ones that have a gender, at least), and using these complex query patterns is what makes your query time out. You can simply do this:

SELECT * WHERE {
 ?city a dbo:City .
 ?city dbo:populationTotal ?pop .
 ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader) ?mayor .
 ?mayor foaf:gender "female"@en
}
Order by DESC(?pop)

Unfortunately it appears that this only gives you 2 or 3 results - the gender info on DBPedia is quite sparse. You can verify that this is the case by doing this query:

SELECT * WHERE {
  ?city a dbo:City .
  ?city dbo:populationTotal ?pop .
  ?city (dbp:mayor | dbo:mayor | dbp:leader |dbo:leader) ?mayor .
  ?mayor foaf:gender ?gender
 }
 Order by DESC(?pop)

which gives you back all mayors for which a gender is known. As you can see the result is only 8 or so (2 female, 6 male).


问:
Extract JSON value to shell variable using jq
I have a json response as shown below :

```<code>[
 {"id":10,
 "list_file":["/var/a.txt",
             "/dev/b.txt"]}
]
</code>```

I need to extract values of list_file and store it shell variable as an array. I tried doing it looping through and reading the values.

```<code>#!/bin/bash
x=()
while read -r value
do
  #echo "$value"
  x+=("$value")
done < <(jq -r '.[] | .list_file' input.json)
</code>```

But the extracted values in the array contains quotes, brackets and comma too.

```<code>[
    "/var/a.txt",
    "/dev/b.txt"
]
</code>```

Could you please help me modify the code so that the array contains only the entries /var/a.txt and /dev/b.txt. Also, I tried readarray and map, but they won't work on Mac Osx. Any help would be really appreciated.

答:
You can use the @tsv string formatter in combination with --raw-output/-r option and split the output to bash array on tabs:

```<code>$ IFS=$'\t'
$ x=($(jq -r '.[] | .list_file | @tsv' input.json))
$ for xx in "${x[@]}"; do echo "$xx"; done
/var/a.txt
/dev/b.txt
</code>```

For -r will strip the outer quotes (useful for making jq filters talk to non-JSON-based systems), and @tsv will output an array as a series of tab-separated strings (tabs, newlines, etc. will be escaped).

Alternatively, you use the @sh filter which outputs an array as a series of space-separated strings. However, to interpret such output, you have to evaluate it:

```<code>$ eval "x=($(jq -r '.[] | .list_file | @sh' input.json))"
</code>```

Body:
I have a json response as shown below :

[
 {"id":10,
 "list_file":["/var/a.txt",
             "/dev/b.txt"]}
]

I need to extract values of list_file and store it shell variable as an array. I tried doing it looping through and reading the values.

#!/bin/bash
x=()
while read -r value
do
  #echo "$value"
  x+=("$value")
done < <(jq -r '.[] | .list_file' input.json)

But the extracted values in the array contains quotes, brackets and comma too.

[
    "/var/a.txt",
    "/dev/b.txt"
]

Could you please help me modify the code so that the array contains only the entries /var/a.txt and /dev/b.txt. Also, I tried readarray and map, but they won't work on Mac Osx. Any help would be really appreciated.

Body:
You can use the @tsv string formatter in combination with --raw-output/-r option and split the output to bash array on tabs:

$ IFS=$'\t'
$ x=($(jq -r '.[] | .list_file | @tsv' input.json))
$ for xx in "${x[@]}"; do echo "$xx"; done
/var/a.txt
/dev/b.txt

For -r will strip the outer quotes (useful for making jq filters talk to non-JSON-based systems), and @tsv will output an array as a series of tab-separated strings (tabs, newlines, etc. will be escaped).

Alternatively, you use the @sh filter which outputs an array as a series of space-separated strings. However, to interpret such output, you have to evaluate it:

$ eval "x=($(jq -r '.[] | .list_file | @sh' input.json))"


问:
msxml3.dll in context sp_OAMethod 'send'
Working code from Win2003 + SQL Server 2005 is not working under Win2012 + SQL Server 2012 sp1.

The only ~real solution I found is:

I copied C:\Windows\System32\msxml3.dll from a Server 2008 to the same
  dir on a server 2012. Problem on 2012 server solved, sending with POST
  and GET working fine.

But as I cannot modify server and both msxml3.dll and msxml6.dll are locked - I need to understand what is wrong and apply other way.

Code is simple as usual for grabbing soap web service:

```<code>Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
Declare @ErrCode    Int;

Exec sp_OACreate 'MSXML2.ServerXMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'post','http://example.com/Authentication.asmx','false'
Exec sp_OAMethod @Object ,'setRequestHeader'    ,NULL ,'Content-Type'   ,'text/xml; charset=utf-8'
Exec sp_OAMethod @Object ,'setRequestHeader'    ,NULL ,'SOAPAction' ,'"http://www.example.com/Login"'
Exec @ErrCode=sp_OAMethod @Object, 'send',null,'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Body>
    <Login xmlns="http://www.example.com/">
      <databaseName>db1</databaseName>
      <userName>login</userName>
      <password>pass</password>
    </Login>
  </soap:Body>
</soap:Envelope>'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ErrCode,@ResponseText
Exec sp_OADestroy @Object
</code>```

I tried both MSXML2.XMLHTTP and MSXML2.ServerXMLHTTP (as well as .6.0 versions) objects.

Error id: -2147024809, with remark 'send' failed. The parameter is incorrect.

Of course Ole Automation Procedures is enabled.

答:
I stumbled upon this nasty issue for an entire weekend. I personally found horrible the "replace DLL" workaround, so I did my best to come out with a safer solution... Luckily enough, I actually found two of them.

Solution 1

Apply the following MS HotFix, which fixes the issue for good:

https://support.microsoft.com/en-us/help/2968741/error-0x80070057-when-sql-server-communicates-to-a-web-server-using-st

(read the post for further info and to request the hotfix via e-mail through MS secure channels)

Solution 2

If you can't apply the HotFix, you can still get the job done by using a slightly different syntax when issuing the SEND command. Instead of this:

```<code>Exec @ErrCode=sp_OAMethod @Object, 'send',null,'your-data';
</code>```

do this:

```<code>Exec @ErrCode=sp_OAMethod @Object, 'send("your-data")';
</code>```

It works for any type of HTTP request data: JSON, XML and even application/x-www-form-urlencoded for standard POST request. The downside is that such syntax is quite ugly... and you have to change all your Stored Procedures that way.

For additional info regarding the issue you can also read this post on my blog.

Body:
Working code from Win2003 + SQL Server 2005 is not working under Win2012 + SQL Server 2012 sp1.

The only ~real solution I found is:

I copied C:\Windows\System32\msxml3.dll from a Server 2008 to the same
  dir on a server 2012. Problem on 2012 server solved, sending with POST
  and GET working fine.

But as I cannot modify server and both msxml3.dll and msxml6.dll are locked - I need to understand what is wrong and apply other way.

Code is simple as usual for grabbing soap web service:

Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
Declare @ErrCode    Int;

Exec sp_OACreate 'MSXML2.ServerXMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'post','http://example.com/Authentication.asmx','false'
Exec sp_OAMethod @Object ,'setRequestHeader'    ,NULL ,'Content-Type'   ,'text/xml; charset=utf-8'
Exec sp_OAMethod @Object ,'setRequestHeader'    ,NULL ,'SOAPAction' ,'"http://www.example.com/Login"'
Exec @ErrCode=sp_OAMethod @Object, 'send',null,'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soap:Body>
    <Login xmlns="http://www.example.com/">
      <databaseName>db1</databaseName>
      <userName>login</userName>
      <password>pass</password>
    </Login>
  </soap:Body>
</soap:Envelope>'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ErrCode,@ResponseText
Exec sp_OADestroy @Object

I tried both MSXML2.XMLHTTP and MSXML2.ServerXMLHTTP (as well as .6.0 versions) objects.

Error id: -2147024809, with remark 'send' failed. The parameter is incorrect.

Of course Ole Automation Procedures is enabled.

Body:
I stumbled upon this nasty issue for an entire weekend. I personally found horrible the "replace DLL" workaround, so I did my best to come out with a safer solution... Luckily enough, I actually found two of them.

Solution 1

Apply the following MS HotFix, which fixes the issue for good:

https://support.microsoft.com/en-us/help/2968741/error-0x80070057-when-sql-server-communicates-to-a-web-server-using-st

(read the post for further info and to request the hotfix via e-mail through MS secure channels)

Solution 2

If you can't apply the HotFix, you can still get the job done by using a slightly different syntax when issuing the SEND command. Instead of this:

Exec @ErrCode=sp_OAMethod @Object, 'send',null,'your-data';

do this:

Exec @ErrCode=sp_OAMethod @Object, 'send("your-data")';

It works for any type of HTTP request data: JSON, XML and even application/x-www-form-urlencoded for standard POST request. The downside is that such syntax is quite ugly... and you have to change all your Stored Procedures that way.

For additional info regarding the issue you can also read this post on my blog.

ContentLicense: CC BY-SA 4.0


问:
Split my file into 128 bytes using c++
I am new to C++, and I need to make a program to read a file and divide it into blocks of 214 bytes. In Java, I used readAllBytes() like this:

byte[] data= Files.readAllBytes(path);
for (int i = 0; i < data.length; i += 215) {
    byte[] data1 = Arrays.copyOfRange(data, i, i + 214);
}
```

<p>Now, in C++, I read the file into a buffer, but I dont have a clue how to divide the buffer into blocks of 214 bytes:</p>

<pre class="lang-cpp prettyprint-override"><code>#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{

    FILE *fileptr;
    char *buffer;
    long filelen;

    fileptr = fopen("test.txt", "rb");
    fseek(fileptr, 0, SEEK_END);
    filelen = ftell(fileptr);
    rewind(fileptr);
    buffer = (char *)malloc((filelen + 1) * sizeof(char));
    fread(buffer, filelen, 1, fileptr);
    cout << buffer;

    fclose(fileptr);
    return 0;
}
</code>```

Can anyone help me make this program, please?

答:
You can make a buffer the size of the chunks you want and try to read a full buffer each time, like this:

```<code>std::ifstream ifs("test.txt", std::ios::binary);

char buf[214];

while(ifs.read(buf, sizeof(buf)) || ifs.gcount())
{
    // use what was read in.

    // gcount() is the number of bytes actually read
    std::string chunk(buf, ifs.gcount());

    std::cout << chunk << '\n';
}
</code>```

Bear in mind that the final buffer may well have less that 214 characters in it.

Title: Split my file into 128 bytes using c++

Body:
I am new to C++, and I need to make a program to read a file and divide it into blocks of 214 bytes. In Java, I used readAllBytes() like this:

byte[] data= Files.readAllBytes(path);
for (int i = 0; i < data.length; i += 215) {
    byte[] data1 = Arrays.copyOfRange(data, i, i + 214);
}

Now, in C++, I read the file into a buffer, but I dont have a clue how to divide the buffer into blocks of 214 bytes:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{

    FILE *fileptr;
    char *buffer;
    long filelen;

    fileptr = fopen("test.txt", "rb");
    fseek(fileptr, 0, SEEK_END);
    filelen = ftell(fileptr);
    rewind(fileptr);
    buffer = (char *)malloc((filelen + 1) * sizeof(char));
    fread(buffer, filelen, 1, fileptr);
    cout << buffer;

    fclose(fileptr);
    return 0;
}

Can anyone help me make this program, please?

Body:
You can make a buffer the size of the chunks you want and try to read a full buffer each time, like this:

std::ifstream ifs("test.txt", std::ios::binary);

char buf[214];

while(ifs.read(buf, sizeof(buf)) || ifs.gcount())
{
    // use what was read in.

    // gcount() is the number of bytes actually read
    std::string chunk(buf, ifs.gcount());

    std::cout << chunk << '\n';
}

Bear in mind that the final buffer may well have less that 214 characters in it.


问:
Mailchimp ajax SyntaxError on form submission
As I can see there is no errors in code, but still its showing this
SyntaxError: missing ; before statement screenshot

Here is the Form:

```<code><form id="bildo_mc_form" action="https://stylishcreativity.us3.list-manage.com/subscribe/post-json?u=7c7040d58ca368b8f8063c1ea&id=f67dfc67a4" method="post">
    <input id="mc-email" type="email" name="EMAIL" placeholder="Your Email">
    <label for="mc-email"></label>
    <button type="submit">Send</button>
</form>
</code>```

Here is the Js:

```<code>jQuery("#bildo_mc_form").submit(function(e){

    console.log("form submitted");

    function callbackFunction(data){
        window.location.href = "http://thanks.com";
        console.log("sucess result" + data.result);
        console.log("sucess msg" + data.msg);
    }

    var url = jQuery(this).prop('action'); // the script where you handle the form input.
    jQuery.ajax({
           type: "GET",
           url: url,
           data: jQuery("#bildo_mc_form").serialize(), // serializes the form's elements.
           dataType: "jsonp",
           contentType: "application/json; charset=utf-8",
           error: function(error){
                // According to jquery docs, this is never called for cross-domain JSONP requests
                console.log("Error Result" + error.result);
            },
           success: callbackFunction
        });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});
</code>```

How can I get rid of this issue?
Pls help :)

答:
Since you receive JSON by ajax, you should set dataType: "json".

Not jsonp.

jsonp response is being executed as a function and it causes the error.

jQuery("#bildo_mc_form").submit(function(e){

    console.log("form submitted");

    function callbackFunction(data){
        window.location.href = "http://thanks.com";
        console.log("sucess result" + data.result);
        console.log("sucess msg" + data.msg);
    }

    var url = jQuery(this).prop('action'); // the script where you handle the form input.
    jQuery.ajax({
           type: "GET",
           url: url,
           data: jQuery("#bildo_mc_form").serialize(), // serializes the form's elements.
           dataType: "json",
           contentType: "application/json; charset=utf-8",
           error: function(error){
                // According to jquery docs, this is never called for cross-domain JSONP requests
                console.log("Error Result" + error.result);
            },
           success: callbackFunction
        });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="bildo_mc_form" action="https://stylishcreativity.us3.list-manage.com/subscribe/post-json?u=7c7040d58ca368b8f8063c1ea&id=f67dfc67a4" method="post">
    <input id="mc-email" type="email" name="EMAIL" placeholder="Your Email">
    <label for="mc-email"></label>
    <button type="submit">Send</button>
</form></code>```

Body:
As I can see there is no errors in code, but still its showing this
SyntaxError: missing ; before statement screenshot

Here is the Form:

<form id="bildo_mc_form" action="https://stylishcreativity.us3.list-manage.com/subscribe/post-json?u=7c7040d58ca368b8f8063c1ea&id=f67dfc67a4" method="post">
    <input id="mc-email" type="email" name="EMAIL" placeholder="Your Email">

    <button type="submit">Send</button>
</form>

Here is the Js:

jQuery("#bildo_mc_form").submit(function(e){

    console.log("form submitted");

    function callbackFunction(data){
        window.location.href = "http://thanks.com";
        console.log("sucess result" + data.result);
        console.log("sucess msg" + data.msg);
    }

    var url = jQuery(this).prop('action'); // the script where you handle the form input.
    jQuery.ajax({
           type: "GET",
           url: url,
           data: jQuery("#bildo_mc_form").serialize(), // serializes the form's elements.
           dataType: "jsonp",
           contentType: "application/json; charset=utf-8",
           error: function(error){
                // According to jquery docs, this is never called for cross-domain JSONP requests
                console.log("Error Result" + error.result);
            },
           success: callbackFunction
        });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

How can I get rid of this issue?
Pls help :)

Body:
Since you receive JSON by ajax, you should set dataType: "json".

Not jsonp.

jsonp response is being executed as a function and it causes the error.

jQuery("#bildo_mc_form").submit(function(e){

    console.log("form submitted");

    function callbackFunction(data){
        window.location.href = "http://thanks.com";
        console.log("sucess result" + data.result);
        console.log("sucess msg" + data.msg);
    }

    var url = jQuery(this).prop('action'); // the script where you handle the form input.
    jQuery.ajax({
           type: "GET",
           url: url,
           data: jQuery("#bildo_mc_form").serialize(), // serializes the form's elements.
           dataType: "json",
           contentType: "application/json; charset=utf-8",
           error: function(error){
                // According to jquery docs, this is never called for cross-domain JSONP requests
                console.log("Error Result" + error.result);
            },
           success: callbackFunction
        });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="bildo_mc_form" action="https://stylishcreativity.us3.list-manage.com/subscribe/post-json?u=7c7040d58ca368b8f8063c1ea&amp;id=f67dfc67a4" method="post">
    <input id="mc-email" type="email" name="EMAIL" placeholder="Your Email">
    <label for="mc-email"></label>
    <button type="submit">Send</button>
</form>


问:
Design patterns to avoid
A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

答:
Singletons - a class using singleton X has a dependency on it that's hard to see and hard to isolate for testing.

They're used very often because they're convenient and easy to understand, but they can really complicate testing.

See Singletons are Pathological Liars.

OwnerDisplayName: Brian Rasmussen

Title: Design patterns to avoid

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: orip


问:
JLabel: load HTML images asynchronously
A JLabel allows HTML contents, which can contain an image among the contents:

```<code>String html = "<html><body>...<img src=\"http://some_url/image.png\"/>...</body></html>";
JLabel label = new JLabel(html);
</code>```

Note that I use the JLabel for rendering images in a JXTreeTable, so the updating of the text of the JLabel is done on the EDT in the renderer.

The problem is that the image gets loaded synchronously. With a slow server, the EDT can be blocked for multiple seconds while the image is being loaded.

I already discovered why the image gets loaded synchronously, and which class I need to modify to switch to async loading of images.

The loading of the image is done by the javax.swing.text.html.ImageView class, which has a method setLoadsSynchronously.

The problem is that I have no clue how I can easily adjust the HTMLFactory / HTMLEditorKit which is responsible for creating that ImageView, and which is used internally by the JLabel .
To make matters even more complicated, I need a solution which works for all Look and Feels.

In case the above is not clear, the following thread dump shows on what the EDT is blocked during the image retrieval:

```<code>"AWT-EventQueue-0@999" prio=6 tid=0x10 nid=NA waiting
  java.lang.Thread.State: WAITING
      at java.lang.Object.wait(Object.java:-1)
      at java.awt.MediaTracker.waitForID(MediaTracker.java:677)
      at javax.swing.ImageIcon.loadImage(ImageIcon.java:314)
      at javax.swing.ImageIcon.setImage(ImageIcon.java:381)
      at javax.swing.text.html.ImageView.loadImage(ImageView.java:704)
      at javax.swing.text.html.ImageView.refreshImage(ImageView.java:673)
      at javax.swing.text.html.ImageView.sync(ImageView.java:645)
      at javax.swing.text.html.ImageView.getPreferredSpan(ImageView.java:443)
      at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:732)
      at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:233)
      at javax.swing.text.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:717)
      at javax.swing.text.html.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:157)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.ParagraphView.getMinimumSpan(ParagraphView.java:270)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:378)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:378)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getPreferredSpan(BoxView.java:545)
      at javax.swing.text.html.BlockView.getPreferredSpan(BlockView.java:362)
      at javax.swing.plaf.basic.BasicHTML$Renderer.<init>(BasicHTML.java:383)
      at javax.swing.plaf.basic.BasicHTML.createHTMLView(BasicHTML.java:67)
      at javax.swing.plaf.basic.BasicHTML.updateRenderer(BasicHTML.java:207)
      at javax.swing.plaf.basic.BasicLabelUI.propertyChange(BasicLabelUI.java:417)
      at javax.swing.plaf.synth.SynthLabelUI.propertyChange(SynthLabelUI.java:296)
      at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
      at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:327)
      at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
      at java.awt.Component.firePropertyChange(Component.java:8428)
      at org.jdesktop.swingx.renderer.JRendererLabel.firePropertyChange(JRendererLabel.java:292)
      at javax.swing.JLabel.setText(JLabel.java:330)
</code>```

答:
The image is only part of the HTML…calling setIcon is not an option.

One approach would be to load the image in the background of a SwingWorker, save it temporarily to the file system, and reference the saved file in the  tag. The variation below, adapted from this example, is a proof of concept. Your actual implementation might employ a SwingWorker<List<Row>, Row>, where each Row contains an image File; your doInBackground() implementation would publish() interim results as they become available; your implementation of process() would ensure that the relevant tree-table renderer sees the correct File for a given Row.

```<code>import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 * @see http://stackoverflow.com/questions/4530659 */
public class WorkerTest extends JFrame {

    private JPanel panel = new JPanel();
    private JLabel label = new JLabel("Loading...");

    public WorkerTest() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label.setHorizontalTextPosition(JLabel.CENTER);
        label.setVerticalTextPosition(JLabel.CENTER);
        this.add(label);
        this.pack();
        this.setLocationRelativeTo(null);
    }

    private void start() {
        new ImageWorker().execute();
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                WorkerTest wt = new WorkerTest();
                wt.setVisible(true);
                wt.start();
            }
        });
    }

    class ImageWorker extends SwingWorker<File, Void> {

        private static final String TEST =
            "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";
        private BufferedImage image;
        private File file;

        @Override
        protected File doInBackground() throws IOException {
            image = ImageIO.read(new URL(TEST));
            file = File.createTempFile("image", null);
            ImageIO.write(image, "png", file);
            return file;
        }

        @Override
        protected void done() {
            label.setText("<html><body><img src=\"file://"
                + file.getAbsolutePath() + "\"/></body></html>");
            panel.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
            WorkerTest.this.pack();
            WorkerTest.this.setLocationRelativeTo(null);
        }
    }
}
</code>```

Title: JLabel: load HTML images asynchronously

Body:
A JLabel allows HTML contents, which can contain an image among the contents:

String html = "......";
JLabel label = new JLabel(html);

Note that I use the JLabel for rendering images in a JXTreeTable, so the updating of the text of the JLabel is done on the EDT in the renderer.

The problem is that the image gets loaded synchronously. With a slow server, the EDT can be blocked for multiple seconds while the image is being loaded.

I already discovered why the image gets loaded synchronously, and which class I need to modify to switch to async loading of images.

The loading of the image is done by the javax.swing.text.html.ImageView class, which has a method setLoadsSynchronously.

The problem is that I have no clue how I can easily adjust the HTMLFactory / HTMLEditorKit which is responsible for creating that ImageView, and which is used internally by the JLabel .
To make matters even more complicated, I need a solution which works for all Look and Feels.

In case the above is not clear, the following thread dump shows on what the EDT is blocked during the image retrieval:

"AWT-EventQueue-0@999" prio=6 tid=0x10 nid=NA waiting
  java.lang.Thread.State: WAITING
      at java.lang.Object.wait(Object.java:-1)
      at java.awt.MediaTracker.waitForID(MediaTracker.java:677)
      at javax.swing.ImageIcon.loadImage(ImageIcon.java:314)
      at javax.swing.ImageIcon.setImage(ImageIcon.java:381)
      at javax.swing.text.html.ImageView.loadImage(ImageView.java:704)
      at javax.swing.text.html.ImageView.refreshImage(ImageView.java:673)
      at javax.swing.text.html.ImageView.sync(ImageView.java:645)
      at javax.swing.text.html.ImageView.getPreferredSpan(ImageView.java:443)
      at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:732)
      at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:233)
      at javax.swing.text.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:717)
      at javax.swing.text.html.ParagraphView.calculateMinorAxisRequirements(ParagraphView.java:157)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.ParagraphView.getMinimumSpan(ParagraphView.java:270)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:378)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:568)
      at javax.swing.text.html.BlockView.getMinimumSpan(BlockView.java:378)
      at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:903)
      at javax.swing.text.html.BlockView.calculateMinorAxisRequirements(BlockView.java:146)
      at javax.swing.text.BoxView.checkRequests(BoxView.java:935)
      at javax.swing.text.BoxView.getPreferredSpan(BoxView.java:545)
      at javax.swing.text.html.BlockView.getPreferredSpan(BlockView.java:362)
      at javax.swing.plaf.basic.BasicHTML$Renderer.<init>(BasicHTML.java:383)
      at javax.swing.plaf.basic.BasicHTML.createHTMLView(BasicHTML.java:67)
      at javax.swing.plaf.basic.BasicHTML.updateRenderer(BasicHTML.java:207)
      at javax.swing.plaf.basic.BasicLabelUI.propertyChange(BasicLabelUI.java:417)
      at javax.swing.plaf.synth.SynthLabelUI.propertyChange(SynthLabelUI.java:296)
      at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:335)
      at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:327)
      at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:263)
      at java.awt.Component.firePropertyChange(Component.java:8428)
      at org.jdesktop.swingx.renderer.JRendererLabel.firePropertyChange(JRendererLabel.java:292)
      at javax.swing.JLabel.setText(JLabel.java:330)

Body:
The image is only part of the HTML…calling setIcon is not an option.

One approach would be to load the image in the background of a SwingWorker, save it temporarily to the file system, and reference the saved file in the <img/> tag. The variation below, adapted from this example, is a proof of concept. Your actual implementation might employ a SwingWorker<List<Row>, Row>, where each Row contains an image File; your doInBackground() implementation would publish() interim results as they become available; your implementation of process() would ensure that the relevant tree-table renderer sees the correct File for a given Row.

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
 * @see http://stackoverflow.com/questions/4530659 */
public class WorkerTest extends JFrame {

    private JPanel panel = new JPanel();
    private JLabel label = new JLabel("Loading...");

    public WorkerTest() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        label.setHorizontalTextPosition(JLabel.CENTER);
        label.setVerticalTextPosition(JLabel.CENTER);
        this.add(label);
        this.pack();
        this.setLocationRelativeTo(null);
    }

    private void start() {
        new ImageWorker().execute();
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                WorkerTest wt = new WorkerTest();
                wt.setVisible(true);
                wt.start();
            }
        });
    }

    class ImageWorker extends SwingWorker<File, Void> {

        private static final String TEST =
            "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";
        private BufferedImage image;
        private File file;

        @Override
        protected File doInBackground() throws IOException {
            image = ImageIO.read(new URL(TEST));
            file = File.createTempFile("image", null);
            ImageIO.write(image, "png", file);
            return file;
        }

        @Override
        protected void done() {
            label.setText("<html><body><img src=\"file://"
                + file.getAbsolutePath() + "\"/></body></html>");
            panel.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
            WorkerTest.this.pack();
            WorkerTest.this.setLocationRelativeTo(null);
        }
    }
}


问:
Shrink double if statement in Python
I cannot use the following statement because x and y may be defined as None:

```<code>if x*y > 9:
    pass
</code>```

unsupported operand type(s) for *: 'NoneType' and 'NoneType'

So I should check first for the existence:

```<code>if x and y:
    if x*y > 9:
        pass
</code>```

It seems a bit redundant. Is there a better way to achieve this?

答:
Following the EAFP (Easier to Ask Forgiveness than Permission) protocol, here's an alternative using try and except:

```<code>try:
   if x * y > 9:
       pass
except TypeError:
   pass
</code>```

Title: Shrink double if statement in Python

Body:
I cannot use the following statement because x and y may be defined as None:

if x*y > 9:
    pass

unsupported operand type(s) for *: 'NoneType' and 'NoneType'

So I should check first for the existence:

if x and y:
    if x*y > 9:
        pass

It seems a bit redundant. Is there a better way to achieve this?

Body:
Following the EAFP (Easier to Ask Forgiveness than Permission) protocol, here's an alternative using try and except:

try:
   if x * y > 9:
       pass
except TypeError:
   pass


问:
Accessing Values in Deeply Nested Array - Ruby on Rails
I am using an API call which returns a JSON response. I want to access the data inside the response so I can create some nice display cards showing the info and pictures. Here is a snippet from the response, the response property is populated with about 20 objects I'll include just two for brevity:

```<code>{
    "success": true,
    "message": "",
    "result": [
        {
            "MarketCurrency": "LTC",
            "BaseCurrency": "BTC",
            "MarketCurrencyLong": "Litecoin",
            "BaseCurrencyLong": "Bitcoin",
            "MinTradeSize": 1e-8,
            "MarketName": "BTC-LTC",
            "IsActive": true,
            "Created": "2014-02-13T00:00:00",
            "Notice": null,
            "IsSponsored": null,
            "LogoUrl": "https://i.imgur.com/R29q3dD.png"
        },
        {
            "MarketCurrency": "DOGE",
            "BaseCurrency": "BTC",
            "MarketCurrencyLong": "Dogecoin",
            "BaseCurrencyLong": "Bitcoin",
            "MinTradeSize": 1e-8,
            "MarketName": "BTC-DOGE",
            "IsActive": true,
            "Created": "2014-02-13T00:00:00",
            "Notice": null,
            "IsSponsored": null,
            "LogoUrl": "https://i.imgur.com/e1RS4Hn.png"
        },
</code>```

In my Rails controller I'm using JSON.parse and I'm trying to turn it into an object with the Open struct option:

```<code>@markets = JSON.parse(markets.to_json, object_class: OpenStruct)
</code>```

In my view I'll do this <%=@markets.class%> and it shows Array and not object. So I try this <%=@markets.size%> and it shows 1. If I do <%=@markets[0]['success']%> I would expect it to return true but it returns 'success'. So, I'm not understanding why the ostruct library isn't working like I would expect or how I can get to the objects stored in the result array. Any help is greatly appreciated!

答:
You already have a JSON response, isn't needed to use to_json again, try just parsing that object, and then use the dot . to access its fields, as an OpenStruct object now then you can access them as methods:

```<code>require 'json'

a = '{
  "success": true,
  "message": "",
  "result": [{
    "MarketCurrency": "LTC",
    "BaseCurrency": "BTC",
    "MarketCurrencyLong": "Litecoin",
    "BaseCurrencyLong": "Bitcoin",
    "MinTradeSize": 1e-8,
    "MarketName": "BTC-LTC",
    "IsActive": true,
    "Created": "2014-02-13T00:00:00",
    "Notice": null,
    "IsSponsored": null,
    "LogoUrl": "https://i.imgur.com/R29q3dD.png"
  }, {
    "MarketCurrency": "DOGE",
    "BaseCurrency": "BTC",
    "MarketCurrencyLong": "Dogecoin",
    "BaseCurrencyLong": "Bitcoin",
    "MinTradeSize": 1e-8,
    "MarketName": "BTC-DOGE",
    "IsActive": true,
    "Created": "2014-02-13T00:00:00",
    "Notice": null,
    "IsSponsored": null,
    "LogoUrl": "https://i.imgur.com/e1RS4Hn.png"
  }]
}'

b = JSON.parse(a, object_class: OpenStruct)
p b.success
# => true
</code>```

Body:
I am using an API call which returns a JSON response. I want to access the data inside the response so I can create some nice display cards showing the info and pictures. Here is a snippet from the response, the response property is populated with about 20 objects I'll include just two for brevity:

{
    "success": true,
    "message": "",
    "result": [
        {
            "MarketCurrency": "LTC",
            "BaseCurrency": "BTC",
            "MarketCurrencyLong": "Litecoin",
            "BaseCurrencyLong": "Bitcoin",
            "MinTradeSize": 1e-8,
            "MarketName": "BTC-LTC",
            "IsActive": true,
            "Created": "2014-02-13T00:00:00",
            "Notice": null,
            "IsSponsored": null,
            "LogoUrl": "https://i.imgur.com/R29q3dD.png"
        },
        {
            "MarketCurrency": "DOGE",
            "BaseCurrency": "BTC",
            "MarketCurrencyLong": "Dogecoin",
            "BaseCurrencyLong": "Bitcoin",
            "MinTradeSize": 1e-8,
            "MarketName": "BTC-DOGE",
            "IsActive": true,
            "Created": "2014-02-13T00:00:00",
            "Notice": null,
            "IsSponsored": null,
            "LogoUrl": "https://i.imgur.com/e1RS4Hn.png"
        },

In my Rails controller I'm using JSON.parse and I'm trying to turn it into an object with the Open struct option:

@markets = JSON.parse(markets.to_json, object_class: OpenStruct)

In my view I'll do this <%=@markets.class%> and it shows Array and not object. So I try this <%=@markets.size%> and it shows 1. If I do <%=@markets[0]['success']%> I would expect it to return true but it returns 'success'. So, I'm not understanding why the ostruct library isn't working like I would expect or how I can get to the objects stored in the result array. Any help is greatly appreciated!

Body:
You already have a JSON response, isn't needed to use to_json again, try just parsing that object, and then use the dot . to access its fields, as an OpenStruct object now then you can access them as methods:

require 'json'

a = '{
  "success": true,
  "message": "",
  "result": [{
    "MarketCurrency": "LTC",
    "BaseCurrency": "BTC",
    "MarketCurrencyLong": "Litecoin",
    "BaseCurrencyLong": "Bitcoin",
    "MinTradeSize": 1e-8,
    "MarketName": "BTC-LTC",
    "IsActive": true,
    "Created": "2014-02-13T00:00:00",
    "Notice": null,
    "IsSponsored": null,
    "LogoUrl": "https://i.imgur.com/R29q3dD.png"
  }, {
    "MarketCurrency": "DOGE",
    "BaseCurrency": "BTC",
    "MarketCurrencyLong": "Dogecoin",
    "BaseCurrencyLong": "Bitcoin",
    "MinTradeSize": 1e-8,
    "MarketName": "BTC-DOGE",
    "IsActive": true,
    "Created": "2014-02-13T00:00:00",
    "Notice": null,
    "IsSponsored": null,
    "LogoUrl": "https://i.imgur.com/e1RS4Hn.png"
  }]
}'

b = JSON.parse(a, object_class: OpenStruct)
p b.success
# => true


问:
Terms & Conditions Gem for Rails
```<code>Rails 3.2
</code>```

I have a Rails application that the product team would like me to add a "Terms & Conditions" section that a new user would have to scroll through until the end, before the new user creation process is completed (I am using Devise for user management).

I did a search for a Gem, but could not find any. Anyone know of a Gem I can use, or should I write a piece of code from scratch?

答: Don't think you need a gem for this, just create your custom Devise view and add in a Terms & Conditions scrollable div. Then you can use something like this question to detect when they scroll to the bottom of it. Keep your submit button disabled and when you detect they reach the bottom enable it and allow them to submit.</p>

Title: Terms & Conditions Gem for Rails

Body:
Rails 3.2

I have a Rails application that the product team would like me to add a "Terms & Conditions" section that a new user would have to scroll through until the end, before the new user creation process is completed (I am using Devise for user management).

I did a search for a Gem, but could not find any. Anyone know of a Gem I can use, or should I write a piece of code from scratch?


问:
How Do I Force Redrawing (drawRect) of a SubView When it Changes Dimensions?
I have a UIView that contains a row of subclasses of UIView. The subclass has overridden drawRect: and has set  contentMode = UIViewContentModeRedraw.

As the user squashes and stretches the parent container the child views squash and stretch. As the shape change occurs I would like to have drawRect called repeatedly to change the contents of the child views. So far I have been unsuccessful. What is the correct way to do this?

Cheers,

Doug

答:
This solution is a little crazy, but it makes logical sense, and has a great visual result.  I'm working with a NSLayoutManager and a couple NSTextContainers, laying out text in two columns.  Because I'm using multiple text containers (and I'm not sure I want multiple UITextView), I'm overriding the draw(rect: CGRect) method of MyDrawingView: UIView.

The problem is that using self.contentMode = .redraw still results in some minor stretching on rotation--significant enough to be a deal-breaker.

I noticed that setting contentMode = .left, or even contentMode = .scaleAspectFit was close to what I wanted, in terms of pixel-perfect rotation.  But obviously, I wasn't getting the draw call I needed.

So--I overrode layoutSubviews(), switched the contentMode to .scaleAspectFit, called super.layoutSubviews(), and then switched it back.  :P

```<code>override func layoutSubviews() {
    self.contentMode = .scaleAspectFit

    super.layoutSubviews()
    self.contentMode = .redraw
}
</code>```

It is...perfect.

Body:
This solution is a little crazy, but it makes logical sense, and has a great visual result.  I'm working with a NSLayoutManager and a couple NSTextContainers, laying out text in two columns.  Because I'm using multiple text containers (and I'm not sure I want multiple UITextView), I'm overriding the draw(rect: CGRect) method of MyDrawingView: UIView.

The problem is that using self.contentMode = .redraw still results in some minor stretching on rotation--significant enough to be a deal-breaker.

I noticed that setting contentMode = .left, or even contentMode = .scaleAspectFit was close to what I wanted, in terms of pixel-perfect rotation.  But obviously, I wasn't getting the draw call I needed.

So--I overrode layoutSubviews(), switched the contentMode to .scaleAspectFit, called super.layoutSubviews(), and then switched it back.  :P

override func layoutSubviews() {
    self.contentMode = .scaleAspectFit

    super.layoutSubviews()
    self.contentMode = .redraw
}

It is...perfect.


问:
iOS app extension to modify phone keypad
I want to extend the functionality of phone keyboard.

I can't find any documentation on whether iOS 8+ has an API to do this. If it's possible can someone point me to some docs?

答:
There is currently no API to extend the functionality of the iOS phone keypad system-wide.

It is possible to create a system-wide custom keyboard (documention), as well as call a phone number from an app, but not to override the system phone UI.