问:
ARcore and mobile-vision
I need to create an android app doing mainly two things.

1) Detect price and barcode

2) Creating AR content around the detected price/barcode

For the detection part, I use google mobile-vision and for the AR part I use ARcore. The problem I have is that Arcore doesnt allow auto focus so I dont have a good enough resolution to read the prices or bar codes.

So I was wondering if there was a standard way to do text recognition and AR in the same app.

Thank you.

答:
You can implement them in the same app, on different activities. if you are using the mobile vision API. you can set the start the intent for detection with startActivityForResult and when the result is returned. you can Implement a transistion in the onActivityResult part. Since the AR depends on the detected data you can pass the information to the AR activity using putExtra. use this as a template

```<code> fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(DetectActivity.this, ScanActivity.class);
                    startActivityForResult(i, REQUEST_CODE);

                }
            });

     @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
                if (data != null) {

                    final Barcode barcode = data.getParcelableExtra("barcode");
                    String rslt=barcode.displayValue;

Intent intent =new Intent(DetectActivity.this, ArActivity.class);
                    intent.putExtra("link", rslt);
                    startActivity(intent);
                    finish();
</code>```

Hope this helps,
ScanActivity is the normal Camera View SurfaceView activity that mobile vision uses

Title: ARcore and mobile-vision

Body:
You can implement them in the same app, on different activities. if you are using the mobile vision API. you can set the start the intent for detection with startActivityForResult and when the result is returned. you can Implement a transistion in the onActivityResult part. Since the AR depends on the detected data you can pass the information to the AR activity using putExtra. use this as a template

 fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(DetectActivity.this, ScanActivity.class);
                    startActivityForResult(i, REQUEST_CODE);

                }
            });

     @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
                if (data != null) {

                    final Barcode barcode = data.getParcelableExtra("barcode");
                    String rslt=barcode.displayValue;

Intent intent =new Intent(DetectActivity.this, ArActivity.class);
                    intent.putExtra("link", rslt);
                    startActivity(intent);
                    finish();

Hope this helps,
ScanActivity is the normal Camera View SurfaceView activity that mobile vision uses


来源: stackexchange

问:
Get name of currently executing test in JUnit 4
In JUnit 3, I could get the name of the currently running test like this:

```<code>public class MyTest extends TestCase
{
    public void testSomething()
    {
        System.out.println("Current test is " + getName());
        ...
    }
}
</code>```

which would print "Current test is testSomething".

Is there any out-of-the-box or simple way to do this in JUnit 4?

Background: Obviously, I don't want to just print the name of the test. I want to load test-specific data that is stored in a resource with the same name as the test. You know, convention over configuration and all that.

答: I'd suggest you decouple the test method name from your test data set. I would model a DataLoaderFactory class which loads/caches the sets of test data from your resources, and then in your test case cam call some interface method which returns a set of test data for the test case. Having the test data tied to the test method name assumes the test data can only be used once, where in most case i'd suggest that the same test data in uses in multiple tests to verify various aspects of your business logic.   </p>

OwnerDisplayName: Dave Ray

ContentLicense: CC BY-SA 4.0

Body:
In JUnit 3, I could get the name of the currently running test like this:

public class MyTest extends TestCase
{
    public void testSomething()
    {
        System.out.println("Current test is " + getName());
        ...
    }
}

which would print "Current test is testSomething".

Is there any out-of-the-box or simple way to do this in JUnit 4?

Background: Obviously, I don't want to just print the name of the test. I want to load test-specific data that is stored in a resource with the same name as the test. You know, convention over configuration and all that.

LastEditorDisplayName: Dave Ray

ContentLicense: CC BY-SA 2.5


问:
awk: take entries from file and add values in between
I have the following file:

```<code>2    some
5    some
8    some
10   thing
15   thing
19   thing
</code>```

Now I want to end up with entries, where for "some" 2,5,8 correspond to rows where there is a 1, everything else is 0. It doesn't matter how many rows there are. This means for "some":

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

and for "thing"

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

Is this possible in a quick way with awk? I mean with something like:

```<code>awk '{for(i=1;i<=10;i++) entries[$i]=0 for(f=0;<=NF;f++) entries[$f]=1' testfile.txt
</code>```

答:
perl:</p>

```<code>perl -lanE '
        push @{$idx{$F[1]}}, $F[0] - 1;  # subtract 1 because we are working with
                                          # (zero-based) array indices
        $max = $F[0];     # I assume the input is sorted by column 1
    } END {
        $, = "\n";
        for $word (keys %idx) {
            # create a $max-sized array filled with zeroes
            @a = (0) x $max;
            # then, populate the entries which should be 1
            @a[ @{$idx{$word}} ] = (1) x @{$idx{$word}};

            say $word, @a;
        }
' file |  pr -2T -s | nl -v0
</code>```

```<code> 0  thing   some
 1  0       0
 2  0       1
 3  0       0
 4  0       0
 5  0       1
 6  0       0
 7  0       0
 8  0       1
 9  0       0
10  1       0
11  0       0
12  0       0
13  0       0
14  0       0
15  1       0
16  0       0
17  0       0
18  0       0
19  1       0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following file:

2    some
5    some
8    some
10   thing
15   thing
19   thing

Now I want to end up with entries, where for "some" 2,5,8 correspond to rows where there is a 1, everything else is 0. It doesn't matter how many rows there are. This means for "some":

0
1
0
0
1
0
0
1
0
0

and for "thing"

0
0
0
0
0
0
0
0
0
1
0
0
0
0
1
0
0
0
1
0

Is this possible in a quick way with awk? I mean with something like:

awk '{for(i=1;i<=10;i++) entries[$i]=0 for(f=0;<=NF;f++) entries[$f]=1' testfile.txt

Body:
perl:

perl -lanE '
        push @{$idx{$F[1]}}, $F[0] - 1;  # subtract 1 because we are working with
                                          # (zero-based) array indices
        $max = $F[0];     # I assume the input is sorted by column 1
    } END {
        $, = "\n";
        for $word (keys %idx) {
            # create a $max-sized array filled with zeroes
            @a = (0) x $max;
            # then, populate the entries which should be 1
            @a[ @{$idx{$word}} ] = (1) x @{$idx{$word}};

            say $word, @a;
        }
' file |  pr -2T -s | nl -v0

 0  thing   some
 1  0       0
 2  0       1
 3  0       0
 4  0       0
 5  0       1
 6  0       0
 7  0       0
 8  0       1
 9  0       0
10  1       0
11  0       0
12  0       0
13  0       0
14  0       0
15  1       0
16  0       0
17  0       0
18  0       0
19  1       0


问:
Split table row into two fields and count each
So far I have wrote the following query:

```<code>SELECT forum_topics.*, users.id as userid, users.username, users.avatar, forum_categories.name as cat_name
FROM forum_topics
INNER JOIN users
ON users.id = forum_topics.author_id
INNER JOIN forum_categories
ON forum_categories.id = forum_topics.category_id
WHERE forum_topics.id = 64
</code>```

But I also want to add another table votes that has the following structure:

```<code>___________________________________________________________
| id | object_type | object_id | receiver | giver | type    |
___________________________________________________________
| 128| topic       |     64    |    21    |  22   | like    |
| 129| topic_reply |     55    |    21    |  22   | dislike |
___________________________________________________________
</code>```

Basically the relation between the two tables is forum_topics.id from Table 1 and  object_id from Table 2 (the bottom one). This is for a forum and I want to display likes/dislikes for each topic and reply. type could be like and dislike. receiver is the user that made the post, giver is the user that voted. I want to INNER JOIN the votes table in the first query and count all likes and dislikes into two separate fields. Something like:

Select votes.count(*) as likes WHERE type = 'like and votes.count(*) as dislikes WHERE type = 'dislike'
The query got so complicated and I am so confused.

Edit: So I figured it out for forum_topics. Here is how I did it:

```<code>    SELECT forum_topics.*, users.id as userid, users.username, users.avatar, forum_categories.name as cat_name,
   count(CASE WHEN votes.type = 'like'    AND votes.object_type = 'topic'  then 1 else null end) as votes_likes,
   count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic'  then 1 else null end) as votes_dislikes
FROM forum_topics
INNER JOIN users
ON users.id = forum_topics.author_id
INNER JOIN forum_categories
ON forum_categories.id = forum_topics.category_id
INNER JOIN votes
ON votes.object_id = forum_topics.id
WHERE forum_topics.id = ?
</code>```

Now for forum_posts It is not working..

```<code>SELECT forum_posts.*, users.id as userid, users.username, users.avatar,
      count(CASE WHEN votes.type = 'like'    AND votes.object_type = 'topic_post' then 1 else null end) as votes_likes,
      count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic_post' then 1 else null end) as votes_dislikes
  FROM forum_posts
  INNER JOIN users
  ON users.id = forum_posts.author_id
  LEFT JOIN votes
  ON votes.object_id = forum_posts.id
  WHERE forum_posts.topic_id = 64
  ORDER BY forum_posts.id
</code>```

Any ideas how to fix it? In HeidiSQL it returns one row with everything NULL.

答:
try using group by;</p>

```<code>SELECT type, COUNT(*)
FROM votes
GROUP BY type;
</code>```

Body:
So far I have wrote the following query:

SELECT forum_topics.*, users.id as userid, users.username, users.avatar, forum_categories.name as cat_name
FROM forum_topics
INNER JOIN users
ON users.id = forum_topics.author_id
INNER JOIN forum_categories
ON forum_categories.id = forum_topics.category_id
WHERE forum_topics.id = 64

But I also want to add another table votes that has the following structure:

___________________________________________________________
| id | object_type | object_id | receiver | giver | type    |
___________________________________________________________
| 128| topic       |     64    |    21    |  22   | like    |
| 129| topic_reply |     55    |    21    |  22   | dislike |
___________________________________________________________

Basically the relation between the two tables is forum_topics.id from Table 1 and  object_id from Table 2 (the bottom one). This is for a forum and I want to display likes/dislikes for each topic and reply. type could be like and dislike. receiver is the user that made the post, giver is the user that voted. I want to INNER JOIN the votes table in the first query and count all likes and dislikes into two separate fields. Something like:

Select votes.count(*) as likes WHERE type = 'like and votes.count(*) as dislikes WHERE type = 'dislike'
The query got so complicated and I am so confused.

Edit: So I figured it out for forum_topics. Here is how I did it:

    SELECT forum_topics.*, users.id as userid, users.username, users.avatar, forum_categories.name as cat_name,
   count(CASE WHEN votes.type = 'like'    AND votes.object_type = 'topic'  then 1 else null end) as votes_likes,
   count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic'  then 1 else null end) as votes_dislikes
FROM forum_topics
INNER JOIN users
ON users.id = forum_topics.author_id
INNER JOIN forum_categories
ON forum_categories.id = forum_topics.category_id
INNER JOIN votes
ON votes.object_id = forum_topics.id
WHERE forum_topics.id = ?

Now for forum_posts It is not working..

SELECT forum_posts.*, users.id as userid, users.username, users.avatar,
      count(CASE WHEN votes.type = 'like'    AND votes.object_type = 'topic_post' then 1 else null end) as votes_likes,
      count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic_post' then 1 else null end) as votes_dislikes
  FROM forum_posts
  INNER JOIN users
  ON users.id = forum_posts.author_id
  LEFT JOIN votes
  ON votes.object_id = forum_posts.id
  WHERE forum_posts.topic_id = 64
  ORDER BY forum_posts.id

Any ideas how to fix it? In HeidiSQL it returns one row with everything NULL.

Body:
try using group by;

SELECT type, COUNT(*)
FROM votes
GROUP BY type;


问:
How to merge 3 queries into one recordset
I need to export to excel summary stats from three access SQL queries, as shown below. These are being programmed in vba:

```<code>strSQL2 = "SELECT * FROM qry_pp_prev2;"
strSQL3 = "SELECT * FROM qry_pp_prev3;"
strSQL4 = "SELECT * FROM qry_pp_prev4;"

'trying to merge the 3 queries above
Set db = CurrentDb()
Set rs = db.OpenRecordset(strSQL2)
Set rs1 = db.OpenRecordset(strSQL3)
Set rs2 = db.OpenRecordset(strSQL4)

'to create excel template
Set objXL = CreateObject("Excel.Application")
Set objWB = objXL.Workbooks.Add()
Set objWS = objWB.Worksheets("Sheet1")

With objWS
.cells(1, 1).Value = "X reporting tool"
.cells(2, 1).Value = "District"
.cells(2, 2).Value = Me!subd
 .......
</code>```

Problem in putting all queries in one file access says it's too complex and thus doesn't give output. However when i use the above to merge the SQL queries and have them all export the data into a template created from access vba as above the results are not accurate.

Currently the results are blank in most of the template created, with some values on some parts of the excel template?

hope this makes sense?

答:
Not an answer, just a large comment

If all queries return the same amount of columns, you can easily do this:

```<code>strSQL_union = "SELECT * FROM qry_pp_prev2  UNION ALL"
strSQL_union = strSQL_union + " SELECT * FROM qry_pp_prev3 UNION ALL"
strSQL_union = strSQL_union + " SELECT * FROM qry_pp_prev4;"
</code>```

You will end with just one resulset.

Body:
I need to export to excel summary stats from three access SQL queries, as shown below. These are being programmed in vba:

strSQL2 = "SELECT * FROM qry_pp_prev2;"
strSQL3 = "SELECT * FROM qry_pp_prev3;"
strSQL4 = "SELECT * FROM qry_pp_prev4;"

'trying to merge the 3 queries above
Set db = CurrentDb()
Set rs = db.OpenRecordset(strSQL2)
Set rs1 = db.OpenRecordset(strSQL3)
Set rs2 = db.OpenRecordset(strSQL4)

'to create excel template
Set objXL = CreateObject("Excel.Application")
Set objWB = objXL.Workbooks.Add()
Set objWS = objWB.Worksheets("Sheet1")

With objWS
.cells(1, 1).Value = "X reporting tool"
.cells(2, 1).Value = "District"
.cells(2, 2).Value = Me!subd
 .......

Problem in putting all queries in one file access says it's too complex and thus doesn't give output. However when i use the above to merge the SQL queries and have them all export the data into a template created from access vba as above the results are not accurate.

Currently the results are blank in most of the template created, with some values on some parts of the excel template?

hope this makes sense?

Body:
Not an answer, just a large comment

If all queries return the same amount of columns, you can easily do this:

strSQL_union = "SELECT * FROM qry_pp_prev2  UNION ALL"
strSQL_union = strSQL_union + " SELECT * FROM qry_pp_prev3 UNION ALL"
strSQL_union = strSQL_union + " SELECT * FROM qry_pp_prev4;"

You will end with just one resulset.


问:
Java - Restricting by what a method can be called
I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:

```<code>if(trace.length<2){
    throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
    throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}
</code>```

Is there something else I should be doing, or should I just not forget how my program works?

答:
This seems like a very brittle solution to a problem you should not need to solve.

In this particular case you may not suffer too greatly in future maintenance, just a couple of methods with these kind of special guards. But imagine trying to apply such logic to many methods across a large code base - it's just not a tenable thing to do. Even in your case you are effectivley writing code that cannot be reused in other contexts.

The fact that you need to do this surely reflects some kind of mis-design.

I infer that you have some kind of stateful interface whose state gets fouled up if called unexpectedly. Ideally I would want to make the interface more robust, but if that just cannot be done: If there are particular methods that should use this interface can you move those methods to a specific class - maybe an inner class of the current objtec you have - and have a handle visible only in this class?

```<code> private Class TheLegalCaller {
      private RestrictedCallee myCallee = new RestricatedCallee() ; // or other creation
      public void doOneThing() { myCallee.doOne(); }
      public void doOtherThing() } myCallee.doOther(); }
 }
