问:
C++ simple file read-in to array question
Simple quick question.
Whats the best way to read in an array of float values that you don't know how long they will be?
(However we know it will not be longer than 75 integers long)

Lets say I have a file (derp.txt)
and the integers are 5.3 6.2 1.5 5.0 1.4 4.5.....etc

and I want to put them into array numbers[75];
Whats the best way of doing this in C++ (and if your feeling awesome C)

I was thinking it'd be a combination of stringstreams and getline, but im not familiar with stringstreams at all.

edit: i forgot to mention this.
After that array is another 2 numbers which dont belong into that array (they are easy to read in) so basically I just need to read till the end of the line

答:
```<code>std::vector<double> results;
std::copy(std::istream_iterator<double>(std::cin),
          std::istream_iterator<double>(),
          std::back_inserter(results));
</code>```

You can replace std::cin with whatever stream you are actually using.

It's a bit messier to read into an array, but you probably don't want to use an array anyway; you said that you don't know how long the list of values will be, so how do you know that 75 is the correct size for the array?  With std::vector, you don't have this problem.

Body:
std::vector<double> results;
std::copy(std::istream_iterator<double>(std::cin),
          std::istream_iterator<double>(),
          std::back_inserter(results));

You can replace std::cin with whatever stream you are actually using.

It's a bit messier to read into an array, but you probably don't want to use an array anyway; you said that you don't know how long the list of values will be, so how do you know that 75 is the correct size for the array?  With std::vector, you don't have this problem.


来源: stackexchange

问:
navigation controller doesn't work on all views
I'm working on a project and I have a tabbar controller and there are four views connected to the tabbar controller , however all views are working just fine but one , the view does not recognize that it is embedded from a navigation controller which results (no back button and no tabbar)
here is a picture of the part that is not working in the storyboard :

答:
The problem solved !
The segue was of type show(e.g push) however unlike the other views this one didn't work with navigation controller , so what I've done is that I deleted the segue and created another one with exactly the same attributes , and it worked !
Thank you guys for your efforts </p>

ContentLicense: CC BY-SA 3.0


问:
how pass parameter to php class by class()::function()
How pass parameter to PHP class by class()::function()?

```<code>class greenHouse{
    public function __construct(connection $con){
    }

    public function show(){
    }

}

$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass::$namefunction();
</code>```

works

```<code>$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass($con)::$namefunction();
</code>```

doesn't work

I want to pass a parameter to the class with $nameclass($con)::$namefunction();. How do I do that in PHP?

答:
You can instantiate an object and immediately discard it by calling new within braces:

```<code>class Test
{
    private $name;

    function __construct($name)
    {
        $this->name = $name;
    }

    function speak()
    {

        echo $this->name;
    }

    function __destruct()
    {
        echo 'dead';
    }
}
$class='Test';
$method='speak';

(new $class('David'))->$method();

echo ' is ';

$temp = new $class('John');
$temp->$method();

echo ' is ';

//Daviddead is John is dead
</code>```

So in your case:

```<code>(new $nameclass($con))->$namefunction();
</code>```

Body:
How pass parameter to PHP class by class()::function()?

class greenHouse{
    public function __construct(connection $con){
    }

    public function show(){
    }

}

$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass::$namefunction();

works

$nameclass = 'greenHouse';
$namefunction = 'show';
$nameclass($con)::$namefunction();

doesn't work

I want to pass a parameter to the class with $nameclass($con)::$namefunction();. How do I do that in PHP?

Body:
You can instantiate an object and immediately discard it by calling new within braces:

class Test
{
    private $name;

    function __construct($name)
    {
        $this->name = $name;
    }

    function speak()
    {

        echo $this->name;
    }

    function __destruct()
    {
        echo 'dead';
    }
}
$class='Test';
$method='speak';

(new $class('David'))->$method();

echo ' is ';

$temp = new $class('John');
$temp->$method();

echo ' is ';

//Daviddead is John is dead

So in your case:

(new $nameclass($con))->$namefunction();


问:
HTML5 Have left aligned text and right aligned text in same line within paragraph
I want to have "This is a test" left aligned and "[Rare photograph]" right aligned but still be on the same line.

I'm a newbie at HTML5, so a simple explanation would be appreciated.

Thanks! :)

```<code><p style = "margin-left:75px;max-width:750px;"><br/>
        This is a test.
        [Rare photograph]

</p>
</code>```

答:
You can't do that without an additional tag, but what you can do is inject a  tag within a
 tag, and give each  a respective float: left and float: right:

  This is a test.
  [Rare photograph]

```

Hope this helps! :)

Body:
I want to have "This is a test" left aligned and "[Rare photograph]" right aligned but still be on the same line.

I'm a newbie at HTML5, so a simple explanation would be appreciated.

Thanks! :)

        This is a test.
        [Rare photograph]

Body:
You can't do that without an additional tag, but what you can do is inject a <span> tag within a <p> tag, and give each <span> a respective float: left and float: right:

<p style="margin-left: 75px; max-width: 750px;">
  <span style="float: left">This is a test.</span>
  <span style="float: right">[Rare photograph]</span>
</p>

Hope this helps! :)


问:
I need to nest 2 arrays so that I can echo order header as well as order item details
I have updated my original post based on what I learned from your comments below. It is a much simpler process than I originally thought.

```<code>    require '../database.php';

    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "SELECT * FROM Orders WHERE id = 430";
            $q = $pdo->prepare($sql);
            $q->execute(array($id));
            $data = $q->fetch(PDO::FETCH_ASSOC);

            echo    'Order Num: ' . $data['id'] . '<br>';

    $sql = "SELECT  * FROM Order_items
            JOIN    Parts ON Parts.id = Order_Items.part_id
            WHERE   Order_Items.orders_id = 430";

            $q = $pdo->prepare($sql);
            $q->execute(array($line_item_id));
            $data = $q->fetch(PDO::FETCH_ASSOC);

            while ($data = $q->fetch(PDO::FETCH_ASSOC))
            {
                echo '- ' . $data['part_num'] . $data['qty'] . "<br>";
            }

     Database::disconnect();
</code>```

Unfortunately, only my first query is producing results. The second query is producing the following ERROR LOG: "Base table or view not found: 1146 Table 'Order_items' doesn't exist" but I am expecting the following results.

Expected Results from Query 1:
     Order Num: 430

Expected Results from Query 2:

```<code>- Screws 400
- Plates 35
- Clips 37
- Poles 7
- Zip ties 45
</code>```

答:
Now that I understand where you are coming from, let's explain a couple of things.

1.PDO and mysqli are two ways of accessing the database; they essentially do the same things, but the notation is different.

2.Arrays are variables with multiple "compartments". Most typical array has the compartments identified by a numerical index, like:

```<code>$array[0] = 'OR12345'; //order number
$array[1] = '2017-03-15'; //order date
$array[2] = 23; //id of a person/customer placing the order
</code>```

etc. But this would require us to remember which number index means what. So in PHP there are associative arrays, which allow using text strings as indexes, and are used for fetching SQL query results.

3.The statement

```<code>$data = $q->fetch(PDO::FETCH_ASSOC)
</code>```

or

```<code>$row = $result->fetch_assoc()
</code>```

do exactly the same thing: put a record (row) from a query into an array, using field names as indexes. This way it's easy to use the data, because you can use field names (with a little bit around them) for displaying or manipulating the field values.

4.The

```<code>while ($row = $result->fetch_assoc())
</code>```

does two things. It checks if there is a row still to fetch from the query results. and while there is one - it puts it into the array $row for you to use, and repeats (all the stuff between { and }).

So you fetch the row, display the results in whatever form you want, and then loop to fetch another row. If there are no more rows to fetch - the loop ends.

5.You should avoid using commas in the FROM clause in a query. This notation can be used only if the fields joining the tables are obvious (named the same), but it is bad practice anyway. The joins between tables should be specified explicitly. In the first query you want the header only, and there is no additional table needed in your example, so you should have just

```<code>SELECT *
FROM Orders
WHERE Orders.Order_ID = 12345
</code>```

whereas in the second query I understand you have a table Parts, which contains descriptions of various parts that can be ordered? If so, then the second query should have:

```<code>SELECT *
FROM Order_items
JOIN Parts ON Parts.ID = Order_Items.Part_ID
WHEERE Order_Items.Order_ID = 12345
</code>```

If in your Orders table you had a field for the ID of the supplier Supplier_ID, pointing to a Suppliers table, and an ID of the person placing the order Customer_ID, pointing to a Customers table, then the first query would look like this:

```<code>SELECT *
FROM Orders
JOIN Suppliers ON Suppliers.ID = Orders.Supplier_ID
JOIN Customers ON Customers.ID = Orders.Customer_ID
WHERE Orders.Order_ID = 12345
</code>```

Hope this is enough for you to learn further on your own :).

Body:
I have updated my original post based on what I learned from your comments below. It is a much simpler process than I originally thought.

    require '../database.php';

    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = "SELECT * FROM Orders WHERE id = 430";
            $q = $pdo->prepare($sql);
            $q->execute(array($id));
            $data = $q->fetch(PDO::FETCH_ASSOC);

            echo    'Order Num: ' . $data['id'] . '
';

    $sql = "SELECT  * FROM Order_items
            JOIN    Parts ON Parts.id = Order_Items.part_id
            WHERE   Order_Items.orders_id = 430";

            $q = $pdo->prepare($sql);
            $q->execute(array($line_item_id));
            $data = $q->fetch(PDO::FETCH_ASSOC);

            while ($data = $q->fetch(PDO::FETCH_ASSOC))
            {
                echo '- ' . $data['part_num'] . $data['qty'] . "
";
            }

     Database::disconnect();

Unfortunately, only my first query is producing results. The second query is producing the following ERROR LOG: "Base table or view not found: 1146 Table 'Order_items' doesn't exist" but I am expecting the following results.

Expected Results from Query 1:
     Order Num: 430

Expected Results from Query 2:

- Screws 400
- Plates 35
- Clips 37
- Poles 7
- Zip ties 45

Body:
Now that I understand where you are coming from, let's explain a couple of things.

1.PDO and mysqli are two ways of accessing the database; they essentially do the same things, but the notation is different.

2.Arrays are variables with multiple "compartments". Most typical array has the compartments identified by a numerical index, like:

$array[0] = 'OR12345'; //order number
$array[1] = '2017-03-15'; //order date
$array[2] = 23; //id of a person/customer placing the order

etc. But this would require us to remember which number index means what. So in PHP there are associative arrays, which allow using text strings as indexes, and are used for fetching SQL query results.

3.The statement

$data = $q->fetch(PDO::FETCH_ASSOC)

or

$row = $result->fetch_assoc()

do exactly the same thing: put a record (row) from a query into an array, using field names as indexes. This way it's easy to use the data, because you can use field names (with a little bit around them) for displaying or manipulating the field values.

4.The

while ($row = $result->fetch_assoc())

does two things. It checks if there is a row still to fetch from the query results. and while there is one - it puts it into the array $row for you to use, and repeats (all the stuff between { and }).

So you fetch the row, display the results in whatever form you want, and then loop to fetch another row. If there are no more rows to fetch - the loop ends.

5.You should avoid using commas in the FROM clause in a query. This notation can be used only if the fields joining the tables are obvious (named the same), but it is bad practice anyway. The joins between tables should be specified explicitly. In the first query you want the header only, and there is no additional table needed in your example, so you should have just

SELECT *
FROM Orders
WHERE Orders.Order_ID = 12345

whereas in the second query I understand you have a table Parts, which contains descriptions of various parts that can be ordered? If so, then the second query should have:

SELECT *
FROM Order_items
JOIN Parts ON Parts.ID = Order_Items.Part_ID
WHEERE Order_Items.Order_ID = 12345

If in your Orders table you had a field for the ID of the supplier Supplier_ID, pointing to a Suppliers table, and an ID of the person placing the order Customer_ID, pointing to a Customers table, then the first query would look like this:

SELECT *
FROM Orders
JOIN Suppliers ON Suppliers.ID = Orders.Supplier_ID
JOIN Customers ON Customers.ID = Orders.Customer_ID
WHERE Orders.Order_ID = 12345

Hope this is enough for you to learn further on your own :).


问:
NetLogo: calculate perimeter of a patch-set
I'm modeling territory selection in NetLogo, and would like my turtles to calculate the perimeter of their territory once established. I've been trying to come up with ideas for how to do this, but haven't found a good means yet. Any ideas?

```<code>patches-own
[ owner ] ;; patches know who owns them