</code>```

Now the downside with this is that it only pushes the problem up a level, if you randomly use TheLegalCaller in the wrong places then I guess you still have an issue. But maybe by making the restriction very visible it aids your memory?

Body:
I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:

if(trace.length<2){
    throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
    throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}

Is there something else I should be doing, or should I just not forget how my program works?

Body:
This seems like a very brittle solution to a problem you should not need to solve.

In this particular case you may not suffer too greatly in future maintenance, just a couple of methods with these kind of special guards. But imagine trying to apply such logic to many methods across a large code base - it's just not a tenable thing to do. Even in your case you are effectivley writing code that cannot be reused in other contexts.

The fact that you need to do this surely reflects some kind of mis-design.

I infer that you have some kind of stateful interface whose state gets fouled up if called unexpectedly. Ideally I would want to make the interface more robust, but if that just cannot be done: If there are particular methods that should use this interface can you move those methods to a specific class - maybe an inner class of the current objtec you have - and have a handle visible only in this class?

 private Class TheLegalCaller {
      private RestrictedCallee myCallee = new RestricatedCallee() ; // or other creation
      public void doOneThing() { myCallee.doOne(); }
      public void doOtherThing() } myCallee.doOther(); }
 }

Now the downside with this is that it only pushes the problem up a level, if you randomly use TheLegalCaller in the wrong places then I guess you still have an issue. But maybe by making the restriction very visible it aids your memory?


问:
What is the purpose of '_' in macro
I am trying to understand one of the VPP sample function name 'sample_plugin_api_hookup'. What is the purpose of underscore ('_' ) in macro (#define _(N,n) ) ?

```<code>   #define _(N,n)                                                  \
        vl_msg_api_set_handlers((VL_API_##N + sm->msg_id_base),     \
                               #n,          \
                               vl_api_##n##_t_handler,              \
                               vl_noop_handler,                     \
                               vl_api_##n##_t_endian,               \
                               vl_api_##n##_t_print,                \
                               sizeof(vl_api_##n##_t), 1);
        foreach_sample_plugin_api_msg;
    #undef _
</code>```

答:
_ is a valid C identifier, though it's reserved for use at file scope. A C identifier consists of a letter or underscore, followed by zero or more letters, underscores, or digits (I'm ignoring universal character names).

Apparently the author of that code wanted a name that's short, easy to type, and unobtrusive. I believe the GNU gettext package, or code that uses it, follows this convention, with a macro call like

```<code> _("This is a message")
</code>```

being replaced by a localized version of the message. (Which means that a program that uses GNU gettext likely would have to pick a different name).

foreach_sample_plugin_api_msg is another macro that makes use of the _ macro, which is why the _ macro is undefined immediately after that line.

Perhaps the author was influenced by the Go language, which uses _ as a blank identifier.

Opinions are likely to differ on the question of whether this is a neat trick or a crime against good taste.

Title: What is the purpose of '_' in macro

Body:
I am trying to understand one of the VPP sample function name 'sample_plugin_api_hookup'. What is the purpose of underscore ('_' ) in macro (#define _(N,n) ) ?

   #define _(N,n)                                                  \
        vl_msg_api_set_handlers((VL_API_##N + sm->msg_id_base),     \
                               #n,          \
                               vl_api_##n##_t_handler,              \
                               vl_noop_handler,                     \
                               vl_api_##n##_t_endian,               \
                               vl_api_##n##_t_print,                \
                               sizeof(vl_api_##n##_t), 1);
        foreach_sample_plugin_api_msg;
    #undef _

Body:
_ is a valid C identifier, though it's reserved for use at file scope. A C identifier consists of a letter or underscore, followed by zero or more letters, underscores, or digits (I'm ignoring universal character names).

Apparently the author of that code wanted a name that's short, easy to type, and unobtrusive. I believe the GNU gettext package, or code that uses it, follows this convention, with a macro call like

 _("This is a message")

being replaced by a localized version of the message. (Which means that a program that uses GNU gettext likely would have to pick a different name).

foreach_sample_plugin_api_msg is another macro that makes use of the _ macro, which is why the _ macro is undefined immediately after that line.

Perhaps the author was influenced by the Go language, which uses _ as a blank identifier.

Opinions are likely to differ on the question of whether this is a neat trick or a crime against good taste.


问:
What is this Rspec syntax exactly asking for?
TL;DR I am going to a bootcamp next year and one their assessments to get in is learning ruby. I have a background in JS and am very new to ruby. I have this assessment in which case I am not familiar with what the test wants me to do. Below is the test case(Rspec) and right below that is my answer.

```<code>describe "some silly block functions" do
  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end

  expect(result).to eq("olleh")
end

it "reverses each word in the string returned by the default block" do
  result = reverser do
    "hello dolly"
  end

  expect(result).to eq("olleh yllod")
  end
end
</code>```

This is my answer code:

```<code>def reverser sentence
  words = sentence.split(" ")
  result = []

  words.length.times do |i|
    result.push(yield(words[i]))
  end

  result.join(" ")
end

reverser("hello dolly") {|n| n.reverse} #=> 'olleh yllod'
</code>```

As I mentioned above I am new to ruby and the idea of yielding is like a callback function for JS. I am having a hard time figuring out what expected code the test case wants me to write. It says that 'it reverses each word in the string returned by the default block' from the statement I just created a block outside of the function where the words are being reversed. I appreciate the help and guidance from whoever can give advice.

答:
This is really more about TDD than about Ruby. The approach would be much the same in any other language as well.

The point of TDD is to write the simplest test that could possibly fail, and then write the simplest code that could possibly change the error message. Step #1 is already provided to you in this example, so this is really about step #2: write the simplest code that could possibly change the message.

Let's run the tests! The message says:

```<code> NoMethodError:
   undefined method `reverser' …
</code>```

What's the simplest code that could possibly change a message that says a method doesn't exist? Well, make the method exist, of course!

```<code>def reverser; end
</code>```

Now, the message is:

```<code>expected: "olleh"
     got: nil
</code>```

Okay, so it expected us to return the string 'olleh', but we actually returned nil. That's easy:

```<code>def reverser; 'olleh' end
</code>```

Great! The first test passes. But the second still fails. It says:

```<code>expected: "olleh yllod"
     got: "olleh"
</code>```

Hmm … apparently, it is not enough to just return something statically. We have to return something different every time. The obvious source would be an argument, but our method doesn't have any parameters. Or does it? Yes! In Ruby, all methods have an implicit block parameter! You can evaluate it using the yield keyword, so let's try that:

```<code>def reverser; yield end
</code>```

Damn! We're back to two errors! That was a step backwards. Or was it? Let's look at the first error message:

```<code>expected: "olleh"
     got: "hello"
</code>```

Do you notice something? The expected value is exactly the reverse of the value we are currently returning. So, all we need to do is reverse the return value:

```<code>def reverser; yield.reverse end
</code>```

Hooray! We're back to 1 error:

```<code>expected: "olleh yllod"
     got: "yllod olleh"
</code>```

Again, can you spot what is happening? The order of the words is reversed! We need to separate the words and then reverse them, then put them back together:

```<code>def reverser; yield.reverse.split.reverse.join end
</code>```

So close!

```<code>expected: "olleh yllod"
     got: "ollehyllod"
</code>```

We just need to put the space back in:

```<code>def reverser; yield.reverse.split.reverse.join(' ') end
</code>```

Yippieh!

```<code>2 examples, 0 failures
</code>```

The important thing is: at no point did we actually have to think. Every step of the way, the tests told us what to do, what to do next, and when we were done. That's what TDD is about: the tests drive the development.

Body:
TL;DR I am going to a bootcamp next year and one their assessments to get in is learning ruby. I have a background in JS and am very new to ruby. I have this assessment in which case I am not familiar with what the test wants me to do. Below is the test case(Rspec) and right below that is my answer.

describe "some silly block functions" do
  describe "reverser" do
    it "reverses the string returned by the default block" do
      result = reverser do
        "hello"
      end

  expect(result).to eq("olleh")
end

it "reverses each word in the string returned by the default block" do
  result = reverser do
    "hello dolly"
  end

  expect(result).to eq("olleh yllod")
  end
end

This is my answer code:

def reverser sentence
  words = sentence.split(" ")
  result = []

  words.length.times do |i|
    result.push(yield(words[i]))
  end

  result.join(" ")
end

reverser("hello dolly") {|n| n.reverse} #=> 'olleh yllod'

As I mentioned above I am new to ruby and the idea of yielding is like a callback function for JS. I am having a hard time figuring out what expected code the test case wants me to write. It says that 'it reverses each word in the string returned by the default block' from the statement I just created a block outside of the function where the words are being reversed. I appreciate the help and guidance from whoever can give advice.

Body:
This is really more about TDD than about Ruby. The approach would be much the same in any other language as well.

The point of TDD is to write the simplest test that could possibly fail, and then write the simplest code that could possibly change the error message. Step #1 is already provided to you in this example, so this is really about step #2: write the simplest code that could possibly change the message.

Let's run the tests! The message says:

 NoMethodError:
   undefined method `reverser' …

What's the simplest code that could possibly change a message that says a method doesn't exist? Well, make the method exist, of course!

def reverser; end

Now, the message is:

expected: "olleh"
     got: nil

Okay, so it expected us to return the string 'olleh', but we actually returned nil. That's easy:

def reverser; 'olleh' end

Great! The first test passes. But the second still fails. It says:

expected: "olleh yllod"
     got: "olleh"

Hmm … apparently, it is not enough to just return something statically. We have to return something different every time. The obvious source would be an argument, but our method doesn't have any parameters. Or does it? Yes! In Ruby, all methods have an implicit block parameter! You can evaluate it using the yield keyword, so let's try that:

def reverser; yield end

Damn! We're back to two errors! That was a step backwards. Or was it? Let's look at the first error message:

expected: "olleh"
     got: "hello"

Do you notice something? The expected value is exactly the reverse of the value we are currently returning. So, all we need to do is reverse the return value:

def reverser; yield.reverse end

Hooray! We're back to 1 error:

expected: "olleh yllod"
     got: "yllod olleh"

Again, can you spot what is happening? The order of the words is reversed! We need to separate the words and then reverse them, then put them back together:

def reverser; yield.reverse.split.reverse.join end

So close!

expected: "olleh yllod"
     got: "ollehyllod"

We just need to put the space back in:

def reverser; yield.reverse.split.reverse.join(' ') end

Yippieh!

2 examples, 0 failures

The important thing is: at no point did we actually have to think. Every step of the way, the tests told us what to do, what to do next, and when we were done. That's what TDD is about: the tests drive the development.


问:
Distinct Values using Set
I have been using

```<code>      <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
      </FormGroup>
</code>```

to get a unique array for a dropdown option, however I now need to pass an array with each object in it having a label and a value.

I have refactored the code as follows,

```<code>   <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => {
            return {value: options.campaign, label: options.campaign };
          }))]}/>
      </FormGroup>
</code>```

...but the unique element is now not working (see below with duplicates). What am I doing wrong please?

The input array looks like...

```<code>    [
    1. 0:{_id: "zWTiLEjqrCKdxTvze", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "newevent", …}
    2. 1:{_id: "SkZzDMAWokFFYEycp", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "instagramlaunch", …}
    3. 2:{_id: "p4pychanC5Zw8iWAQ", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "stuffinhere", …}
       … more in here including more than 1 object with instagram launch for example
    ]
</code>```

Original approach resulted in Array of...

```<code>    0:"newevent"
    1:"sheffieldevent"
    2:"stuffinhere"
    3:”instagramlaunch"
    4:”anothertest"
    5:”yetanother"
</code>```

now results in...

```<code>    0:{value: "newevent", label: "newevent"}
    1:{value: "sheffieldevent", label: "sheffieldevent"}
    2:{value: "stuffinhere", label: "stuffinhere"}
    3:{value: "instagramlaunch", label: "instagramlaunch"}
    4:{value: "instagramlaunch", label: "instagramlaunch"}
    5:{value: "instagramlaunch", label: "instagramlaunch”}
    6:{value: "anothertest", label: "anothertest”}
    7:{value: "yetanother", label: "yetanother"}
</code>```

答:
I resolved this using lodash...</p>

```<code>    campaignOptions={_.uniqBy(this.props.records.map((options,index) => {return { value: index, label: options.campaign }}),'label')}/>
</code>```

Title: Distinct Values using Set

Body:
I have been using

      <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
      </FormGroup>

to get a unique array for a dropdown option, however I now need to pass an array with each object in it having a label and a value.

I have refactored the code as follows,

   <FormGroup>
        <Campaign
          campaignName={this.campaignName.bind(this)}
          campaignOptions={[...new Set(this.props.records.map(options => {
            return {value: options.campaign, label: options.campaign };
          }))]}/>
      </FormGroup>

...but the unique element is now not working (see below with duplicates). What am I doing wrong please?

The input array looks like...

    [
    1. 0:{_id: "zWTiLEjqrCKdxTvze", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "newevent", …}
    2. 1:{_id: "SkZzDMAWokFFYEycp", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "instagramlaunch", …}
    3. 2:{_id: "p4pychanC5Zw8iWAQ", owner: "K7xTxu7PRDCuhFZRC", company_ID: "1", campaign: "stuffinhere", …}
       … more in here including more than 1 object with instagram launch for example
    ]

Original approach resulted in Array of...

    0:"newevent"
    1:"sheffieldevent"
    2:"stuffinhere"
    3:”instagramlaunch"
    4:”anothertest"
    5:”yetanother"

now results in...

    0:{value: "newevent", label: "newevent"}
    1:{value: "sheffieldevent", label: "sheffieldevent"}
    2:{value: "stuffinhere", label: "stuffinhere"}
    3:{value: "instagramlaunch", label: "instagramlaunch"}
    4:{value: "instagramlaunch", label: "instagramlaunch"}
    5:{value: "instagramlaunch", label: "instagramlaunch”}
    6:{value: "anothertest", label: "anothertest”}
    7:{value: "yetanother", label: "yetanother"}

Body:
I resolved this using lodash...

    campaignOptions={_.uniqBy(this.props.records.map((options,index) => {return { value: index, label: options.campaign }}),'label')}/>


问:
Xamarin: Obsolete Forms.Context and AlertDialog.Builder
I used to create it like this

```<code>        AlertDialog.Builder b = new AlertDialog.Builder( Forms.Context );
</code>```

And it worked fine. But Forms.Context is obsolete now so I changed it to

```<code>        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context );
</code>```

Now it crashes with

```<code>Android.Content.Res.Resources+NotFoundException: Resource ID #0x0
</code>```

I tried the alternative constructor

```<code>        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context, Resource.Style.Theme_AppCompat_Light );
</code>```

And that crashes with

```<code>Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application
</code>```

So what context do I pass to AlertDialog.Builder() in XF2.5? I don't feel like installing a 3rd party library for this.

答:
One way is to create a static variable in Main Activity like this

```<code>public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    internal static MainActivity Instance { get; private set; }

    protected override void OnCreate(Bundle bundle)
    {
        ...
        global::Xamarin.Forms.Forms.Init(this, bundle);
        Instance = this;
        LoadApplication(new App());
    }
}
</code>```

The reference it in your code like this

```<code>AlertDialog.Builder b = new AlertDialog.Builder( MainActivity.Instance );
</code>```

For more details and other ways to achieve this, see David Britchs blog post

Body:
I used to create it like this

        AlertDialog.Builder b = new AlertDialog.Builder( Forms.Context );

And it worked fine. But Forms.Context is obsolete now so I changed it to

        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context );

Now it crashes with

Android.Content.Res.Resources+NotFoundException: Resource ID #0x0

I tried the alternative constructor

        AlertDialog.Builder b = new AlertDialog.Builder( Android.App.Application.Context, Resource.Style.Theme_AppCompat_Light );

And that crashes with

Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application

So what context do I pass to AlertDialog.Builder() in XF2.5? I don't feel like installing a 3rd party library for this.

Body:
One way is to create a static variable in Main Activity like this

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    internal static MainActivity Instance { get; private set; }

    protected override void OnCreate(Bundle bundle)
    {
        ...
        global::Xamarin.Forms.Forms.Init(this, bundle);
        Instance = this;
        LoadApplication(new App());
    }
}

The reference it in your code like this

AlertDialog.Builder b = new AlertDialog.Builder( MainActivity.Instance );

For more details and other ways to achieve this, see David Britchs blog post


问:
Get index of array element as Int
I have an array of UIViewController in my protocol

```<code>var viewControllers: [MyViewController] { get }
</code>```

I want to get the index of item with specific ViewController

```<code>let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController)
</code>```

But the type of idfx is Array.index.

How can I get the index of an array element as an Int?

答:
The problem isn't that it's of type Array.index, which is a typealias for Int, as Nonuld says. The problem is that it's an optional. You need to unwrap the optional somehow. One way is to use "if let" optional binding:

```<code>if let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController) {
  print("view controller found at index \(idfx)")
} else {
  print("View controller not found in array")
}
</code>```

Title: Get index of array element as Int

Body:
I have an array of UIViewController in my protocol

var viewControllers: [MyViewController] { get }

I want to get the index of item with specific ViewController

let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController)

But the type of idfx is Array.index.

How can I get the index of an array element as an Int?

Body:
The problem isn't that it's of type Array.index, which is a typealias for Int, as Nonuld says. The problem is that it's an optional. You need to unwrap the optional somehow. One way is to use "if let" optional binding:

if let idfx = viewModel.viewControllers.index(of: viewController as! MyViewController) {
  print("view controller found at index \(idfx)")
} else {
  print("View controller not found in array")
}


问:
Speed up the calculation of proportion of most frequent digits in a string, in R
I need help with speeding up a function to compute the proportion repeating digits (ignoring any non-digit). The function helps identify fake entries from a user, before running any check-digit verification (if such is even available). Think fake phone number, fake student number, fake checking account number, fake credit card number, fake any identifier, and so on.

The function is a generalization from this post.

Here is what it does. For the specified number of most frequently appearing digits, it computes the proportion of top digits to all digits in a string, ignoring all non-digits. If there are no digits in a string, it returns 1.0. All calculations are done on a vector of strings.

```<code>library(microbenchmark)
V = c('(12) 1221-12121,one-twoooooooooo', 'twos:22-222222222', '34-11111111, ext.123',
        '01012', '123-456-789 valid', 'no digits', '', NaN, NA)