turtles-own
[ territory  ;; agentset of patches I own
  food ;; food acquired in my territory
  threshold ] ;; food required, will build territory until meet this

to go
   tick
   ask turtles [ build-territory ]
end

to build-territory
   if food > threshold [ calculate-perimeter ]  ;; stop building when enough food
   pick-patch  ;; keep picking patches until meet threshold.
end

to calculate-perimeter
   ;; what could I use to add up the perimeter of the territory?
end
</code>```

Thanks in advance for any suggestions!

答:
A modification of my last answer to you:

```<code>to setup
  ca
  ask patches with [pxcor > 0 ] [
    set pcolor white
  ]
  crt 1
end

to go
  ask turtles [
    let blacklist patches with [ pcolor = black ]
    let northpatches patches with [ pycor > 0 ]
    let northred ( northpatches with [ member? self blacklist = false ] )
    ask northred [ set pcolor red ]
    let border northred with [ any? neighbors4 with [ pcolor != red ] ]
    ask border [
      set pcolor blue
    ]
    print count border
  ]
end
</code>```

You can designate border/perimeter patches as any of you territory patches with neighbors that are not territory. For you it might look something like:

```<code>  ask turtles [
    print count territory with [ any? neighbors4 with [owner != myself ]
    ]
  ]
</code>```

Again, I can't test it without your setup so you would have to modify.

Edited below

To count the edges of patches that are on the border, you could have them count their neighbors4 that belong to another turtle. Then, they can add them to that turtle's perimeter length. For example:

```<code>to assess-perimeter  ;;; must be called by a turtle
  print ("Assessing perimeter")
  let current-turtle who
  let temp-per-len 0
  let border-patches patches with [ owner = current-turtle and any? neighbors4 with [ owner != current-turtle ] ]
  show (word "I have " count border-patches " border patches")
  ask border-patches [
    ;; One way to get each border patch to check each of its neighbors
    let nobodies 4 - count neighbors4 ;; if any patches are on the edge of the world, returns the number of those edges
    let non-territory-edges count neighbors4 with [ owner != current-turtle ]
    let border-edges nobodies + non-territory-edges
    set temp-per-len temp-per-len + border-edges
  ]
  show (word "My perimeter length: " temp-per-len )
  set perimeter-length temp-per-len
end
</code>```

If that is called after all turtles have chosen their entire home range, the idea is that each turtle assesses the border of its home range. Then, it has each of those border patches count its neighbors4 that have a different owner. I used "temp-per-len" as a summing variable within the loop, which is then used to set the turtles-own "perimeter-length". Full model code, including setup and definitions, here. Note- you'll have to download or copy the code, the model is too bulky to run well in the HTML format.

Also, I didn't actually count to make sure this worked perfectly- I did a quick version and crossed my fingers, but I think the idea makes sense and hopefully gets you started.

Body:
I'm modeling territory selection in NetLogo, and would like my turtles to calculate the perimeter of their territory once established. I've been trying to come up with ideas for how to do this, but haven't found a good means yet. Any ideas?

patches-own
[ owner ] ;; patches know who owns them

turtles-own
[ territory  ;; agentset of patches I own
  food ;; food acquired in my territory
  threshold ] ;; food required, will build territory until meet this

to go
   tick
   ask turtles [ build-territory ]
end

to build-territory
   if food > threshold [ calculate-perimeter ]  ;; stop building when enough food
   pick-patch  ;; keep picking patches until meet threshold.
end

to calculate-perimeter
   ;; what could I use to add up the perimeter of the territory?
end

Thanks in advance for any suggestions!

Body:
A modification of my last answer to you:

to setup
  ca
  ask patches with [pxcor > 0 ] [
    set pcolor white
  ]
  crt 1
end

to go
  ask turtles [
    let blacklist patches with [ pcolor = black ]
    let northpatches patches with [ pycor > 0 ]
    let northred ( northpatches with [ member? self blacklist = false ] )
    ask northred [ set pcolor red ]
    let border northred with [ any? neighbors4 with [ pcolor != red ] ]
    ask border [
      set pcolor blue
    ]
    print count border
  ]
end

You can designate border/perimeter patches as any of you territory patches with neighbors that are not territory. For you it might look something like:

  ask turtles [
    print count territory with [ any? neighbors4 with [owner != myself ]
    ]
  ]

Again, I can't test it without your setup so you would have to modify.

Edited below

To count the edges of patches that are on the border, you could have them count their neighbors4 that belong to another turtle. Then, they can add them to that turtle's perimeter length. For example:

to assess-perimeter  ;;; must be called by a turtle
  print ("Assessing perimeter")
  let current-turtle who
  let temp-per-len 0
  let border-patches patches with [ owner = current-turtle and any? neighbors4 with [ owner != current-turtle ] ]
  show (word "I have " count border-patches " border patches")
  ask border-patches [
    ;; One way to get each border patch to check each of its neighbors
    let nobodies 4 - count neighbors4 ;; if any patches are on the edge of the world, returns the number of those edges
    let non-territory-edges count neighbors4 with [ owner != current-turtle ]
    let border-edges nobodies + non-territory-edges
    set temp-per-len temp-per-len + border-edges
  ]
  show (word "My perimeter length: " temp-per-len )
  set perimeter-length temp-per-len
end

If that is called after all turtles have chosen their entire home range, the idea is that each turtle assesses the border of its home range. Then, it has each of those border patches count its neighbors4 that have a different owner. I used "temp-per-len" as a summing variable within the loop, which is then used to set the turtles-own "perimeter-length". Full model code, including setup and definitions, here. Note- you'll have to download or copy the code, the model is too bulky to run well in the HTML format.

Also, I didn't actually count to make sure this worked perfectly- I did a quick version and crossed my fingers, but I think the idea makes sense and hopefully gets you started.


问:
Issues indexing data into elasticsearch in laravel
I am trying to index a whole table of about 47k records into elastic search.  This is not a lot of data.  Regardless, I am chunking the records with eloquent and no matter the size of the chunk, by the 5th "update_mapping" of ES console output, everything just stops.

I'm not 100% sure what information you will need to help debug this, so I will try to cover everything.

Laravel 5.2 hosted inside a vagrant machine, running the Scotch-Vagrant image.

I am using the official docker image from elastic search:

```<code>docker run -p 9200:9200 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" docker.elastic.co/elasticsearch/elasticsearch:5.2.1
</code>```

To work with ES, I am using their official package.  In my composer.json:

```<code>"elasticsearch/elasticsearch": "^5.1"
</code>```

I used this tutorial to get up and running:
https://michaelstivala.com/learning-elasticsearch-with-laravel/

(Including the "beefed up" wrapper.)

I added a method to his class, as a debugging effor:

```<code>public function createIndex($params) {
    return $this->client->indices()->create($params);
}
</code>```

I'll get to the createIndex method shortly.

I had to modify his Provider register method to include the host information:

```<code>public function register()
{

    $hosts = [
        [
            'host' => '10.0.2.2', // the host ip from inside vagrant
            'port' => '9200',
            'scheme' => 'http',
            'user' => 'elastic', // yeah I know, change this.
            'pass' => 'changeme' // I will.
        ]
    ];

    $this->app->bind(Elastic::class, function ($app) use ($hosts) {
        return new Elastic(
            ClientBuilder::create()
                ->setHosts($hosts)
                ->build()
        );
    });
}
</code>```

With this, I have Elasticsearch up and running with my laravel project.  On to the indexing.

```<code>$elastic = app(Elastic::class);

// Table Causes has 84 records.
Causes::chunk(100, function ($causes) use ($elastic) {
    foreach ($causes as $cause) {
        $elastic->index([
            'index' => 'pwi',
            'type' => 'cause',
            'id' => $cause->cause_id,
            'body' => $cause->toArray()
        ]);
    }
});