Fake_Similarity = function(V, TopNDigits) {
    vapply(V, function(v) {
        freq = sort(tabulate(as.integer(charToRaw(v)))[48:57], decreasing = T);
        ratio = sum(freq[1:TopNDigits], na.rm = T) / sum(freq, na.rm = T)
        if (is.nan(ratio)) ratio = 1
        ratio
    },
    double(1))
}

t(rbind(Top1Digit = Fake_Similarity(v, 1), Top2Digits = Fake_Similarity(v, 2), Top3Digits = Fake_Similarity(v, 3)))

microbenchmark(Fake_Similarity(v, 2))
</code>```

with the output. The labels are not important, but the order ratios must match the original order of corresponding strings.

```<code>                                 Top1Digit Top2Digits Top3Digits
(12) 1221-12121,one-twoooooooooo 0.5454545  1.0000000  1.0000000
twos:22-222222222                1.0000000  1.0000000  1.0000000
34-11111111, ext.123             0.6923077  0.8461538  0.9230769
01012                            0.4000000  0.8000000  1.0000000
123-456-789 valid                0.1111111  0.2222222  0.3333333
no digits                        1.0000000  1.0000000  1.0000000
                                 1.0000000  1.0000000  1.0000000
NaN                              1.0000000  1.0000000  1.0000000
<NA>                             1.0000000  1.0000000  1.0000000
Unit: milliseconds
                  expr      min       lq     mean   median       uq      max neval
 Fake_Similarity(v, 2) 1.225418 1.283113 1.305139 1.292755 1.304262 1.769703   100
</code>```

For example, twos:22-222222222 has 11 digits and all of them are the same. So, for the Top1Digit we have 11/11=1, for the Top2Digits we have (11+0)/11=1 again, and so on. In other words, this is a fake number by any measure. It is highly unlikely for, let's say, a person's phone number to have identical digits, including the area code.

答:
This probably won't compete with the RCPP solution, but I think it makes good efficiency gains. The point of this implementation is to not run the algorithm for each N, rather to run it for all Ns at once. This means we only have to do charToRaw once per string, instead of once per N per string, and similarly the sorting, tabulating, etc. Then we can use optimized functions cumsum and colSums to calculate all frequencies at once.

```<code>library(matrixStats)
Fake_Similarity3 = function(V, N) {
    freq = vapply(V, function(v) {
        s = sort(tabulate(as.integer(charToRaw(v)))[48:57], decreasing = T)
        length(s) = 10
        return(s)
    }, FUN.VALUE = integer(10), USE.NAMES = FALSE)
    cumfreq = colCumsums(freq)
    ratio = t(cumfreq) / (colSums(freq, na.rm = T))
    ratio[!is.finite(ratio) | ratio == 0] = 1
  return(ratio[, N, drop = FALSE])
}
</code>```

With this function, instead of calling with arguments (V, 1), (V, 2), and (V, 3), we would just call (V, 1:3)

```<code> #           [,1]      [,2]      [,3]
 # [1,] 0.5454545 1.0000000 1.0000000
 # [2,] 1.0000000 1.0000000 1.0000000
 # [3,] 0.6923077 0.8461538 0.9230769
 # [4,] 0.4000000 0.8000000 1.0000000
 # [5,] 0.1111111 0.2222222 0.3333333
 # [6,] 1.0000000 1.0000000 1.0000000
 # [7,] 1.0000000 1.0000000 1.0000000
 # [8,] 1.0000000 1.0000000 1.0000000
 # [9,] 1.0000000 1.0000000 1.0000000

microbenchmark::microbenchmark(
    FS1 = t(rbind(Top1Digit = Fake_Similarity(V, 1), Top2Digits = Fake_Similarity(V, 2), Top3Digits = Fake_Similarity(V, 3))),
    FS3 = Fake_Similarity3(V, 1:3)
)

# Unit: microseconds
#  expr     min      lq     mean   median        uq      max neval cld
#   FS1 896.336 958.490 1103.260 1011.800 1145.0125 2494.136   100   b
#   FS3 311.798 336.853  399.983  358.979  408.0855  886.013   100  a
</code>```

So, it's about 3x faster than the original for top 1, 2, and 3 digits. The more top digits used, the better this will do relative to the original.

Body:
I need help with speeding up a function to compute the proportion repeating digits (ignoring any non-digit). The function helps identify fake entries from a user, before running any check-digit verification (if such is even available). Think fake phone number, fake student number, fake checking account number, fake credit card number, fake any identifier, and so on.

The function is a generalization from this post.

Here is what it does. For the specified number of most frequently appearing digits, it computes the proportion of top digits to all digits in a string, ignoring all non-digits. If there are no digits in a string, it returns 1.0. All calculations are done on a vector of strings.

library(microbenchmark)
V = c('(12) 1221-12121,one-twoooooooooo', 'twos:22-222222222', '34-11111111, ext.123',
        '01012', '123-456-789 valid', 'no digits', '', NaN, NA)

Fake_Similarity = function(V, TopNDigits) {
    vapply(V, function(v) {
        freq = sort(tabulate(as.integer(charToRaw(v)))[48:57], decreasing = T);
        ratio = sum(freq[1:TopNDigits], na.rm = T) / sum(freq, na.rm = T)
        if (is.nan(ratio)) ratio = 1
        ratio
    },
    double(1))
}

t(rbind(Top1Digit = Fake_Similarity(v, 1), Top2Digits = Fake_Similarity(v, 2), Top3Digits = Fake_Similarity(v, 3)))

microbenchmark(Fake_Similarity(v, 2))

with the output. The labels are not important, but the order ratios must match the original order of corresponding strings.

                                 Top1Digit Top2Digits Top3Digits
(12) 1221-12121,one-twoooooooooo 0.5454545  1.0000000  1.0000000
twos:22-222222222                1.0000000  1.0000000  1.0000000
34-11111111, ext.123             0.6923077  0.8461538  0.9230769
01012                            0.4000000  0.8000000  1.0000000
123-456-789 valid                0.1111111  0.2222222  0.3333333
no digits                        1.0000000  1.0000000  1.0000000
                                 1.0000000  1.0000000  1.0000000
NaN                              1.0000000  1.0000000  1.0000000
<NA>                             1.0000000  1.0000000  1.0000000
Unit: milliseconds
                  expr      min       lq     mean   median       uq      max neval
 Fake_Similarity(v, 2) 1.225418 1.283113 1.305139 1.292755 1.304262 1.769703   100

For example, twos:22-222222222 has 11 digits and all of them are the same. So, for the Top1Digit we have 11/11=1, for the Top2Digits we have (11+0)/11=1 again, and so on. In other words, this is a fake number by any measure. It is highly unlikely for, let's say, a person's phone number to have identical digits, including the area code.

Body:
This probably won't compete with the RCPP solution, but I think it makes good efficiency gains. The point of this implementation is to not run the algorithm for each N, rather to run it for all Ns at once. This means we only have to do charToRaw once per string, instead of once per N per string, and similarly the sorting, tabulating, etc. Then we can use optimized functions cumsum and colSums to calculate all frequencies at once.

library(matrixStats)
Fake_Similarity3 = function(V, N) {
    freq = vapply(V, function(v) {
        s = sort(tabulate(as.integer(charToRaw(v)))[48:57], decreasing = T)
        length(s) = 10
        return(s)
    }, FUN.VALUE = integer(10), USE.NAMES = FALSE)
    cumfreq = colCumsums(freq)
    ratio = t(cumfreq) / (colSums(freq, na.rm = T))
    ratio[!is.finite(ratio) | ratio == 0] = 1
  return(ratio[, N, drop = FALSE])
}

With this function, instead of calling with arguments (V, 1), (V, 2), and (V, 3), we would just call (V, 1:3)

 #           [,1]      [,2]      [,3]
 # [1,] 0.5454545 1.0000000 1.0000000
 # [2,] 1.0000000 1.0000000 1.0000000
 # [3,] 0.6923077 0.8461538 0.9230769
 # [4,] 0.4000000 0.8000000 1.0000000
 # [5,] 0.1111111 0.2222222 0.3333333
 # [6,] 1.0000000 1.0000000 1.0000000
 # [7,] 1.0000000 1.0000000 1.0000000
 # [8,] 1.0000000 1.0000000 1.0000000
 # [9,] 1.0000000 1.0000000 1.0000000

microbenchmark::microbenchmark(
    FS1 = t(rbind(Top1Digit = Fake_Similarity(V, 1), Top2Digits = Fake_Similarity(V, 2), Top3Digits = Fake_Similarity(V, 3))),
    FS3 = Fake_Similarity3(V, 1:3)
)

# Unit: microseconds
#  expr     min      lq     mean   median        uq      max neval cld
#   FS1 896.336 958.490 1103.260 1011.800 1145.0125 2494.136   100   b
#   FS3 311.798 336.853  399.983  358.979  408.0855  886.013   100  a

So, it's about 3x faster than the original for top 1, 2, and 3 digits. The more top digits used, the better this will do relative to the original.


问:
Java Lab - Counting Runs
Langauge: Java

No syntax errors and passed the compiler but failed my tester. Anyone can tell me what I did wrong here?

Here's what the lab text states for what the method is to do:
"counts how many runs (consecutive blocks of equal elements) there are in the subarray of arr from index start to index end , inclusive"

Also: I'm not allowed to use any loops for this lab, if-else statements are okay though.

parameters: arr = array, start/end = indices for start/end

```<code>public class Recursion {
    int countRuns(int[] arr, int start, int end) {
        if (start >= end)
            return 0; //checks for null arrays

        int counter = 0;
        if (start == 0)
            counter = 1;

        //check the next element for similarity/difference
        if (arr[start] != arr[start+1])
            counter = 1;

        return counter + countRuns(arr, start + 1, end);
    }
}
</code>```

答:
I think you just slightly missed the conditions at beginning and end.. This should work:</p>

```<code>public class Recursion {
    int countRuns(int[] arr, int start, int end) {
        if (start > end)
            return 0; //checks for null arrays

        if (start == end) // the indices are inclusive
            return 1;

        int counter;
        if (arr[start] == arr[start + 1]) {
            counter = 0; // we'll still be in the same run, if they're equal
        } else {
            counter = 1; // otherwise it's a new run
        }

        return counter + countRuns(arr, start + 1, end);
    }
}
</code>```

Title: Java Lab - Counting Runs

Body:
Langauge: Java

No syntax errors and passed the compiler but failed my tester. Anyone can tell me what I did wrong here?

Here's what the lab text states for what the method is to do:
"counts how many runs (consecutive blocks of equal elements) there are in the subarray of arr from index start to index end , inclusive"

Also: I'm not allowed to use any loops for this lab, if-else statements are okay though.

parameters: arr = array, start/end = indices for start/end

public class Recursion {
    int countRuns(int[] arr, int start, int end) {
        if (start >= end)
            return 0; //checks for null arrays

        int counter = 0;
        if (start == 0)
            counter = 1;

        //check the next element for similarity/difference
        if (arr[start] != arr[start+1])
            counter = 1;

        return counter + countRuns(arr, start + 1, end);
    }
}

Body:
I think you just slightly missed the conditions at beginning and end.. This should work:

public class Recursion {
    int countRuns(int[] arr, int start, int end) {
        if (start > end)
            return 0; //checks for null arrays

        if (start == end) // the indices are inclusive
            return 1;

        int counter;
        if (arr[start] == arr[start + 1]) {
            counter = 0; // we'll still be in the same run, if they're equal
        } else {
            counter = 1; // otherwise it's a new run
        }

        return counter + countRuns(arr, start + 1, end);
    }
}


问:
Keeping images in sync with web server in iOS with regards to foto stream
Simple scenario: I like to synchronize images on my server with an iOS app. The app regularly gets a list of image resources and downloads these to the iOS photo album / creates PHAssets. The app stores both the PHAssets fresh localIdentifier and the resource url with core data. It will not download these images again. Let's say this is happening on my iPhone and on my iPad. Let's say both devices ran these synchronisation jobs and are 100% in sync with my webserver.
And here is the catch: the iOS foto stream will produce a copy of each downloaded image on the respective other device - once it had enough time to do its own syncing. I will end up with duplicates on both devices.

Is there any way to prevent this from happening?

答: I guess, it should be PHAsset's property "originalFilename". If I set this to a globally unique identifier, I can recognize files, which have already been downloaded to this device.</p>


问:
JFile Chooser throwing errors before use, only sometimes?
I create a JFile Chooser, and use .setCurrentDirectory(); to set the Directory to the root of my java project folder by passing a newFile("."); This seems to work fine sometimes, but other times it throws an error. This all happens while the program is loading, before any user input, so as far as I can tell it's completely random whether it happens or not. Here's the File Chooser related bits of my code:

```<code>public class PnlHighScores extends JPanel {

    JFileChooser fcScores = new JFileChooser();

    PnlHighScores() {

        fcScores.addChoosableFileFilter(new TxtFilter());

        //***********This seems to cause a strange error only somethimes, Right as the program is run!***********
        fcScores.setCurrentDirectory(new File("."));//http://www.rgagnon.com/javadetails/java-0370.html
    }

    class ActFileChooser implements ActionListener {

        public void actionPerformed(ActionEvent e) {//http://download.oracle.com/javase/tutorial/uiswing/examples/components/FileChooserDemoProject/src/components/FileChooserDemo.java
            int returnVal = fcScores.showOpenDialog(PnlHighScores.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                filScores = fcScores.getSelectedFile();
                sFileLocation = filScores.getAbsolutePath();//.getParent();//http://www.java-forums.org/awt-swing/29485-how-retrieve-path-filechooser.html
                //System.out.println(filScores);
                pnlScoreText.updateScoreFile(sFileLocation);
            }

        }
    }
    class TxtFilter extends javax.swing.filechooser.FileFilter {//http://www.exampledepot.com/egs/javax.swing.filechooser/Filter.html

        public boolean accept(File file) {
            String filename = file.getName();
            if (file.isDirectory()) {
                return true;
            } else {
                return filename.endsWith(".txt");
            }
        }

        public String getDescription() {
            return "*.txt";
        }
    }
}
</code>```

The exact error is:

```<code>Exception in thread "main" java.lang.IndexOutOfBoundsException: Invalid index
        at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:497)
        at sun.swing.FilePane$SortableListModel.getElementAt(FilePane.java:528)
        at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1343)
        at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1294)
        at javax.swing.plaf.basic.BasicListUI.getCellBounds(BasicListUI.java:935)
        at javax.swing.JList.getCellBounds(JList.java:1600)
        at javax.swing.JList.ensureIndexIsVisible(JList.java:1116)
        at sun.swing.FilePane.ensureIndexIsVisible(FilePane.java:1540)
        at sun.swing.FilePane.doDirectoryChanged(FilePane.java:1466)
        at sun.swing.FilePane.propertyChange(FilePane.java:1513)
        at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:339)
        at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:276)
        at java.awt.Component.firePropertyChange(Component.java:8128)
        at javax.swing.JFileChooser.setCurrentDirectory(JFileChooser.java:568)
        at Cannon.PnlSettings.<init>(PnlSettings.java:45)
        at Cannon.FraWindow.<init>(FraWindow.java:19)
        at Cannon.Main.main(Main.java:7)
Java Result: 1
</code>```

The Main class simply creates FraWindow, and FraWindow Creates PnlSetting through its constructor method. They should be irrelavent, but here's main just in case:

```<code>package Cannon;

//Creates the frame
public class Main {

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

答:
This all happens while the program is loading,

All code that affects the GUI should execute on the Event Dispatch Thread. The creation of the GUI should be wrapped in a SwingUtilities.invokeLater().

Read the section from the Swing tutorial on Concurrency for more information. And look at any of the examples that demonstrate the proper way to create the GUI.

Body:
I create a JFile Chooser, and use .setCurrentDirectory(); to set the Directory to the root of my java project folder by passing a newFile("."); This seems to work fine sometimes, but other times it throws an error. This all happens while the program is loading, before any user input, so as far as I can tell it's completely random whether it happens or not. Here's the File Chooser related bits of my code:

public class PnlHighScores extends JPanel {

    JFileChooser fcScores = new JFileChooser();

    PnlHighScores() {

        fcScores.addChoosableFileFilter(new TxtFilter());

        //***********This seems to cause a strange error only somethimes, Right as the program is run!***********
        fcScores.setCurrentDirectory(new File("."));//http://www.rgagnon.com/javadetails/java-0370.html
    }

    class ActFileChooser implements ActionListener {

        public void actionPerformed(ActionEvent e) {//http://download.oracle.com/javase/tutorial/uiswing/examples/components/FileChooserDemoProject/src/components/FileChooserDemo.java
            int returnVal = fcScores.showOpenDialog(PnlHighScores.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                filScores = fcScores.getSelectedFile();
                sFileLocation = filScores.getAbsolutePath();//.getParent();//http://www.java-forums.org/awt-swing/29485-how-retrieve-path-filechooser.html
                //System.out.println(filScores);
                pnlScoreText.updateScoreFile(sFileLocation);
            }

        }
    }
    class TxtFilter extends javax.swing.filechooser.FileFilter {//http://www.exampledepot.com/egs/javax.swing.filechooser/Filter.html

        public boolean accept(File file) {
            String filename = file.getName();
            if (file.isDirectory()) {
                return true;
            } else {
                return filename.endsWith(".txt");
            }
        }

        public String getDescription() {
            return "*.txt";
        }
    }
}

The exact error is:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Invalid index
        at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:497)
        at sun.swing.FilePane$SortableListModel.getElementAt(FilePane.java:528)
        at javax.swing.plaf.basic.BasicListUI.updateLayoutState(BasicListUI.java:1343)
        at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(BasicListUI.java:1294)
        at javax.swing.plaf.basic.BasicListUI.getCellBounds(BasicListUI.java:935)
        at javax.swing.JList.getCellBounds(JList.java:1600)
        at javax.swing.JList.ensureIndexIsVisible(JList.java:1116)
        at sun.swing.FilePane.ensureIndexIsVisible(FilePane.java:1540)
        at sun.swing.FilePane.doDirectoryChanged(FilePane.java:1466)
        at sun.swing.FilePane.propertyChange(FilePane.java:1513)
        at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:339)
        at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:276)
        at java.awt.Component.firePropertyChange(Component.java:8128)
        at javax.swing.JFileChooser.setCurrentDirectory(JFileChooser.java:568)
        at Cannon.PnlSettings.<init>(PnlSettings.java:45)
        at Cannon.FraWindow.<init>(FraWindow.java:19)
        at Cannon.Main.main(Main.java:7)