// Table Country has 248 records.
Country::chunk(100, function ($countries) use ($elastic) {
    foreach ($countries as $country) {
        $elastic->index([
            'index' => 'pwi',
            'type' => 'country',
            'id' => $country->country_id,
            'body' => $country->toArray()
        ]);
    }
});
</code>```

These index without issue.  Now the big one.

```<code>// Table Organizations has 47066 records.
Organizations::chunk(5000, function ($organizations) use ($elastic) {
    foreach ($organizations as $organization) {
        $elastic->index([
            'index' => 'pwi',
            'type' => 'organization',
            'id' => $organization->org_id,
            'body' => $organization->toArray()
        ]);
    }
});
</code>```

When I run all three indexes with the above configuration, this is the output I get in the docker console window

```<code> [2017-03-28T19:22:11,305][INFO ][o.e.c.m.MetaDataCreateIndexService] [knre-px] [pwi] creating index, cause [auto(index api)], templates [], shards [5]/[1], mappings []
 [2017-03-28T19:22:11,443][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] create_mapping [cause]
 [2017-03-28T19:22:16,190][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] create_mapping [country]
 [2017-03-28T19:22:16,604][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [country]
 [2017-03-28T19:22:29,088][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] create_mapping [organization]
 [2017-03-28T19:22:29,375][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
 [2017-03-28T19:22:29,453][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
 [2017-03-28T19:22:30,309][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
 [2017-03-28T19:22:30,717][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
 [2017-03-28T19:22:33,247][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
</code>```

For organizations, regardless of the chunk size, it gets to that 5th update mapping, and that is where everything comes to a halt.  Chunks of 10, or chunks of 5000 same result. The browser window is still spinning.  There is never any additional output in the console.  It just sits there, eventually giving me the maximum execution time exceeded error.

I have tried increasing the shard count, using that createIndex method, before I index anything I run:

```<code>$params = [
    'index' => 'pwi',
    'body' => [
        'settings' => [
            'number_of_shards' => 10
        ],
    ]
];

$elastic->createIndex($params);
</code>```

With no changes to the final results.

I was having this error when I started up the docker image:

```<code>max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
</code>```

Running this:
    sudo sysctl -w vm.max_map_count=262144

(https://github.com/docker-library/elasticsearch/issues/111)
Fixed that.

It isn't an issue with the data.  It isn't getting stuck on the same record if the chunk size is 10, and on the next try the chunk size is 5000.

I was using the Elasticquent package (Only I had to use ES 2.4), and had the same issue when I got to indexing the organizations table.  Using chunks of 200 got past it though (Not with the current process though).  I need to search across types, and I cannot find a package that will easily do that so I've decided to do it on my own.  If I cancel the index request, and then start using my search code (not indexing anything, just using what has been indexed) everything works great!

If I were a betting man, I'd say there is something wrong with my configuration.  Or the ES/Docker server.  Unfortunately I don't know what to google.  47k in records is NOT a lot... right?  So what am I missing?

Thanks for reading all of this.  I appreciate any assistance.

[edit]

I changed the code:

```<code>Organizations::chunk(200, function ($organizations) use ($elastic) {
    foreach ($organizations as $organization) {
        $elastic->index([
            'index' => 'pwi',
            'type' => 'organization',
            'id' => $organization->org_id,
            'body' => [
                "org_name" => $organization->org_name,
                "org_desc" => $organization->org_desc,
            ]
        ]);
    }
});
</code>```

And now it it doesn't get past the first create map:

```<code>"elasticsearch/elasticsearch": "^5.1"
</code>```0

答:
Temporary solution was to increase the execution time.

```<code>ini_set('max_execution_time', 600);
</code>```

Is vagrant maybe just that slow?  It took 8 minutes to index those 47k of records.

Either way, this was a solution.  I feel not the best?

Body:
I am trying to index a whole table of about 47k records into elastic search.  This is not a lot of data.  Regardless, I am chunking the records with eloquent and no matter the size of the chunk, by the 5th "update_mapping" of ES console output, everything just stops.

I'm not 100% sure what information you will need to help debug this, so I will try to cover everything.

Laravel 5.2 hosted inside a vagrant machine, running the Scotch-Vagrant image.

I am using the official docker image from elastic search:

docker run -p 9200:9200 -e "http.host=0.0.0.0" -e "transport.host=127.0.0.1" docker.elastic.co/elasticsearch/elasticsearch:5.2.1

To work with ES, I am using their official package.  In my composer.json:

"elasticsearch/elasticsearch": "^5.1"

I used this tutorial to get up and running:
https://michaelstivala.com/learning-elasticsearch-with-laravel/

(Including the "beefed up" wrapper.)

I added a method to his class, as a debugging effor:

public function createIndex($params) {
    return $this->client->indices()->create($params);
}

I'll get to the createIndex method shortly.

I had to modify his Provider register method to include the host information:

public function register()
{

    $hosts = [
        [
            'host' => '10.0.2.2', // the host ip from inside vagrant
            'port' => '9200',
            'scheme' => 'http',
            'user' => 'elastic', // yeah I know, change this.
            'pass' => 'changeme' // I will.
        ]
    ];

    $this->app->bind(Elastic::class, function ($app) use ($hosts) {
        return new Elastic(
            ClientBuilder::create()
                ->setHosts($hosts)
                ->build()
        );
    });
}

With this, I have Elasticsearch up and running with my laravel project.  On to the indexing.

$elastic = app(Elastic::class);

// Table Causes has 84 records.
Causes::chunk(100, function ($causes) use ($elastic) {
    foreach ($causes as $cause) {
        $elastic->index([
            'index' => 'pwi',
            'type' => 'cause',
            'id' => $cause->cause_id,
            'body' => $cause->toArray()
        ]);
    }
});

// Table Country has 248 records.
Country::chunk(100, function ($countries) use ($elastic) {
    foreach ($countries as $country) {
        $elastic->index([
            'index' => 'pwi',
            'type' => 'country',
            'id' => $country->country_id,
            'body' => $country->toArray()
        ]);
    }
});

These index without issue.  Now the big one.

// Table Organizations has 47066 records.
Organizations::chunk(5000, function ($organizations) use ($elastic) {
    foreach ($organizations as $organization) {
        $elastic->index([
            'index' => 'pwi',
            'type' => 'organization',
            'id' => $organization->org_id,
            'body' => $organization->toArray()
        ]);
    }
});

When I run all three indexes with the above configuration, this is the output I get in the docker console window

 [2017-03-28T19:22:11,305][INFO ][o.e.c.m.MetaDataCreateIndexService] [knre-px] [pwi] creating index, cause [auto(index api)], templates [], shards [5]/[1], mappings []
 [2017-03-28T19:22:11,443][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] create_mapping [cause]
 [2017-03-28T19:22:16,190][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] create_mapping [country]
 [2017-03-28T19:22:16,604][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [country]
 [2017-03-28T19:22:29,088][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] create_mapping [organization]
 [2017-03-28T19:22:29,375][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
 [2017-03-28T19:22:29,453][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
 [2017-03-28T19:22:30,309][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
 [2017-03-28T19:22:30,717][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]
 [2017-03-28T19:22:33,247][INFO ][o.e.c.m.MetaDataMappingService] [knre-px] [pwi/Jswi4XuJTyqj56edsNfjfg] update_mapping [organization]

For organizations, regardless of the chunk size, it gets to that 5th update mapping, and that is where everything comes to a halt.  Chunks of 10, or chunks of 5000 same result. The browser window is still spinning.  There is never any additional output in the console.  It just sits there, eventually giving me the maximum execution time exceeded error.

I have tried increasing the shard count, using that createIndex method, before I index anything I run:

$params = [
    'index' => 'pwi',
    'body' => [
        'settings' => [
            'number_of_shards' => 10
        ],
    ]
];

$elastic->createIndex($params);

With no changes to the final results.

I was having this error when I started up the docker image:

max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

Running this:
    sudo sysctl -w vm.max_map_count=262144

(https://github.com/docker-library/elasticsearch/issues/111)
Fixed that.

It isn't an issue with the data.  It isn't getting stuck on the same record if the chunk size is 10, and on the next try the chunk size is 5000.

I was using the Elasticquent package (Only I had to use ES 2.4), and had the same issue when I got to indexing the organizations table.  Using chunks of 200 got past it though (Not with the current process though).  I need to search across types, and I cannot find a package that will easily do that so I've decided to do it on my own.  If I cancel the index request, and then start using my search code (not indexing anything, just using what has been indexed) everything works great!

If I were a betting man, I'd say there is something wrong with my configuration.  Or the ES/Docker server.  Unfortunately I don't know what to google.  47k in records is NOT a lot... right?  So what am I missing?

Thanks for reading all of this.  I appreciate any assistance.

[edit]

I changed the code:

Organizations::chunk(200, function ($organizations) use ($elastic) {
    foreach ($organizations as $organization) {
        $elastic->index([
            'index' => 'pwi',
            'type' => 'organization',
            'id' => $organization->org_id,
            'body' => [
                "org_name" => $organization->org_name,
                "org_desc" => $organization->org_desc,
            ]
        ]);
    }
});

And now it it doesn't get past the first create map:

[2017-03-28T20:00:14,543][INFO ][o.e.c.m.MetaDataCreateIndexService] [eBlAEK7] [pwi] creating index, cause [auto(index api)], templates [], shards [5]/[1], mappings []
[2017-03-28T20:00:14,668][INFO ][o.e.c.m.MetaDataMappingService] [eBlAEK7] [pwi/Fqj91gS9Q6CBfl4z2ZNvXw] create_mapping [organization]

Body:
Temporary solution was to increase the execution time.

ini_set('max_execution_time', 600);

Is vagrant maybe just that slow?  It took 8 minutes to index those 47k of records.

Either way, this was a solution.  I feel not the best?


问:
Check input file size using Flash
I have a multipart html form with a file input element and would like to check the size of the selected file before uploading. I can access the file path using the value attribute, however is it possible to pass that path to a swf and have the swf return the file size or is this blocked by the flash sandbox? Are there any existing projects that already do this? I'd like to avoid replacing my file input element with a flash uploader if possible.</p>

答: Passing file names and accessing it via Flash is security risk. Flash does support a FileReference API, but it requires user input in order to work.</p>

ContentLicense: CC BY-SA 2.5

Title: Check input file size using Flash


问:
Applescript, placing an image in a table cell in InDesign CC 2017
I am attempting to create a script that automatically inputs a tabled/tabular slug at the base of an InDesign page - quite a common query on the internet and thus far have done very well by cobbling together bits of relevant script... Creates table, inputs variables, find page size etc etc...
HOWEVER, I'm stuck when it comes to inputting logo - really want to input my company logo into one of the table cells. Just from Users' HD location.

Does anyone have any tips they could share on this?
Again, this is Applescript for InDesign.

答:
The content of a cell is text. So you need to create a rectangle and insert the image there:

Found this on macscripter a while ago - Modify it to your needs (especially the image bounds - the size/position)

```<code>set placedimage to (choose file) as string

tell application "InDesign CC 2017"
   tell document 1
       tell table 1 of story 1
           tell cell 1
               set NewImage to make new rectangle at insertion point 1 with properties {label:"Photo 1"}
               set ImageBounds to geometric bounds of NewImage
               set geometric bounds of NewImage to {item 1 of ImageBounds, item 2 of ImageBounds, (item 1 of ImageBounds) + 24, (item 2 of ImageBounds) + 18}
           end tell
       end tell
       place placedimage on NewImage
   end tell
end tell
</code>```

Body:
The content of a cell is text. So you need to create a rectangle and insert the image there:

Found this on macscripter a while ago - Modify it to your needs (especially the image bounds - the size/position)

set placedimage to (choose file) as string

tell application "InDesign CC 2017"
   tell document 1
       tell table 1 of story 1
           tell cell 1
               set NewImage to make new rectangle at insertion point 1 with properties {label:"Photo 1"}
               set ImageBounds to geometric bounds of NewImage
               set geometric bounds of NewImage to {item 1 of ImageBounds, item 2 of ImageBounds, (item 1 of ImageBounds) + 24, (item 2 of ImageBounds) + 18}
           end tell
       end tell
       place placedimage on NewImage
   end tell
end tell


问:
Calculate Elapsed time in python in specific format
I am trying to write a program to determine the time and date corresponding to a elapsed number of seconds since 00: 00: 00 on 1 January 2016.

But i wanted my result in specific format.
i.e should be the corresponding hour (in military time), minute, second, day of the month, month name, year, and day of the week name (Sunday – Saturday).
for example,output should look like the following

```<code>23:59:32 2 January 2018 Tuesday
</code>```

i tried to code this

```<code>import time
start = time.time()
#do something
end = time.time()
temp = end-start
print(temp)
hours = temp//3600
temp = temp - 3600*hours
minutes = temp//60
seconds = temp - 60*minutes
print('%d:%d:%d' %(hours,minutes,seconds))
</code>```

But i could only get the hours, minutes and seconds part,
Is there any way i can get the month,year,and week name too ?

Also i'm trying to handle leap years too.since a leap year has 366 days with 29 days in February. Leap years are years that are evenly divisible by 4, with the exception of those evenly divisible by 100 but not 400.

答:
To format a datetime you can use strftime().

```<code>import datetime
my_time = datetime.datetime(year=2018, month=1, day=2, hour=23, minute=59,second=32)
print (my_time.strftime("%X %-d %B %Y %A"))
</code>```

If you want to change the format use this table for reference

Body:
I am trying to write a program to determine the time and date corresponding to a elapsed number of seconds since 00: 00: 00 on 1 January 2016.

But i wanted my result in specific format.
i.e should be the corresponding hour (in military time), minute, second, day of the month, month name, year, and day of the week name (Sunday – Saturday).
for example,output should look like the following

23:59:32 2 January 2018 Tuesday

i tried to code this

import time
start = time.time()
#do something
end = time.time()
temp = end-start
print(temp)
hours = temp//3600
temp = temp - 3600*hours
minutes = temp//60
seconds = temp - 60*minutes
print('%d:%d:%d' %(hours,minutes,seconds))

But i could only get the hours, minutes and seconds part,
Is there any way i can get the month,year,and week name too ?

Also i'm trying to handle leap years too.since a leap year has 366 days with 29 days in February. Leap years are years that are evenly divisible by 4, with the exception of those evenly divisible by 100 but not 400.

Body:
To format a datetime you can use strftime().

import datetime
my_time = datetime.datetime(year=2018, month=1, day=2, hour=23, minute=59,second=32)
print (my_time.strftime("%X %-d %B %Y %A"))

If you want to change the format use this table for reference


问:
linking issue with opencv and ros indigo while trying to install vision_opencv
Hi my question is of two folds.
First, I am confused as why there are opencv3 and OpenCV-3.1.0-dev packages is in /opt/ros/indigo/share as i have read that opencv 2.4.8 is the default version of ROS indigo.

Also, I have opencv 2.4.13 version installed on ubuntu 14.04 with ROS Indigo, I want to use opencv for vision part for my project and for that i tried to install vision_opencv package from source. However when I try to build the package using catkin_make following error occurs

similar question is asked here ROS, opencv3 and CMake - unable to remove the library

```<code>-- ==> add_subdirectory(vision_opencv/image_geometry)
</code>```

CMake Error at /opt/ros/indigo/share/OpenCV-3.1.0-dev/OpenCVModules.cmake:183 (message):
  The imported target "opencv_xobjdetect" references the file

```<code> "/opt/ros/indigo/lib/libopencv_xobjdetect3.so.3.1.0"
</code>```

but this file does not exist.  Possible reasons include:

The file was deleted, renamed, or moved to another location.

An install or uninstall procedure did not complete successfully.

The installation package was faulty and contained

"/opt/ros/indigo/share/OpenCV-3.1.0-dev/OpenCVModules.cmake"

but not all the files it references.

Call Stack (most recent call first):
  /opt/ros/indigo/share/OpenCV-3.1.0-dev/OpenCVConfig.cmake:86 (include)
  vision_opencv/image_geometry/CMakeLists.txt:5 (find_package)

-- Configuring incomplete, errors occurred!
See also "/home/hemang/catkin_ws/build/CMakeFiles/CMakeOutput.log".
See also "/home/hemang/catkin_ws/build/CMakeFiles/CMakeError.log".

What I dont understand is why is it trying to link with Opencv3 when system does not have opencv3 installed or ROS indigo comes with opencv3 now ??

答:
so I figured it out so in the CMakeLists.txt files of both cv_bridge and image_geometry, find package(OpenCV REQUIRED)
should be find package (OpenCV 2.4.13 REQUIRED) . This is in my case as I have OpenCV 2.4.13 installed, one can replace it with any version one is using.

Body:
Hi my question is of two folds.
First, I am confused as why there are opencv3 and OpenCV-3.1.0-dev packages is in /opt/ros/indigo/share as i have read that opencv 2.4.8 is the default version of ROS indigo.

Also, I have opencv 2.4.13 version installed on ubuntu 14.04 with ROS Indigo, I want to use opencv for vision part for my project and for that i tried to install vision_opencv package from source. However when I try to build the package using catkin_make following error occurs

similar question is asked here ROS, opencv3 and CMake - unable to remove the library

-- ==> add_subdirectory(vision_opencv/image_geometry)

CMake Error at /opt/ros/indigo/share/OpenCV-3.1.0-dev/OpenCVModules.cmake:183 (message):
  The imported target "opencv_xobjdetect" references the file

 "/opt/ros/indigo/lib/libopencv_xobjdetect3.so.3.1.0"

but this file does not exist.  Possible reasons include:

The file was deleted, renamed, or moved to another location.

An install or uninstall procedure did not complete successfully.

The installation package was faulty and contained

"/opt/ros/indigo/share/OpenCV-3.1.0-dev/OpenCVModules.cmake"

but not all the files it references.

Call Stack (most recent call first):
  /opt/ros/indigo/share/OpenCV-3.1.0-dev/OpenCVConfig.cmake:86 (include)
  vision_opencv/image_geometry/CMakeLists.txt:5 (find_package)

-- Configuring incomplete, errors occurred!
See also "/home/hemang/catkin_ws/build/CMakeFiles/CMakeOutput.log".
See also "/home/hemang/catkin_ws/build/CMakeFiles/CMakeError.log".

What I dont understand is why is it trying to link with Opencv3 when system does not have opencv3 installed or ROS indigo comes with opencv3 now ??


问:
Beta by Crashlytics app doesn't install
I added myself as a tester for my Android app. Received and opened the email on my Android device. Got to this screen:

Clicked on "Download" and got this:

The problem now:  The "INSTALL" button doesn't work, i.e., it's not clickable.

This was on Nexus 5X Android 7.0.

答: Make sure there aren't any apps drawing to the screen like screen dimming apps (see: https://android.stackexchange.com/questions/69981/why-cant-i-press-the-install-button-when-installing-applications-from-unknown-s).</p>

Title: Beta by Crashlytics app doesn't install


问:
All objects refuse to save c#
I am confused why my checkbox states are not saving. I have done this before on other projects, am I missing some bit of code?

```<code> private void Form1_Load(object sender, EventArgs e)
        {
            materialCheckBox1.Checked = Properties.Settings.Default.CheckBox1;
            materialCheckBox2.Checked = Properties.Settings.Default.CheckBox2;
            materialCheckBox4.Checked = Properties.Settings.Default.CheckBox3;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.CheckBox1 = materialCheckBox1.Checked;
            Properties.Settings.Default.CheckBox2 = materialCheckBox2.Checked;
            Properties.Settings.Default.CheckBox3 = materialCheckBox4.Checked;
            Properties.Settings.Default.Save();
        }
</code>```

答:
I was using Environment.Exit(0); to close instead of Application.Exit();

Why does this occur?

System.Environment.Exit(): Terminates the current process and gives the underlying operating system the specified exit code.

This does NOT Save!

System.Windows.Forms.Application.Exit(): Informs all message loops that they must terminate, and then closes all application windows after the messages have been processed.

https://thestandardoutput.com/posts/terminating-your-c-application/

Title: All objects refuse to save c#

Body:
I am confused why my checkbox states are not saving. I have done this before on other projects, am I missing some bit of code?

 private void Form1_Load(object sender, EventArgs e)
        {
            materialCheckBox1.Checked = Properties.Settings.Default.CheckBox1;
            materialCheckBox2.Checked = Properties.Settings.Default.CheckBox2;
            materialCheckBox4.Checked = Properties.Settings.Default.CheckBox3;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.CheckBox1 = materialCheckBox1.Checked;
            Properties.Settings.Default.CheckBox2 = materialCheckBox2.Checked;
            Properties.Settings.Default.CheckBox3 = materialCheckBox4.Checked;
            Properties.Settings.Default.Save();
        }


问:
how to convert soap response to object
I have an xml file and a matching object definition.

How can i fill an instance of the object with the xml data?

I have registered to get ebay notification, and it sent me an xml in soap format.

How can i listen to this soap request and parse it into its matching object ?

答: You should not need to manipulate XML at all if this is a SOAP web service. See How to Consume a Web Service.</p>

Title: how to convert soap response to object


问:
Loop and Add Data to a Hashtable
I am working with a software list, and the Import-Excel module (Link), trying to create a hash table of software name and version number, with each host exported as its own sheet.  I'm using the Export-MultipleExcelSheets cmdlet within the module.

Here is a sample of what my $Inventory variable looks like:

```
Count Name                      Group
----- ----                      -----
  103 10.105.122.27             {@{Host=10.105.122.27; Name=Update Rollup 10 for Exchange Server 2010 Service Pack 3 (KB3049853); Version=1}, @{Host=10.105.122.27; Name=Update Rollup 14 for Exchange Server 2010 Service Pack 3 (K...
  103 10.105.122.28             {@{Host=10.105.122.28; Name=Update Rollup 10 for Exchange Server 2010 Service Pack 3 (KB3049853); Version=1}, @{Host=10.105.122.28; Name=Update Rollup 14 for Exchange Server 2010 Service Pack 3 (K...
  119 10.105.76.221             {@{Host=10.105.76.221; Name=Update Rollup 10 for Exchange Server 2010 Service Pack 3 (KB3049853); Version=1}, @{Host=10.105.76.221; Name=Update Rollup 15 for Exchange Server 2010 Service Pack 3 (K...
  116 10.105.76.222             {@{Host=10.105.76.222; Name=Update Rollup 15 for Exchange Server 2010 Service Pack 3 (KB3184728); Version=1}, @{Host=10.105.76.222; Name=Update Rollup 16 for Exchange Server 2010 Service Pack 3 (K...
```

Here is the code I am trying to use:

```<code>    Foreach ($I In $Inventory)
    {
        $DataToGather.Add($I.Name, {$I.Group | Select-Object Name, Version})
    }

    Export-MultipleExcelSheets -Show -Autosize -Path "C:\Path\To\Software Inventory.xlsx" $DataToGather
</code>```

I get no errors with this code but it results in 10 sheets with the same software list (I know these machines do not have the same exact software list).

Is there a better way do to what I'm doing?

答:
A ScriptBlock { } might be causing the behaviour that you're seeing, you should change the ScriptBlock { } inside the Add method to Parenthesis ( ) instead.

```<code>Foreach ($I In $Inventory)
{
    # Change the $i.Group section to be surrounded by Parenthesis
    $DataToGather.Add($I.Name, ($I.Group | Select-Object Name, Version))
}
</code>```

If that doesn't work try commenting out the Export-MultupleExcelSheets function and simply returning your $DataToGather variable to see what comes out, this might help you narrow down the problem.

Title: Loop and Add Data to a Hashtable

Body:
I am working with a software list, and the Import-Excel module (Link), trying to create a hash table of software name and version number, with each host exported as its own sheet.  I'm using the Export-MultipleExcelSheets cmdlet within the module.

Here is a sample of what my $Inventory variable looks like:

Count Name                      Group
----- ----                      -----
  103 10.105.122.27             {@{Host=10.105.122.27; Name=Update Rollup 10 for Exchange Server 2010 Service Pack 3 (KB3049853); Version=1}, @{Host=10.105.122.27; Name=Update Rollup 14 for Exchange Server 2010 Service Pack 3 (K...
  103 10.105.122.28             {@{Host=10.105.122.28; Name=Update Rollup 10 for Exchange Server 2010 Service Pack 3 (KB3049853); Version=1}, @{Host=10.105.122.28; Name=Update Rollup 14 for Exchange Server 2010 Service Pack 3 (K...
  119 10.105.76.221             {@{Host=10.105.76.221; Name=Update Rollup 10 for Exchange Server 2010 Service Pack 3 (KB3049853); Version=1}, @{Host=10.105.76.221; Name=Update Rollup 15 for Exchange Server 2010 Service Pack 3 (K...
  116 10.105.76.222             {@{Host=10.105.76.222; Name=Update Rollup 15 for Exchange Server 2010 Service Pack 3 (KB3184728); Version=1}, @{Host=10.105.76.222; Name=Update Rollup 16 for Exchange Server 2010 Service Pack 3 (K...

Here is the code I am trying to use:

    Foreach ($I In $Inventory)
    {
        $DataToGather.Add($I.Name, {$I.Group | Select-Object Name, Version})
    }

    Export-MultipleExcelSheets -Show -Autosize -Path "C:\Path\To\Software Inventory.xlsx" $DataToGather

I get no errors with this code but it results in 10 sheets with the same software list (I know these machines do not have the same exact software list).

Is there a better way do to what I'm doing?

Body:
A ScriptBlock { } might be causing the behaviour that you're seeing, you should change the ScriptBlock { } inside the Add method to Parenthesis ( ) instead.

Foreach ($I In $Inventory)
{
    # Change the $i.Group section to be surrounded by Parenthesis
    $DataToGather.Add($I.Name, ($I.Group | Select-Object Name, Version))
}

If that doesn't work try commenting out the Export-MultupleExcelSheets function and simply returning your $DataToGather variable to see what comes out, this might help you narrow down the problem.


问:
kubernetes transfer Physical IP to dubbo
I want to transfer Physical IP to dubbo pod by yaml,but the parameter is Fixed value.For example:
dubbo.yaml

```<code>spec:
  replicas: 2
  ...
    env:
            - name:  PhysicalIP
              value: 192.168.1.1
</code>```

In pod before start dubbo,i can replay container ip,for example:

```<code>echo "replay /etc/hosts"
cp /etc/hosts /etc/hosts.tmp
sed -i "s/.*$(hostname)/${PhysicalIP}   $(hostname)/" /etc/hosts.tmp
cat /etc/hosts.tmp > /etc/hosts
</code>```

There is an question,when pod deploy to host 192.168.1.1 and host 192.168.1.2,the host 192.168.1.2's pod environment variable ${PhysicalIP} value is 192.168.1.1,I want to ${PhysicalIP} is 192.168.1.2 in host 192.168.1.2,Is there any way?

答:
You should be able to get information about the pod through Environment Variables or using a DownwardAPIVolumeFile.

Using environment variables:

You should add to your yaml something like this:

```<code>env:
  - name: MY_NODE_NAME
    valueFrom:
      fieldRef:
        fieldPath: spec.nodeName
</code>```

As far as I know, the name of the node is, right now, the best approach to what you need that you can get from inside the container.

Using a DownwardAPIVolumeFile:

You should add to your yaml something like this:

```<code>volumes:
  - name: podinfo
    downwardAPI:
      items:
        - path: "nodename"
          fieldRef:
            fieldPath: spec.nodeName
</code>```

This way you will have the information of the node name stored in /etc/nodename

The issue #24657 and the pull #42717, on the kubernetes github are related to this. (Sorry, I need more reputation here to be able to post more links!).

As you can see there, access to the node IP through the downwardAPI should be available soon (using status.hostIP, probably).

Body:
I want to transfer Physical IP to dubbo pod by yaml,but the parameter is Fixed value.For example:
dubbo.yaml

spec:
  replicas: 2
  ...
    env:
            - name:  PhysicalIP
              value: 192.168.1.1

In pod before start dubbo,i can replay container ip,for example:

echo "replay /etc/hosts"
cp /etc/hosts /etc/hosts.tmp
sed -i "s/.*$(hostname)/${PhysicalIP}   $(hostname)/" /etc/hosts.tmp
cat /etc/hosts.tmp > /etc/hosts

There is an question,when pod deploy to host 192.168.1.1 and host 192.168.1.2,the host 192.168.1.2's pod environment variable ${PhysicalIP} value is 192.168.1.1,I want to ${PhysicalIP} is 192.168.1.2 in host 192.168.1.2,Is there any way?

Body:
You should be able to get information about the pod through Environment Variables or using a DownwardAPIVolumeFile.

Using environment variables:

You should add to your yaml something like this:

env:
  - name: MY_NODE_NAME
    valueFrom:
      fieldRef:
        fieldPath: spec.nodeName

As far as I know, the name of the node is, right now, the best approach to what you need that you can get from inside the container.

Using a DownwardAPIVolumeFile:

You should add to your yaml something like this:

volumes:
  - name: podinfo
    downwardAPI:
      items:
        - path: "nodename"
          fieldRef:
            fieldPath: spec.nodeName

This way you will have the information of the node name stored in /etc/nodename

The issue #24657 and the pull #42717, on the kubernetes github are related to this. (Sorry, I need more reputation here to be able to post more links!).

As you can see there, access to the node IP through the downwardAPI should be available soon (using status.hostIP, probably).


问:
Error using ServiceStack.Text to deserialize derived generic type
I'm using ServiceStack.Text to serialize/deserialize objects before storing them in Redis, but i've come across some objects, that won't deserialize as expected.

I have a base type (bit of legacy code, with many projects using this base type) with a property of type object. Later a generic version of the base type have been added, exposing the property as a generic type.

Using ServiceStack.Text to serialize and deserialize the generic type sets the property on the base class (type object) and not the more specific type on the derived class.

A simple console app to reproduce the errors goes something like this:

```<code>class Program
{
    public class Base<T> : Base
    {
        //hide the Value property on the base class
        public new T Value { get; set; }
    }

    public class Base
    {
        public object Value { get; set; }
    }

    static void Main(string[] args)
    {
        var a = new Base<List<string>>()
        {
            Value = new List<string>() { "one", "two", "three" },
        };

        var serialized = TypeSerializer.SerializeToString(a);
        var deserialized = TypeSerializer.DeserializeFromString<Base<List<string>>>(serialized);

        //throws a null ref exception
        Console.WriteLine(deserialized.Value.Count);
    }
}
</code>```

Setting a breakpoint after deserialization, Visual Studio shows the object with base.Value as the List<string> with the value of the serialized list, but the Value property on my Base<List<String>> class is null.

Screenshot of debugger in Visual Studio

Is there any way to configure TypeSerializer (or JsonSerializer) to correctly set to more specific property instead of the property on the base class?

Any help is appreciated.

Update

Based on the answer, i solved it by making the Base<T> and Base inherit from a new abstract base class, like so:

```<code>public abstract class DummyBase
{
    public string Test { get; set; } = "Test";
}

public class BaseResponse<T> : DummyBase
{
    public T Value { get; set; }
}

public class BaseResponse : DummyBase
{
    public object Value { get; set; }
}
</code>```

答:
Even though Base.Value is hidden, it's still visible to reflection (eg with a.GetType().GetProperties(). That could be the problem.

The following seems to work. The getters and setters in Base<T> just wrap Base.Value. DummyBase<T> is necessary to get ServiceStack to deserialize the string to the correct type.

```<code>class Program
{
    public static void Main (string[] args)
    {
        var a = new Base<List<string>>()
        {
            Value = new List<string> { "one", "two", "three" },
        };

        var serialized = TypeSerializer.SerializeToString(a);
        var deserialized = TypeSerializer.DeserializeFromString<DummyBase<List<string>>>(serialized);

        // no longer throws a null ref exception
        Console.WriteLine(deserialized.Value.Count);
    }
}

public class DummyBase<T>
{
    public T Value { get; set; }
}

public class Base<T> : Base
{
    public new T Value
    {
        get { return (T)base.Value; }
        set { base.Value = value; }
    }
}

public class Base
{
    public object Value { get; set; }
}
</code>```

Of course, all this wouldn't be necessary if Base<T> didn't inherit from Base.

Body:
I'm using ServiceStack.Text to serialize/deserialize objects before storing them in Redis, but i've come across some objects, that won't deserialize as expected.

I have a base type (bit of legacy code, with many projects using this base type) with a property of type object. Later a generic version of the base type have been added, exposing the property as a generic type.

Using ServiceStack.Text to serialize and deserialize the generic type sets the property on the base class (type object) and not the more specific type on the derived class.

A simple console app to reproduce the errors goes something like this:

class Program
{
    public class Base<T> : Base
    {
        //hide the Value property on the base class
        public new T Value { get; set; }
    }

    public class Base
    {
        public object Value { get; set; }
    }

    static void Main(string[] args)
    {
        var a = new Base<List<string>>()
        {
            Value = new List<string>() { "one", "two", "three" },
        };

        var serialized = TypeSerializer.SerializeToString(a);
        var deserialized = TypeSerializer.DeserializeFromString<Base<List<string>>>(serialized);

        //throws a null ref exception
        Console.WriteLine(deserialized.Value.Count);
    }
}

Setting a breakpoint after deserialization, Visual Studio shows the object with base.Value as the List<string> with the value of the serialized list, but the Value property on my Base<List<String>> class is null.

Screenshot of debugger in Visual Studio

Is there any way to configure TypeSerializer (or JsonSerializer) to correctly set to more specific property instead of the property on the base class?

Any help is appreciated.

Update

Based on the answer, i solved it by making the Base<T> and Base inherit from a new abstract base class, like so:

public abstract class DummyBase
{
    public string Test { get; set; } = "Test";
}

public class BaseResponse<T> : DummyBase
{
    public T Value { get; set; }
}

public class BaseResponse : DummyBase
{
    public object Value { get; set; }
}

Body:
Even though Base.Value is hidden, it's still visible to reflection (eg with a.GetType().GetProperties(). That could be the problem.

The following seems to work. The getters and setters in Base<T> just wrap Base.Value. DummyBase<T> is necessary to get ServiceStack to deserialize the string to the correct type.

class Program
{
    public static void Main (string[] args)
    {
        var a = new Base<List<string>>()
        {
            Value = new List<string> { "one", "two", "three" },
        };

        var serialized = TypeSerializer.SerializeToString(a);
        var deserialized = TypeSerializer.DeserializeFromString<DummyBase<List<string>>>(serialized);

        // no longer throws a null ref exception
        Console.WriteLine(deserialized.Value.Count);
    }
}

public class DummyBase<T>
{
    public T Value { get; set; }
}

public class Base<T> : Base
{
    public new T Value
    {
        get { return (T)base.Value; }
        set { base.Value = value; }
    }
}

public class Base
{
    public object Value { get; set; }
}

Of course, all this wouldn't be necessary if Base<T> didn't inherit from Base.


问:
I'm trying to copy the active worksheet to the end of the workbook
All is working well, but I need the values copied, not the formulas. Also the formatting of the worksheet. This is what I have:

```<code>Dim strName As String, strSht As String
strName = "DMR" & " " & Range("S1").Value
strSht = ActiveSheet.Name

Application.ScreenUpdating = False
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = strName
Sheets(strSht).Range("A1:Y89").Copy
Sheets(strName).Range("A1").PasteSpecial Paste:=xlPasteValues
</code>```

This doesn't do what I am trying to accomplish. Some cells in the active worksheet being copied, have formulas in them. I need to copy the values of the formulas, along with the formatting of the sheet. Can anyone help? I'm using Excel 2013. TIA...

答:
There is a known peculiarity when pasting Unions of discontiguous cells that you end up pasting Values and Formats. Excel cannot resolve the relational cell addresses of a discontiguous range of formulas so it opts for the values and carries the formats along for the ride.

```<code>Dim strName As String, strSht As String

strName = "DMR" & " " & Range("S1").Value
strSht = ActiveSheet.Name

Application.ScreenUpdating = False
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = strName
Sheets(strSht).Range("A1:Y89, Y91").Copy Destination:=Sheets(strName).Range("A1")
</code>```

The above adds (what I beieve to be a blank, unused cell) Y91 to the original copy range to create a discontiguous union of cells. You will end up with the values and formats with no formulas.

Body:
All is working well, but I need the values copied, not the formulas. Also the formatting of the worksheet. This is what I have:

Dim strName As String, strSht As String
strName = "DMR" & " " & Range("S1").Value
strSht = ActiveSheet.Name

Application.ScreenUpdating = False
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = strName
Sheets(strSht).Range("A1:Y89").Copy
Sheets(strName).Range("A1").PasteSpecial Paste:=xlPasteValues

This doesn't do what I am trying to accomplish. Some cells in the active worksheet being copied, have formulas in them. I need to copy the values of the formulas, along with the formatting of the sheet. Can anyone help? I'm using Excel 2013. TIA...

Body:
There is a known peculiarity when pasting Unions of discontiguous cells that you end up pasting Values and Formats. Excel cannot resolve the relational cell addresses of a discontiguous range of formulas so it opts for the values and carries the formats along for the ride.

Dim strName As String, strSht As String

strName = "DMR" & " " & Range("S1").Value
strSht = ActiveSheet.Name

Application.ScreenUpdating = False
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = strName
Sheets(strSht).Range("A1:Y89, Y91").Copy Destination:=Sheets(strName).Range("A1")

The above adds (what I beieve to be a blank, unused cell) Y91 to the original copy range to create a discontiguous union of cells. You will end up with the values and formats with no formulas.


问:
Visiualize and analyze relations of classes in c++ project
which free tool to use for getting visualized representation classes in c++ project?</p>

答:
http://www.cppdepend.com/

You can download a trial version.


问:
Setting starting (left) bounding of X NumberAxis in LineChart
I am having problems making my LineChart's X NumberAxis display it's Series/Data starting from some left (starting) value.

As above: All my data is ascending for X axis starting with 50000. How can I make the chart also start at 50000?

I've tried: xAxis.setLowerBound(50000); but it didn't work.

Is there maybe some specific time this value should be set?

Additional note: Series is created along with LineChart, the data is added later over time to the Series (ascending order).

答: As said in @James_D 's comment setForceZeroInRange(false); worked.


问:
Error writing to csv
I'm attempting to write a data frame to csv but it seems to be complaining because the columns contain lists.

I want to be able to do is access this data frame and call it into R at a later time. I don't care how to accomplish this (save as a text file etc).  This is a fairly large data set n=182305.  Any ideas to write it to a file that I can fairly quickly read into R (I'm not married to a csv file)

DATA Frame & the Code I've Tried

```<code>DF2<-structure(list(word = c("3-D", "4-F", "4-H'er", "4-H", "A battery",
"a bon march"), pos.code = c("AN", "N", "N", "A", "h", "v"),
    pos = list(c("A", "N"), "N", "N", "A", "h", "v"), noun = list(
        TRUE, TRUE, TRUE, FALSE, FALSE, FALSE), plural = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), noun.phrase = list(
        FALSE, FALSE, FALSE, FALSE, TRUE, FALSE), verb.usually.participle = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), transitive.verb = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), intransitive.verb = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), adjective = list(
        TRUE, FALSE, FALSE, TRUE, FALSE, FALSE), adverb = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, TRUE), conjunction = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), preposition = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), interjection = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), pronoun = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), definite.article = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), indefinite.article = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), nominative = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)), .Names = c("word",
"pos.code", "pos", "noun", "plural", "noun.phrase", "verb.usually.participle",
"transitive.verb", "intransitive.verb", "adjective", "adverb",
"conjunction", "preposition", "interjection", "pronoun", "definite.article",
"indefinite.article", "nominative"), row.names = c(NA, 6L), class = "data.frame")

write.table(DF2, file = "mobyPOS.csv", sep = " ", col.names = TRUE,qmethod = "double")
</code>```

Error message I got:

```<code>> write.table(DF2, file = "mobyPOS.csv", sep = " ", col.names = TRUE,qmethod = "double")
Error in write.table(x, file, nrow(x), p, rnames, sep, eol, na, dec, as.integer(quote),  :
  unimplemented type 'list' in 'EncodeElement'
</code>```

答: maybe convert to characters then save? DF2$pos <- as.character(DF2$pos)

Title: Error writing to csv

Body:
I'm attempting to write a data frame to csv but it seems to be complaining because the columns contain lists.

I want to be able to do is access this data frame and call it into R at a later time. I don't care how to accomplish this (save as a text file etc).  This is a fairly large data set n=182305.  Any ideas to write it to a file that I can fairly quickly read into R (I'm not married to a csv file)

DATA Frame & the Code I've Tried

DF2<-structure(list(word = c("3-D", "4-F", "4-H'er", "4-H", "A battery",
"a bon march"), pos.code = c("AN", "N", "N", "A", "h", "v"),
    pos = list(c("A", "N"), "N", "N", "A", "h", "v"), noun = list(
        TRUE, TRUE, TRUE, FALSE, FALSE, FALSE), plural = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), noun.phrase = list(
        FALSE, FALSE, FALSE, FALSE, TRUE, FALSE), verb.usually.participle = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), transitive.verb = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), intransitive.verb = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), adjective = list(
        TRUE, FALSE, FALSE, TRUE, FALSE, FALSE), adverb = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, TRUE), conjunction = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), preposition = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), interjection = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), pronoun = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), definite.article = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), indefinite.article = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), nominative = list(
        FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)), .Names = c("word",
"pos.code", "pos", "noun", "plural", "noun.phrase", "verb.usually.participle",
"transitive.verb", "intransitive.verb", "adjective", "adverb",
"conjunction", "preposition", "interjection", "pronoun", "definite.article",
"indefinite.article", "nominative"), row.names = c(NA, 6L), class = "data.frame")

write.table(DF2, file = "mobyPOS.csv", sep = " ", col.names = TRUE,qmethod = "double")

Error message I got:

> write.table(DF2, file = "mobyPOS.csv", sep = " ", col.names = TRUE,qmethod = "double")
Error in write.table(x, file, nrow(x), p, rnames, sep, eol, na, dec, as.integer(quote),  :
  unimplemented type 'list' in 'EncodeElement'


问:
How to render ggplot chart when button update is pressed?
I would like to have this chart to rerender only when I press on button updt. This is the code I have so far

```<code>---
title: ""
author:
output:
  flexdashboard::flex_dashboard:
    storyboard: true

runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(ggplot2)
library(dplyr)
```

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

```{r}
actionButton('updt', 'Update chart')
checkboxGroupInput('gear', 'number of gears', unique(mtcars$gear), (mtcars$gear))
observeEvent( eventExpr = input$updt , handlerExpr = {
  renderPlot({
    dd <- mtcars %>% filter(gear %in% input$gear)
    f1 <- ggplot(aes(mpg, disp), data=dd) + geom_point()
    f1
  })

})

```
</code>```

答:
According to ?observeEvent:

observeEvent returns an observer reference class object

This can not be plotted.

You could do something like:

```<code>observeEvent( eventExpr = input$updt , handlerExpr = {
  output$myplot <- renderPlot({
    dd <- mtcars %>% filter(gear %in% isolate(input$gear))
    f1 <- ggplot(aes(mpg, disp), data=dd) + geom_point()
    f1
  })
})
plotOutput("myplot")
</code>```

but still you have to isolate(input$gear) as output$myplot is reactive to input$gear

So the best is to remove the observeEvent, add req(input$updt) to make  renderPlot reactive to it and isolate(input$gear):

```<code>renderPlot({
    req(input$updt)
    dd <- mtcars %>% filter(gear %in% isolate(input$gear))
    f1 <- ggplot(aes(mpg, disp), data=dd) + geom_point()
    f1
  })
</code>```

Body:
I would like to have this chart to rerender only when I press on button updt. This is the code I have so far

---
title: ""
author:
output:
  flexdashboard::flex_dashboard:
    storyboard: true

runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(ggplot2)
library(dplyr)
```

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

```{r}
actionButton('updt', 'Update chart')
checkboxGroupInput('gear', 'number of gears', unique(mtcars$gear), (mtcars$gear))
observeEvent( eventExpr = input$updt , handlerExpr = {
  renderPlot({
    dd <- mtcars %>% filter(gear %in% input$gear)
    f1 <- ggplot(aes(mpg, disp), data=dd) + geom_point()
    f1
  })

})

```

Body:
According to ?observeEvent:

observeEvent returns an observer reference class object

This can not be plotted.

You could do something like:

observeEvent( eventExpr = input$updt , handlerExpr = {
  output$myplot <- renderPlot({
    dd <- mtcars %>% filter(gear %in% isolate(input$gear))
    f1 <- ggplot(aes(mpg, disp), data=dd) + geom_point()
    f1
  })
})
plotOutput("myplot")

but still you have to isolate(input$gear) as output$myplot is reactive to input$gear

So the best is to remove the observeEvent, add req(input$updt) to make  renderPlot reactive to it and isolate(input$gear):

renderPlot({
    req(input$updt)
    dd <- mtcars %>% filter(gear %in% isolate(input$gear))
    f1 <- ggplot(aes(mpg, disp), data=dd) + geom_point()
    f1
  })


问:
mingw64 shell perl CPAN does not work for any module
```<code>$ perl -MCPAN -e 'install XML::Simple'

Reading '/u/.cpan/Metadata'
  Database was generated on Fri, 14 Oct 2016 19:29:02 GMT
Running install for module 'XML::Simple'
Checksum for /u/.cpan/sources/authors/id/G/GR/GRANTM/XML-Simple-2.22.tar.gz ok
directory tmp-9128 changed before chdir, expected dev=235194353 ino=7590237479028601933, actual dev=235194353 ino=15919093302750535503, aborting. at /usr/share/perl5/core_perl/CPAN/Distribution.pm line 623.
</code>```

Please suggest any solution, even manually download and install is not working.

答: After much discussion found no solution to this and it seems the Mingw/git bash shell does not support all the CPAN modules, even though the same works fine from Linux boxes and I was able to use it from local Virtual Box setup.</p>

Body:
$ perl -MCPAN -e 'install XML::Simple'

Reading '/u/.cpan/Metadata'
  Database was generated on Fri, 14 Oct 2016 19:29:02 GMT
Running install for module 'XML::Simple'
Checksum for /u/.cpan/sources/authors/id/G/GR/GRANTM/XML-Simple-2.22.tar.gz ok
directory tmp-9128 changed before chdir, expected dev=235194353 ino=7590237479028601933, actual dev=235194353 ino=15919093302750535503, aborting. at /usr/share/perl5/core_perl/CPAN/Distribution.pm line 623.

Please suggest any solution, even manually download and install is not working.


问:
Best practice to communicate with Elastic in an application
It will be first time I am going to use Elastic in production.

For databases, I use repository pattern, for example concrete classes of IOrderRepository, IFacetRepository uses SQL and Mongo drivers to communicate with db.

The application is going to get all the products from Elastic, and I use Elastic REST Api to get data.

What can be the best practice to represent elastic provider(?) in code base?

I can continue using Repository pattern,and create ProductRepository that uses ElasticClient and make http calls, but I feel it is not a perfect solution.

I also can't create ProductService as I don't want any business in the code.
Single responsibility is getting the products from elastic, that's all.

May be mediator pattern is the right way to implement.

What do you suggest?

答:
I'd go with a ProductRepository that uses ElasticClient internally:

A Repository is an interface to a database and its clients needn't know if its implementation talks to an Relational DB, MongoDB or Elasticsearch. This is exactly what you'd achieve by creating a ProductRepository class.

If, in future, you move from Elasticsearch to another database, such as DynamoDB, you just need to change ProductRepository and its clients won't care.

Be wary of Mediator pattern, as you can end up with God objects over time.


问:
Using javax.mail to send to multiple recipients
I've got the following...

```<code>msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
</code>```

Which works fine but when I attempt to add this multiple times (with different variables for to) it only sends to the last statement. I've also attempted sending something like email1@gmail.com :email2@gmail.com as the to variable but this throws back an error.

Does anyone have any suggestions as to how I'd send mail to multiple recipients using JUST one e-mail and not multiple e-mails using javax.mail?

答: msg.setRecipients() takes an array of addresses as the second parameter.

Body:
I've got the following...

msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

Which works fine but when I attempt to add this multiple times (with different variables for to) it only sends to the last statement. I've also attempted sending something like email1@gmail.com :email2@gmail.com as the to variable but this throws back an error.

Does anyone have any suggestions as to how I'd send mail to multiple recipients using JUST one e-mail and not multiple e-mails using javax.mail?


问:
How to set up online directory that two servers can access?
I have a very weird, but specific situation. I use XAMPP localhost on my mac, call it server1, and heroku running a php app, call it server2. I need to move a txt file from server1 to server2 (at regular intervals as the txt constantly updates). I cannot use PHP's ftp as heroku doesn't like that. I have no idea how to do this.

I have come up with a plan to somehow get the txt from server1 to an online 'directory' that the app on server2 can access, but I have no idea how to do this, or if this is even possible? Is there a better way to transfer the file? Should I not be using heroku for this in the first place?

答:
Heroku is great for running PHP apps, but it has an ephemeral filesystem. It's not build to upload files and store them on the "server".
(https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem)

If you deploy a new version of your app to Heroku, the uploaded file will be removed. If you don't mind uploading the file again, simply push it to your PHP app running on Heroku using a POST request.

If you want to save it more reliable, think about using a storage service like AWS S3.


问:
Search a text file for two strings and display how many strings are in between
How can I use Binary search in Java to find how many strings lie between the two strings given by the user? I have a large text file to search through.
I was thinking ((word position 2 - word position 1)-1) would give the position from an array but I am not quite sure how to put it into code. I got stuck after checking the file for the words.</p>

```<code>String[] allWords = new String[400000];
        int wordCount = 0;
    Scanner input = new Scanner(new File("C:\\text.txt"));
        while (input.hasNext()) {
    String word = input.next();
    allWords[wordCount] = word;
    wordCount++;

    System.out.println(wordCount);
}

    Scanner sc = new Scanner(new File("C:\\text.txt"));
    while(sc.hasNextLine()){
    String in = sc.nextLine();

    System.out.println("Enter a string:");
    Scanner sc2 = new Scanner(System.in);
    String str = sc2.nextLine();

    System.out.println("Enter a string:");
    Scanner sc3 = new Scanner(System.in);
    String str2 = sc3.nextLine();

    if (str.contains(str)) {
    System.out.println("yes");
}
    if (str.contains(str2)) {
    System.out.println("yes");

    }
</code>```

答:
You could try something like this pseudocode.</p>

```<code>int start
int end
a = startingString
b = startingString

String[] lines  = StringFromFile.split("\n");

for(x in lines)
    if(x=a)
        start = position of x
for(x in lines)
    if(x=b)
        end = position of x
String[] newLines = Arrays.copyOfRange(lines, start,end)
return newLines.length
</code>```

Body:
How can I use Binary search in Java to find how many strings lie between the two strings given by the user? I have a large text file to search through.
I was thinking ((word position 2 - word position 1)-1) would give the position from an array but I am not quite sure how to put it into code. I got stuck after checking the file for the words.

String[] allWords = new String[400000];
        int wordCount = 0;
    Scanner input = new Scanner(new File("C:\\text.txt"));
        while (input.hasNext()) {
    String word = input.next();
    allWords[wordCount] = word;
    wordCount++;

    System.out.println(wordCount);
}

    Scanner sc = new Scanner(new File("C:\\text.txt"));
    while(sc.hasNextLine()){
    String in = sc.nextLine();

    System.out.println("Enter a string:");
    Scanner sc2 = new Scanner(System.in);
    String str = sc2.nextLine();

    System.out.println("Enter a string:");
    Scanner sc3 = new Scanner(System.in);
    String str2 = sc3.nextLine();

    if (str.contains(str)) {
    System.out.println("yes");
}
    if (str.contains(str2)) {
    System.out.println("yes");

    }

Body:
You could try something like this pseudocode.

int start
int end
a = startingString
b = startingString

String[] lines  = StringFromFile.split("\n");

for(x in lines)
    if(x=a)
        start = position of x
for(x in lines)
    if(x=b)
        end = position of x
String[] newLines = Arrays.copyOfRange(lines, start,end)
return newLines.length


问:
What is the maximum length for an ENUM value?
Searched the docs, but to no avail.

What is the maximum length for an enumeration value, i.e. the string literal?

答:
The limit isn't on the length of the literal string, but rather on the table definition.

The MySQL documentation states that

Each table has an .frm file that contains the table definition. The server uses the following expression to check some of the table information stored in the file against upper limit of 64KB.

which is then followed by an ad-hoc equation expressing the approximate size of a table definition.

For a simple test, in a table with a couple fields already, I got my enum up to 63136 characters long, and the .frm was 71775 bytes big (slightly larger than 70KB), so the limit is approximate.  At that point, MySQL complained #1117 - Too many columns, which is misleading to say the least.

Interestingly/oddly/worthwhile to note, the character set of the enum will change the maximum length. -- even if you're using normal characters which should only require 1 byte each.


问:
Looping through a column to move cells with font size 10 down one row
I have section title cells set at 10 pt font while all other data is set at 9 point font in column A.  I am trying to write a vba macro to loop through column A to move each title cell down one row(because the csv leaves a blank cell below them) then move on to the next title cell in the column.  Here is my attempt but I'm not sure what I'm doing wrong here.</p>

```<code>Sub FontSpacing()
    Dim Fnt As Range

  For Each Fnt In Range("A8:A5000")
      If Fnt.Font.Size = "10" Then
       ActiveCell.Cut Destination:=ActiveCell.Offset(",1")
  End If
Next
</code>```

答:
Not sure if you meant 1 Row below or 1 Column right so:

To shift 1 Column:

```<code>Sub FontSpacing()
Dim rng As Range, cell As Range
Set rng = Range("A1:A5000")
For Each cell In rng
    If cell.Font.Size = "10" Then
        cell.Offset(0, 1).Value = cell.Value
        cell.Clear
    End If
Next
End Sub
</code>```

To shift 1 Row:

```<code>Sub FontSpacing()
Dim rng As Range, cell As Range
Set rng = Range("A1:A5000")
For Each cell In rng
    If cell.Font.Size = "10" Then
        a = cell.Row + 1
        Rows(a & ":" & a).Insert Shift:=xlDown, CopyOrigin:=1
        cell.Offset(1, 0).Value = cell.Value
        cell.Offset(1, 0).Font.Size = "11"
        cell.Clear
    End If
Next
End Sub
</code>```

Body:
I have section title cells set at 10 pt font while all other data is set at 9 point font in column A.  I am trying to write a vba macro to loop through column A to move each title cell down one row(because the csv leaves a blank cell below them) then move on to the next title cell in the column.  Here is my attempt but I'm not sure what I'm doing wrong here.

Sub FontSpacing()
    Dim Fnt As Range

  For Each Fnt In Range("A8:A5000")
      If Fnt.Font.Size = "10" Then
       ActiveCell.Cut Destination:=ActiveCell.Offset(",1")
  End If
Next

Body:
Not sure if you meant 1 Row below or 1 Column right so:

To shift 1 Column:

Sub FontSpacing()
Dim rng As Range, cell As Range
Set rng = Range("A1:A5000")
For Each cell In rng
    If cell.Font.Size = "10" Then
        cell.Offset(0, 1).Value = cell.Value
        cell.Clear
    End If
Next
End Sub

To shift 1 Row:

Sub FontSpacing()
Dim rng As Range, cell As Range
Set rng = Range("A1:A5000")
For Each cell In rng
    If cell.Font.Size = "10" Then
        a = cell.Row + 1
        Rows(a & ":" & a).Insert Shift:=xlDown, CopyOrigin:=1
        cell.Offset(1, 0).Value = cell.Value
        cell.Offset(1, 0).Font.Size = "11"
        cell.Clear
    End If
Next
End Sub


问:
How to register MessageBodyWriter and MessageBodyReader in Jersey 2.x
I am implementing RESTful services using jersey api and I've come know that I need to register the custom xmlWriter and xmlReader. Client code implements MessageBodyWriter and I need to know ho0w to register it in server side because I am getting MessageBodyProviderNotFoundException for media type application/xml.

MessageBodyWriter code

```<code>public class SendDocumentsServiceRequestXMLWriter extends BaseMessageBodyWriter implements MessageBodyWriter<SendDocumentsRequest> {

public boolean isWriteable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) {
    return type == SendDocumentsRequest.class && !mediaType.isWildcardType()
            && !mediaType.isWildcardSubtype() && mediaType.isCompatible( MediaType.valueOf( "application/xml" ) );
}

public long getSize( SendDocumentsRequest t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) {
    return 0;
}

public void writeTo( SendDocumentsRequest t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ) throws IOException, WebApplicationException {
    try {
        ESignatureClientJAXBContextFactory.getMarshaller( SendDocumentsRequest.class ).marshal( t, entityStream );
    } catch (Exception e) {
        throw new ESignatureClientException( e );
    }
}
</code>```

}

How can I register this class so that Jersey picks it up?

Thanks

答:
put @Provider on your implementation class along with @Produces or @Consumes depending on Writer or Reader.

Here's a example:http://memorynotfound.com/jax-rs-messagebodywriter/

Body:
I am implementing RESTful services using jersey api and I've come know that I need to register the custom xmlWriter and xmlReader. Client code implements MessageBodyWriter and I need to know ho0w to register it in server side because I am getting MessageBodyProviderNotFoundException for media type application/xml.

MessageBodyWriter code

public class SendDocumentsServiceRequestXMLWriter extends BaseMessageBodyWriter implements MessageBodyWriter<SendDocumentsRequest> {

public boolean isWriteable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) {
    return type == SendDocumentsRequest.class && !mediaType.isWildcardType()
            && !mediaType.isWildcardSubtype() && mediaType.isCompatible( MediaType.valueOf( "application/xml" ) );
}

public long getSize( SendDocumentsRequest t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType ) {
    return 0;
}

public void writeTo( SendDocumentsRequest t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream ) throws IOException, WebApplicationException {
    try {
        ESignatureClientJAXBContextFactory.getMarshaller( SendDocumentsRequest.class ).marshal( t, entityStream );
    } catch (Exception e) {
        throw new ESignatureClientException( e );
    }
}

}

How can I register this class so that Jersey picks it up?

Thanks


问:
How can I test the file type (ascii, binary, etc) of git objects?
I want to find all the files in a given git branch that are ascii/text, from a bare git repository, and add up their total size.

Since this is a bare repo, it has no working tree and the solution of simply checking out the branch and testing the files directly will not work. There may be hundreds of these repositories totalling hundreds of GB and they are read-only for the purposes of this task. This means that creating a working tree is not an option, and the size of repositories means making a copy of each one and creating a working tree in the copy is impractical.

I can list all the objects belonging to a particular branch in a bare git repository like so:

```<code>git ls-tree -r master --long
</code>```

This gives me the object hash:

```<code>100644 blob 486a23256c437b811b5647e40517a35964f60dc6      42    file1.txt
100644 blob f7b528c3a1412c12213e56394b679397bd4ecaa7     131    file2.xml
100644 blob 773c90bbb7ab5552d47ce2fb153fc9d18ed0d386    5617    file3.jpg
100644 blob 420cb792e80a97c89db9c9d7339b4fb9a680aa43   13130    file3.zip
</code>```

In the above example I want to get only the first two plaintext objects but I don't know how to test an object itself for a file type.

答:
Git itself does not distinguish between text and binary files. Many of the front-end porcelain tools do, but internally there isn’t a difference. The best way to figure out which is which is to use a non-git-based tool, file. To get the contents to send in to file, you can use git show. For example, if you ran git show 486a23256c437b811b5647e40517a35964f60dc6 | file -, you might get /dev/stdin: ASCII text. If you ran git show f7b528c3a1412c12213e56394b679397bd4ecaa7 | file -, you might get /dev/stdin: XML 1.0 document text.

In general, file tries to make anything that looks like plain text have the word text somewhere in the output, and nothing that does not look like text. More specifically, the man page for file says:

The type printed will usually contain one of the words text (the file contains only printing characters and a few common control characters and is probably safe to read on an ASCII terminal), executable (the file contains the result of compiling a program in a form understandable to some UNIX kernel or another), or data meaning anything else (data is usually ‘binary’ or non-printable). Exceptions are well-known file formats (core files, tar archives) that are known to contain binary data.

So, if you pipe the output of git show through file, and then look for text in the output, you should be able to determine if it’s text or binary.

Body:
I want to find all the files in a given git branch that are ascii/text, from a bare git repository, and add up their total size.

Since this is a bare repo, it has no working tree and the solution of simply checking out the branch and testing the files directly will not work. There may be hundreds of these repositories totalling hundreds of GB and they are read-only for the purposes of this task. This means that creating a working tree is not an option, and the size of repositories means making a copy of each one and creating a working tree in the copy is impractical.

I can list all the objects belonging to a particular branch in a bare git repository like so:

git ls-tree -r master --long

This gives me the object hash:

100644 blob 486a23256c437b811b5647e40517a35964f60dc6      42    file1.txt
100644 blob f7b528c3a1412c12213e56394b679397bd4ecaa7     131    file2.xml
100644 blob 773c90bbb7ab5552d47ce2fb153fc9d18ed0d386    5617    file3.jpg
100644 blob 420cb792e80a97c89db9c9d7339b4fb9a680aa43   13130    file3.zip

In the above example I want to get only the first two plaintext objects but I don't know how to test an object itself for a file type.


问:
Pandas: attribute_error when converting timestamps to EST
Consider this simple example

```<code>idx2=[pd.to_datetime('2016-08-31 22:08:12') ,
     pd.to_datetime('2016-08-31 22:08:12'),
     pd.to_datetime(np.NaN)]

test2=pd.DataFrame({'value':[1,1,3], 'groups' : ['A',np.NaN,'A']},index=idx2)
test2.reset_index(inplace = True)

test2
Out[29]:
                index groups  value
0 2016-08-31 22:08:12      A      1
1 2016-08-31 22:08:12    NaN      1
2                 NaT      A      3
</code>```

I would like to convert the column index to EST, but this

```<code>test2['index'].map(lambda x: x.tz_localize('UTC').tz_convert('US/Eastern').tz_localize(None))
</code>```

gives me

AttributeError: 'NaTType' object has no attribute 'tz_localize'

Using x[x.notnull()] does not work either. what can I do?

答:
No need to use reset_index, instead just operate directly on the DatetimeIndex which has tz_localize and tz_convert built-in:

```<code>test2.index = test2.index.tz_localize('UTC').tz_convert('US/Eastern').tz_localize(None)
</code>```

The resulting output:

```<code>                    groups  value
2016-08-31 18:08:12      A      1
2016-08-31 18:08:12    NaN      1
NaT                      A      3
</code>```

As noted by @DSM, you can use the .dt accessor if you want to do this on a column, but you'll need to use 3 instances of .dt, one before each timezone operation:

```<code>test2.reset_index(inplace=True)
test2['index'] = test2['index'].dt.tz_localize('UTC').dt.tz_convert('US/Eastern').dt.tz_localize(None)

                index groups  value
0 2016-08-31 18:08:12      A      1
1 2016-08-31 18:08:12    NaN      1
2                 NaT      A      3
</code>```

Body:
Consider this simple example

idx2=[pd.to_datetime('2016-08-31 22:08:12') ,
     pd.to_datetime('2016-08-31 22:08:12'),
     pd.to_datetime(np.NaN)]

test2=pd.DataFrame({'value':[1,1,3], 'groups' : ['A',np.NaN,'A']},index=idx2)
test2.reset_index(inplace = True)

test2
Out[29]:
                index groups  value
0 2016-08-31 22:08:12      A      1
1 2016-08-31 22:08:12    NaN      1
2                 NaT      A      3

I would like to convert the column index to EST, but this

test2['index'].map(lambda x: x.tz_localize('UTC').tz_convert('US/Eastern').tz_localize(None))

gives me

AttributeError: 'NaTType' object has no attribute 'tz_localize'

Using x[x.notnull()] does not work either. what can I do?

Body:
No need to use reset_index, instead just operate directly on the DatetimeIndex which has tz_localize and tz_convert built-in:

test2.index = test2.index.tz_localize('UTC').tz_convert('US/Eastern').tz_localize(None)

The resulting output:

                    groups  value
2016-08-31 18:08:12      A      1
2016-08-31 18:08:12    NaN      1
NaT                      A      3

As noted by @DSM, you can use the .dt accessor if you want to do this on a column, but you'll need to use 3 instances of .dt, one before each timezone operation:

test2.reset_index(inplace=True)
test2['index'] = test2['index'].dt.tz_localize('UTC').dt.tz_convert('US/Eastern').dt.tz_localize(None)

                index groups  value
0 2016-08-31 18:08:12      A      1
1 2016-08-31 18:08:12    NaN      1
2                 NaT      A      3