Java Result: 1

The Main class simply creates FraWindow, and FraWindow Creates PnlSetting through its constructor method. They should be irrelavent, but here's main just in case:

package Cannon;

//Creates the frame
public class Main {

    public static void main(String[] args) {
        FraWindow fraMain = new FraWindow();
    }
}


问:
How to plot multiple Seaborn Jointplot in Subplot
I'm having problem placing Seaborn Jointplot inside a multicolumn subplot.

```<code>import pandas as pd
import seaborn as sns

df = pd.DataFrame({'C1': {'a': 1,'b': 15,'c': 9,'d': 7,'e': 2,'f': 2,'g': 6,'h': 5,'k': 5,'l': 8},
          'C2': {'a': 6,'b': 18,'c': 13,'d': 8,'e': 6,'f': 6,'g': 8,'h': 9,'k': 13,'l': 15}})

fig = plt.figure();
ax1 = fig.add_subplot(121);
ax2 = fig.add_subplot(122);

sns.jointplot("C1", "C2", data=df, kind='reg', ax=ax1)
sns.jointplot("C1", "C2", data=df, kind='kde', ax=ax2)
</code>```

Notice how only a portion of the jointplot is placed inside the subplot and the rest left inside another two plot frames. What I'd want is to have both the distributions also inserted inside the subplots.

Can anyone help with this?

答:
Moving axes in matplotlib is not as easy as it used to be in previous versions. The below is working with the current version of matplotlib.

As has been pointed out at several places (this question, also this issue) several of the seaborn commands create their own figure automatically. This is hardcoded into the seaborn code, so there is currently no way to produce such plots in existing figures. Those are PairGrid, FacetGrid, JointGrid, pairplot, jointplot and lmplot.

There is a seaborn fork available which would allow to supply a subplot grid to the respective classes such that the plot is created in a preexisting figure. To use this, you would need to copy the axisgrid.py from the fork to the seaborn folder. Note that this is currently restricted to be used with matplotlib 2.1 (possibly 2.0 as well).

An alternative could be to create a seaborn figure and copy the axes to another figure. The principle of this is shown in this answer and could be extended to Searborn plots. The implementation is a bit more complicated that I had initially expected. The following is a class SeabornFig2Grid that can be called with a seaborn grid instance (the return of any of the above commands), a matplotlib figure and a subplot_spec, which is a position of a gridspec grid.

Note: This is a proof of concept, it may work for most easy cases, but I would not recommend using it in production code.

```<code>import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
import numpy as np

class SeabornFig2Grid():

    def __init__(self, seaborngrid, fig,  subplot_spec):
        self.fig = fig
        self.sg = seaborngrid
        self.subplot = subplot_spec
        if isinstance(self.sg, sns.axisgrid.FacetGrid) or \
            isinstance(self.sg, sns.axisgrid.PairGrid):
            self._movegrid()
        elif isinstance(self.sg, sns.axisgrid.JointGrid):
            self._movejointgrid()
        self._finalize()

    def _movegrid(self):
        """ Move PairGrid or Facetgrid """
        self._resize()
        n = self.sg.axes.shape[0]
        m = self.sg.axes.shape[1]
        self.subgrid = gridspec.GridSpecFromSubplotSpec(n,m, subplot_spec=self.subplot)
        for i in range(n):
            for j in range(m):
                self._moveaxes(self.sg.axes[i,j], self.subgrid[i,j])

    def _movejointgrid(self):
        """ Move Jointgrid """
        h= self.sg.ax_joint.get_position().height
        h2= self.sg.ax_marg_x.get_position().height
        r = int(np.round(h/h2))
        self._resize()
        self.subgrid = gridspec.GridSpecFromSubplotSpec(r+1,r+1, subplot_spec=self.subplot)

        self._moveaxes(self.sg.ax_joint, self.subgrid[1:, :-1])
        self._moveaxes(self.sg.ax_marg_x, self.subgrid[0, :-1])
        self._moveaxes(self.sg.ax_marg_y, self.subgrid[1:, -1])

    def _moveaxes(self, ax, gs):
        #https://stackoverflow.com/a/46906599/4124317
        ax.remove()
        ax.figure=self.fig
        self.fig.axes.append(ax)
        self.fig.add_axes(ax)
        ax._subplotspec = gs
        ax.set_position(gs.get_position(self.fig))
        ax.set_subplotspec(gs)

    def _finalize(self):
        plt.close(self.sg.fig)
        self.fig.canvas.mpl_connect("resize_event", self._resize)
        self.fig.canvas.draw()

    def _resize(self, evt=None):
        self.sg.fig.set_size_inches(self.fig.get_size_inches())
</code>```

The usage of this class would look like this:

```<code>import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns; sns.set()
import SeabornFig2Grid as sfg

iris = sns.load_dataset("iris")
tips = sns.load_dataset("tips")

# An lmplot
g0 = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips,
                palette=dict(Yes="g", No="m"))
# A PairGrid
g1 = sns.PairGrid(iris, hue="species")
g1.map(plt.scatter, s=5)
# A FacetGrid
g2 = sns.FacetGrid(tips, col="time",  hue="smoker")
g2.map(plt.scatter, "total_bill", "tip", edgecolor="w")
# A JointGrid
g3 = sns.jointplot("sepal_width", "petal_length", data=iris,
                   kind="kde", space=0, color="g")

fig = plt.figure(figsize=(13,8))
gs = gridspec.GridSpec(2, 2)

mg0 = sfg.SeabornFig2Grid(g0, fig, gs[0])
mg1 = sfg.SeabornFig2Grid(g1, fig, gs[1])
mg2 = sfg.SeabornFig2Grid(g2, fig, gs[3])
mg3 = sfg.SeabornFig2Grid(g3, fig, gs[2])

gs.tight_layout(fig)
#gs.update(top=0.7)

plt.show()
</code>```

Note that there might be several drawbacks from copying axes and the above is not (yet) tested thoroughly.

Body:
I'm having problem placing Seaborn Jointplot inside a multicolumn subplot.

import pandas as pd
import seaborn as sns

df = pd.DataFrame({'C1': {'a': 1,'b': 15,'c': 9,'d': 7,'e': 2,'f': 2,'g': 6,'h': 5,'k': 5,'l': 8},
          'C2': {'a': 6,'b': 18,'c': 13,'d': 8,'e': 6,'f': 6,'g': 8,'h': 9,'k': 13,'l': 15}})

fig = plt.figure();
ax1 = fig.add_subplot(121);
ax2 = fig.add_subplot(122);

sns.jointplot("C1", "C2", data=df, kind='reg', ax=ax1)
sns.jointplot("C1", "C2", data=df, kind='kde', ax=ax2)

Notice how only a portion of the jointplot is placed inside the subplot and the rest left inside another two plot frames. What I'd want is to have both the distributions also inserted inside the subplots.

Can anyone help with this?

Body:
Moving axes in matplotlib is not as easy as it used to be in previous versions. The below is working with the current version of matplotlib.

As has been pointed out at several places (this question, also this issue) several of the seaborn commands create their own figure automatically. This is hardcoded into the seaborn code, so there is currently no way to produce such plots in existing figures. Those are PairGrid, FacetGrid, JointGrid, pairplot, jointplot and lmplot.

There is a seaborn fork available which would allow to supply a subplot grid to the respective classes such that the plot is created in a preexisting figure. To use this, you would need to copy the axisgrid.py from the fork to the seaborn folder. Note that this is currently restricted to be used with matplotlib 2.1 (possibly 2.0 as well).

An alternative could be to create a seaborn figure and copy the axes to another figure. The principle of this is shown in this answer and could be extended to Searborn plots. The implementation is a bit more complicated that I had initially expected. The following is a class SeabornFig2Grid that can be called with a seaborn grid instance (the return of any of the above commands), a matplotlib figure and a subplot_spec, which is a position of a gridspec grid.

Note: This is a proof of concept, it may work for most easy cases, but I would not recommend using it in production code.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns
import numpy as np

class SeabornFig2Grid():

    def __init__(self, seaborngrid, fig,  subplot_spec):
        self.fig = fig
        self.sg = seaborngrid
        self.subplot = subplot_spec
        if isinstance(self.sg, sns.axisgrid.FacetGrid) or \
            isinstance(self.sg, sns.axisgrid.PairGrid):
            self._movegrid()
        elif isinstance(self.sg, sns.axisgrid.JointGrid):
            self._movejointgrid()
        self._finalize()

    def _movegrid(self):
        """ Move PairGrid or Facetgrid """
        self._resize()
        n = self.sg.axes.shape[0]
        m = self.sg.axes.shape[1]
        self.subgrid = gridspec.GridSpecFromSubplotSpec(n,m, subplot_spec=self.subplot)
        for i in range(n):
            for j in range(m):
                self._moveaxes(self.sg.axes[i,j], self.subgrid[i,j])

    def _movejointgrid(self):
        """ Move Jointgrid """
        h= self.sg.ax_joint.get_position().height
        h2= self.sg.ax_marg_x.get_position().height
        r = int(np.round(h/h2))
        self._resize()
        self.subgrid = gridspec.GridSpecFromSubplotSpec(r+1,r+1, subplot_spec=self.subplot)

        self._moveaxes(self.sg.ax_joint, self.subgrid[1:, :-1])
        self._moveaxes(self.sg.ax_marg_x, self.subgrid[0, :-1])
        self._moveaxes(self.sg.ax_marg_y, self.subgrid[1:, -1])

    def _moveaxes(self, ax, gs):
        #https://stackoverflow.com/a/46906599/4124317
        ax.remove()
        ax.figure=self.fig
        self.fig.axes.append(ax)
        self.fig.add_axes(ax)
        ax._subplotspec = gs
        ax.set_position(gs.get_position(self.fig))
        ax.set_subplotspec(gs)

    def _finalize(self):
        plt.close(self.sg.fig)
        self.fig.canvas.mpl_connect("resize_event", self._resize)
        self.fig.canvas.draw()

    def _resize(self, evt=None):
        self.sg.fig.set_size_inches(self.fig.get_size_inches())

The usage of this class would look like this:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import seaborn as sns; sns.set()
import SeabornFig2Grid as sfg

iris = sns.load_dataset("iris")
tips = sns.load_dataset("tips")

# An lmplot
g0 = sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips,
                palette=dict(Yes="g", No="m"))
# A PairGrid
g1 = sns.PairGrid(iris, hue="species")
g1.map(plt.scatter, s=5)
# A FacetGrid
g2 = sns.FacetGrid(tips, col="time",  hue="smoker")
g2.map(plt.scatter, "total_bill", "tip", edgecolor="w")
# A JointGrid
g3 = sns.jointplot("sepal_width", "petal_length", data=iris,
                   kind="kde", space=0, color="g")

fig = plt.figure(figsize=(13,8))
gs = gridspec.GridSpec(2, 2)

mg0 = sfg.SeabornFig2Grid(g0, fig, gs[0])
mg1 = sfg.SeabornFig2Grid(g1, fig, gs[1])
mg2 = sfg.SeabornFig2Grid(g2, fig, gs[3])
mg3 = sfg.SeabornFig2Grid(g3, fig, gs[2])

gs.tight_layout(fig)
#gs.update(top=0.7)

plt.show()

Note that there might be several drawbacks from copying axes and the above is not (yet) tested thoroughly.


问:
Formatting DynamoDB data to normal JSON in AWS Lambda
I'm using AWS Lambda to scan data from a DynamoDB table. This is what I get in return:

```<code>{
  "videos": [
    {
      "file": {
        "S": "file1.mp4"
      },
      "id": {
        "S": "1"
      },
      "canvas": {
        "S": "This is Canvas1"
      }
    },
    {
      "file": {
        "S": "main.mp4"
      },
      "id": {
        "S": "0"
      },
      "canvas": {
        "S": "this is a canvas"
      }
    }
  ]
}
</code>```

My front-end application is using Ember Data Rest Adapter which does not accepts such response. Is there any way I can get normal JSON format? There is this NPM module called dynamodb-marshaler to convert DynamoDB data to normal JSON. I'm looking for a native solution if possible.

答:
Node.js
Use the unmarshall function from AWSJavaScriptSDK:

const AWS = require("aws-sdk");

exports.handler = function( event, context, callback ) {
    const newImages = event.Records.map(
            (record) => AWS.DynamoDB.Converter.unmarshall(record.dynamodb.NewImage)
    );
    console.log('Converted records', newImages);
    callback(null, `Success`);
}
```
<p><strong>Python</strong>
Use <code>TypeDeserializer.deserialize</code> from boto3.dynamodb.types:</p>
<pre class="lang-py prettyprint-override"><code>import json
from boto3.dynamodb.types import TypeDeserializer

def ddb_deserialize(r, type_deserializer = TypeDeserializer()):
    return type_deserializer.deserialize({"M": r})

def lambda_handler(event, context):
    new_images = [ ddb_deserialize(r["dynamodb"]["NewImage"]) for r in event['Records'] ]
    print('Converted records', json.dumps(new_images, indent=2))
</code>```

Body:
I'm using AWS Lambda to scan data from a DynamoDB table. This is what I get in return:

{
  "videos": [
    {
      "file": {
        "S": "file1.mp4"
      },
      "id": {
        "S": "1"
      },
      "canvas": {
        "S": "This is Canvas1"
      }
    },
    {
      "file": {
        "S": "main.mp4"
      },
      "id": {
        "S": "0"
      },
      "canvas": {
        "S": "this is a canvas"
      }
    }
  ]
}

My front-end application is using Ember Data Rest Adapter which does not accepts such response. Is there any way I can get normal JSON format? There is this NPM module called dynamodb-marshaler to convert DynamoDB data to normal JSON. I'm looking for a native solution if possible.

Body:
Node.js
Use the unmarshall function from AWSJavaScriptSDK:

const AWS = require("aws-sdk");

exports.handler = function( event, context, callback ) {
    const newImages = event.Records.map(
            (record) => AWS.DynamoDB.Converter.unmarshall(record.dynamodb.NewImage)
    );
    console.log('Converted records', newImages);
    callback(null, `Success`);
}

Python
Use TypeDeserializer.deserialize from boto3.dynamodb.types:

import json
from boto3.dynamodb.types import TypeDeserializer

def ddb_deserialize(r, type_deserializer = TypeDeserializer()):
    return type_deserializer.deserialize({"M": r})

def lambda_handler(event, context):
    new_images = [ ddb_deserialize(r["dynamodb"]["NewImage"]) for r in event['Records'] ]
    print('Converted records', json.dumps(new_images, indent=2))


问:
Copy 1 TB Google Cloud Storage from container a to b - Run-time?
How long would it on average take to copy files with a total size of 1TB within Google Cloud Storage (Regional Storage) from a container a to b?

e.g. gsutil -m cp gs://gdfp-performance/*.csv gs://gdfp-intrastoragetransfer

答:
If the objects are all in the same region and have the same storage class, the operation will only involve changing metadata and the copies won't take any longer regardless of size. In that case, the total size doesn't matter. The main limiting factor is the number of objects.

Regardless, the answer depends tremendously on where you're running the operation from and the characteristics of your network access. You'd probably get optimal performance running it on a large GCE machine in the same region as the data, but again it depends tremendously on how many objects you have, how large they are, and whether you're copying within the same region/class.


问:
How to evenly space out radiobuttons in Android?
I have three radiobuttons and I want to evenly space them across the screen. When I use android:layout_weight="1", the buttons are stretched out across the screen. So how would I have the same amount of space in between each of them that also scales on different screen sizes?

```<code><RadioGroup
        android:id="@+id/auton_bar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:layout_below="@id/clear_fields"
                >
        <RadioButton
            android:id="@+id/auton_radio_1"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:background="@drawable/auton_col"
            android:layout_weight="1"

            />
        <!-- android:layout_marginRight="380dp"  -->
        <RadioButton
            android:id="@+id/auton_radio_2"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:background="@drawable/auton_col"
            android:layout_weight="1"

            />
        <RadioButton
            android:id="@+id/auton_radio_3"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:background="@drawable/auton_col"
            android:layout_weight="1"
            />

    </RadioGroup>
</code>```

答:
I noticed that using layout weights for the RadioButton's caused them to be aligned off-center, eventhough they definitely each shared 50% of the screen (they were left-aligned). Setting a gravity for each RadioButton caused only the text to be centered /facepalm

The XML below shows how to horizontally align two radiobuttons (could be any views) and center them:

```<code>                <RadioGroup
                    android:id="@+id/radiogroup"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <Space
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"/>

                    <RadioButton
                        android:id="@+id/radioyes"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/yes"
                        android:checked="false"/>

                    <Space
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"/>

                    <RadioButton
                        android:id="@+id/radiono"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/no"
                        android:checked="false"/>

                    <Space
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"/>

                </RadioGroup>
</code>```

Body:
I have three radiobuttons and I want to evenly space them across the screen. When I use android:layout_weight="1", the buttons are stretched out across the screen. So how would I have the same amount of space in between each of them that also scales on different screen sizes?

<RadioGroup
        android:id="@+id/auton_bar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:layout_below="@id/clear_fields"
                >
        <RadioButton
            android:id="@+id/auton_radio_1"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:background="@drawable/auton_col"
            android:layout_weight="1"

            />

        <RadioButton
            android:id="@+id/auton_radio_2"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:background="@drawable/auton_col"
            android:layout_weight="1"

            />
        <RadioButton
            android:id="@+id/auton_radio_3"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:background="@drawable/auton_col"
            android:layout_weight="1"
            />

    </RadioGroup>

Body:
I noticed that using layout weights for the RadioButton's caused them to be aligned off-center, eventhough they definitely each shared 50% of the screen (they were left-aligned). Setting a gravity for each RadioButton caused only the text to be centered /facepalm

The XML below shows how to horizontally align two radiobuttons (could be any views) and center them:

                <RadioGroup
                    android:id="@+id/radiogroup"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <Space
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"/>

                    <RadioButton
                        android:id="@+id/radioyes"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/yes"
                        android:checked="false"/>

                    <Space
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"/>

                    <RadioButton
                        android:id="@+id/radiono"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/no"
                        android:checked="false"/>

                    <Space
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"/>

                </RadioGroup>


问:
How to store lines from a file as a variable
I'd like to show the employee number name, occupation, and department of employees from a text file called organisation.txt, and save them in the variables declared in the class OrganisationRecord.

How can I do that?

```<code>#include <iostream>
#include <string>
#include <vector>
#include <fstream>

#define ORGANISATIONALRECORDSFILE "organisation.txt"
#define HRRECORDSFILE "HR_records.txt"
#define PAYROLLRECORDSFILE "payroll_records.txt"

using namespace std;

class OrganisationRecord
{
private:
public:
    string name;
    string occupation;
    string department;
};

class HRRecord
{
private:
public:
    string address;
    string phonenumber;
    string ninumber;
};

class PayrollRecord
{
private:
public:
    string ninumber;
    double salary;
};

class PayrollProcessing
{
private:
    ifstream inputfile;
    ofstream outputfile;
    vector<OrganisationRecord> OrganisationRecords;
    vector<HRRecord> HRRecords;
    vector<PayrollRecord> PayrollRecords;
public:
    void loadOrganisationRecords(string filename);
    void loadHRRecords(string filename);
    void loadPayrollRecords(string filename);
    void displayEmployeeOfSalaryGTE(double salary);
    //GTE = greater than or equal to
};

void PayrollProcessing::loadOrganisationRecords(string filename)
{
    inputfile.open(ORGANISATIONALRECORDSFILE);

    if (!inputfile)
    {
        cout << "the organisation records file does not exist" << endl;
        return;
    }

        OrganisationRecord _organisationrecord;
        int employeenumber;

        while (inputfile >> employeenumber)
        {
            while (inputfile >> _organisationrecord.name)
            {
                cout << _organisationrecord.name;
                cout << _organisationrecord.occupation;
                cout << _organisationrecord.department <<endl;
            }

            OrganisationRecords.push_back(_organisationrecord);
        }

}

int main(void)
{
    PayrollProcessing database1;
    database1.loadOrganisationRecords(ORGANISATIONALRECORDSFILE);

    return 0;
}
</code>```

organisation.txt

0001
Stephen Jones
Sales Clerk
Sales
0002
John Smith
Programmer
OS Development
0003
Fred Blogs
Project Manager
Outsourcing
```

答:
When you use inputfile >> _organisationrecord.name it stops at the first whitespace character. Hence, only Stephen will be read and stored in organisationrecord.name.

You need to change your strategy a bit.

Read the contents of the file line by line. Stop when there are no more lines left.

Process each line as you seem fit.

Here's one way to deal with the input.

```<code>std::string line;
while ( std::getline(inputfile, line) )
{
   // Extract the employeenumber from the line
   std::istringstream str(line);
   if ( !(str >> employeenumber) )
   {
      // Problem reading the employeenumber.
      // Stop reading.
      break;
   }

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }

   _organisationrecord.name = line;

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }
   _organisationrecord.occupation = line;

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }
   _organisationrecord.department = line;

   std::cout << _organisationrecord.employeenumber << std::endl;
   std::cout << _organisationrecord.name << std::endl;
   std::cout << _organisationrecord.occupation << std::endl;
   std::cout << _organisationrecord.department << endl;

   OrganisationRecords.push_back(_organisationrecord);
}
</code>```

Body:
I'd like to show the employee number name, occupation, and department of employees from a text file called organisation.txt, and save them in the variables declared in the class OrganisationRecord.

How can I do that?

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

#define ORGANISATIONALRECORDSFILE "organisation.txt"
#define HRRECORDSFILE "HR_records.txt"
#define PAYROLLRECORDSFILE "payroll_records.txt"

using namespace std;

class OrganisationRecord
{
private:
public:
    string name;
    string occupation;
    string department;
};

class HRRecord
{
private:
public:
    string address;
    string phonenumber;
    string ninumber;
};

class PayrollRecord
{
private:
public:
    string ninumber;
    double salary;
};

class PayrollProcessing
{
private:
    ifstream inputfile;
    ofstream outputfile;
    vector<OrganisationRecord> OrganisationRecords;
    vector<HRRecord> HRRecords;
    vector<PayrollRecord> PayrollRecords;
public:
    void loadOrganisationRecords(string filename);
    void loadHRRecords(string filename);
    void loadPayrollRecords(string filename);
    void displayEmployeeOfSalaryGTE(double salary);
    //GTE = greater than or equal to
};

void PayrollProcessing::loadOrganisationRecords(string filename)
{
    inputfile.open(ORGANISATIONALRECORDSFILE);

    if (!inputfile)
    {
        cout << "the organisation records file does not exist" << endl;
        return;
    }

        OrganisationRecord _organisationrecord;
        int employeenumber;

        while (inputfile >> employeenumber)
        {
            while (inputfile >> _organisationrecord.name)
            {
                cout << _organisationrecord.name;
                cout << _organisationrecord.occupation;
                cout << _organisationrecord.department <<endl;
            }

            OrganisationRecords.push_back(_organisationrecord);
        }

}

int main(void)
{
    PayrollProcessing database1;
    database1.loadOrganisationRecords(ORGANISATIONALRECORDSFILE);

    return 0;
}

organisation.txt

0001
Stephen Jones
Sales Clerk
Sales
0002
John Smith
Programmer
OS Development
0003
Fred Blogs
Project Manager
Outsourcing

Body:
When you use inputfile >> _organisationrecord.name it stops at the first whitespace character. Hence, only Stephen will be read and stored in organisationrecord.name.

You need to change your strategy a bit.

Read the contents of the file line by line. Stop when there are no more lines left.

Process each line as you seem fit.

Here's one way to deal with the input.

std::string line;
while ( std::getline(inputfile, line) )
{
   // Extract the employeenumber from the line
   std::istringstream str(line);
   if ( !(str >> employeenumber) )
   {
      // Problem reading the employeenumber.
      // Stop reading.
      break;
   }

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }

   _organisationrecord.name = line;

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }
   _organisationrecord.occupation = line;

   if (!std::getline(inputfile, line) )
   {
      // Problem reading the next line.
      // Stop reading.
      break;
   }
   _organisationrecord.department = line;

   std::cout << _organisationrecord.employeenumber << std::endl;
   std::cout << _organisationrecord.name << std::endl;
   std::cout << _organisationrecord.occupation << std::endl;
   std::cout << _organisationrecord.department << endl;

   OrganisationRecords.push_back(_organisationrecord);
}


问:
Create an Interval class with desired format
Im trying to create a class called Interval that if given 1 parameter a, it creates it in the format [a,a], and if given 2 parameters a and b, it creates it in the format [a,b]. See the following code

```<code>class Interval():

   def __init__(self,left,*args):

       if args:
           self.left=left
           self.right=args
       else:
           self.left=left
           self.right=left

   def __repr__(self):
       return("[{},{}]".format(self.left,self.right))
</code>```

Now when i have only one parameter it prints it out in the desired format, but with 2 parameters i get a paranthesis inside the brackets, see below:

```<code>    a = Interval(1)
    b = Interval(2,4)
    print (a)
    print (b)
</code>```

Prints out:

```<code>    [1,1]
    [2,(4,)]
</code>```

Why does this happen? Any help appreciated,  thanks.

答:
To be as generic as possible, you can try this:

```<code>class Interval():
  def __init__(self,left,*args):
     if args:
        self.left=left
        self.right=args
     else:
        self.left=left
        self.right=left
  def __repr__(self):
      return("[{},{}]".format(self.left,','.join(map(str, self.right))))
i = Interval(4, 4)
print(i)
</code>```

Output:

```<code>[4,4]
</code>```

Body:
Im trying to create a class called Interval that if given 1 parameter a, it creates it in the format [a,a], and if given 2 parameters a and b, it creates it in the format [a,b]. See the following code

class Interval():

   def __init__(self,left,*args):

       if args:
           self.left=left
           self.right=args
       else:
           self.left=left
           self.right=left

   def __repr__(self):
       return("[{},{}]".format(self.left,self.right))

Now when i have only one parameter it prints it out in the desired format, but with 2 parameters i get a paranthesis inside the brackets, see below:

    a = Interval(1)
    b = Interval(2,4)
    print (a)
    print (b)

Prints out:

    [1,1]
    [2,(4,)]

Why does this happen? Any help appreciated,  thanks.

Body:
To be as generic as possible, you can try this:

class Interval():
  def __init__(self,left,*args):
     if args:
        self.left=left
        self.right=args
     else:
        self.left=left
        self.right=left
  def __repr__(self):
      return("[{},{}]".format(self.left,','.join(map(str, self.right))))
i = Interval(4, 4)
print(i)

Output:

[4,4]


问:
C++ shared ptr release on multiple references
I have an hierarchy where A is an abstract class and B, C, and D are descendants of A. I have a class Controller (MVC pattern) with a shared pointer to A:

```<code>class Controller {

private:
 int it;
 std::shared_ptr<A> theBase;

public:
 void doCall();
//more code

}
</code>```

Inside doCall() I do this:

```<code>void doCall() {

  switch (it) {
    case 4:
      theBase = std::make_shared<B>( B(8) );
      break;
    case 3:
      theBase = std::make_shared<C>( C(6) );
      break;
    default:
      theBase = std::make_shared<D>( D(0) );
      break;
    }

  theBase->method();

}
</code>```

In this way I can properly use smart pointers and I can use inheritance to get the class that I need according to the value of it.

Suppose that I call this code:

```<code>Controller x;
x.doCall();
x.doCall();
</code>```

I am calling doCall() twice, so I am going in the switch twice. This means that std::make_shared is called twice and assigning to theBase. Is this safe?

When I call doCall() for the first time, I have a shared pointer. The second time I am assigning another std::shared_ptr to theBase, and I wonder: is the old pointer (the one of the first call) destroyed and a new one is created? Or do I have to do something like this?

```<code>if (*theBase != nullptr) {
  theBase.reset(); //delete the old one;
}

switch (it) { /* ... */}
</code>```

Each time doCall() is called, I have to create a new object that is a subclass of theBase. Am I doing it correctly?

答:
You have to do nothing. When you assign the newly created shared_ptr to theBase, the old one's reference counter will be decremented. However the old one's counter is 1(if we assume you are not referencing it somewhere else). The counter reaches 0 and the destructor is called.

Take a look at the following code:

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

class myClass
{
public:
    myClass(int i) : m_i(i) { printf("Constructed %d\n", m_i); }
    ~myClass() { printf("Destructed %d\n", m_i); }

    int m_i;
};

int main()
{
    std::shared_ptr<myClass> ptr = std::make_shared<myClass>(5);

    ptr = std::make_shared<myClass>(10);
}
</code>```

The output is:

```<code>Constructed 5
Constructed 10
Destructed 5
Destructed 10
</code>```

The first pointer is destructed just after the second one is created(more specifically when assigned; that's where the first one's counter is decremented).

Body:
I have an hierarchy where A is an abstract class and B, C, and D are descendants of A. I have a class Controller (MVC pattern) with a shared pointer to A:

class Controller {

private:
 int it;
 std::shared_ptr theBase;

public:
 void doCall();
//more code

}

Inside doCall() I do this:

void doCall() {

  switch (it) {
    case 4:
      theBase = std::make_shared( B(8) );
      break;
    case 3:
      theBase = std::make_shared<C>( C(6) );
      break;
    default:
      theBase = std::make_shared<D>( D(0) );
      break;
    }

  theBase->method();

}

In this way I can properly use smart pointers and I can use inheritance to get the class that I need according to the value of it.

Suppose that I call this code:

Controller x;
x.doCall();
x.doCall();

I am calling doCall() twice, so I am going in the switch twice. This means that std::make_shared is called twice and assigning to theBase. Is this safe?

When I call doCall() for the first time, I have a shared pointer. The second time I am assigning another std::shared_ptr to theBase, and I wonder: is the old pointer (the one of the first call) destroyed and a new one is created? Or do I have to do something like this?

if (*theBase != nullptr) {
  theBase.reset(); //delete the old one;
}

switch (it) { /* ... */}

Each time doCall() is called, I have to create a new object that is a subclass of theBase. Am I doing it correctly?

Body:
You have to do nothing. When you assign the newly created shared_ptr to theBase, the old one's reference counter will be decremented. However the old one's counter is 1(if we assume you are not referencing it somewhere else). The counter reaches 0 and the destructor is called.

Take a look at the following code:

#include <stdio.h>
#include <memory>

class myClass
{
public:
    myClass(int i) : m_i(i) { printf("Constructed %d\n", m_i); }
    ~myClass() { printf("Destructed %d\n", m_i); }

    int m_i;
};

int main()
{
    std::shared_ptr<myClass> ptr = std::make_shared<myClass>(5);

    ptr = std::make_shared<myClass>(10);
}

The output is:

Constructed 5
Constructed 10
Destructed 5
Destructed 10

The first pointer is destructed just after the second one is created(more specifically when assigned; that's where the first one's counter is decremented).