问:
Buildr ruby error, can't convert Rake::FileTask into String
I have the following buildr buildfile segment:

```<code>require "buildr/protobuf"

....

define "protobuf-stuff" do
  pbs = protoc(
        Dir[_("pbsrc/some/pkg/*.proto")], {
        :include => [_("pbsrc")],
        })

  comp = compile.from(pbs).with(PROTOBUF_LIB) # MARK
  package :jar
end
</code>```

Buildr is 1.4.4, installed with the Linux install script on two machnies.

Machine 1: Debian 32bit, ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]

Machine 2: Ubuntu 64bit, ruby 1.8.7 (2010-01-10 patchlevel 249) [x86_64-linux]

Machine 1 compiles everything file. Machine 2 fails on the MARK-ed place, with

```<code>Buildr aborted!
TypeError : can't convert Rake::FileTask into String
/usr/lib/ruby/gems/1.8/gems/buildr-1.4.4/lib/buildr/core/application.rb:414:in `raw_load_buildfile'
/usr/lib/ruby/gems/1.8/gems/buildr-1.4.4/lib/buildr/core/application.rb:218:in `load_buildfile'
/usr/lib/ruby/gems/1.8/gems/buildr-1.4.4/lib/buildr/core/application.rb:213:in `load_buildfile'
</code>```

Now I can see that pbs is a FileTask and not a string.. but how come one machine accepts it, the other not? Is there a forced conversion to String?

Some buildr traces are attached at http://pastebin.com/nf4HiYx9 .

Thank you.

答:
The stacktrace on pastebin is very different from the stacktrace pasted here, from what I can see.

Where is the protoc method defined ? Is it part of Buildr core ?

The reason why it fails on one machine and not the other might be the version of Ruby you have, given that the line that fails is "if File.exist? path". path there is supposed to be a String, but is probably converted to a String in one case but not the other.

The overall fix is to add a call after calling protoc(...), protoc(...).map(&:to_s).

I hope this helped.

Body:
I have the following buildr buildfile segment:

require "buildr/protobuf"

....

define "protobuf-stuff" do
  pbs = protoc(
        Dir[_("pbsrc/some/pkg/*.proto")], {
        :include => [_("pbsrc")],
        })

  comp = compile.from(pbs).with(PROTOBUF_LIB) # MARK
  package :jar
end

Buildr is 1.4.4, installed with the Linux install script on two machnies.

Machine 1: Debian 32bit, ruby 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]

Machine 2: Ubuntu 64bit, ruby 1.8.7 (2010-01-10 patchlevel 249) [x86_64-linux]

Machine 1 compiles everything file. Machine 2 fails on the MARK-ed place, with

Buildr aborted!
TypeError : can't convert Rake::FileTask into String
/usr/lib/ruby/gems/1.8/gems/buildr-1.4.4/lib/buildr/core/application.rb:414:in `raw_load_buildfile'
/usr/lib/ruby/gems/1.8/gems/buildr-1.4.4/lib/buildr/core/application.rb:218:in `load_buildfile'
/usr/lib/ruby/gems/1.8/gems/buildr-1.4.4/lib/buildr/core/application.rb:213:in `load_buildfile'

Now I can see that pbs is a FileTask and not a string.. but how come one machine accepts it, the other not? Is there a forced conversion to String?

Some buildr traces are attached at http://pastebin.com/nf4HiYx9 .

Thank you.


来源: stackexchange

问:
Tracking file changes from Photoshop with FileSystemWatcher
I'm currently working on a component of my application which monitors a specific directory for files and keeps them in a DB together with special metadata of those files.

I use a FileSystemWatcher to track additions, renaming, deletion and changes to those files / directories. So far this works perfectly fine. But since FileSystemWatcher is not capable of tracking movements, I'm using hashes to keep track of the files.

Now in order to keep this working I must update the hash in the database once a file was changed. But my first test was proof of failure. Photoshop obviously has some tricky ways to save a file. I always catch a "psXXXXX.tmp" file being changed which I filter with the FileAttributes.Archive. The problem is: The watcher does not throw again for the real changed file. Since I need the real filename and not the temporary one, I can't update the DB.

Even if the file changes in size or the write time changed - nothing happens. It gets completely ignored. The event rises once when the temporary file gets created (or the original the renamed, I don't know) and then nothing happens anymore.

Can anybody explain this behaviour? Has anybody an idea how to avoid this?
Any workarounds or other solutions?

Thanks

答:
I had that problem with PS, I only had to add:

```<code>watcher.Renamed += new RenamedEventHandler(OnChanged);
</code>```

and all was good.

ContentLicense: CC BY-SA 3.0

Body:
I had that problem with PS, I only had to add:

watcher.Renamed += new RenamedEventHandler(OnChanged);

and all was good.


问:
how to import export docker compose?
I am still new in docker and all container things.
I have server with full access at
1.1.1.1 and I installed docker there. (without docker compose)
In the other place my friend have server 2.2.2.2 and he installed docker and docker compose there.

At 2.2.2.2 server, my friend build 3 container : container A (Git), container B(unknown), container C(unknown).
I can access content of container A (Git) with browsers.

My question is: can I import container A to my server in 1.1.1.1? I have user access to download Git, but what I want is to import the container, not Git (content inside the container).
Any hint? what should I do? Or it is impossible to do if I don't have access to the command console?

答:
No. If you would like to have had the image, which is used to run the container A(Git), then your friend has to push the Docker image to a Docker registry. This will give you the possibility to run the same Docker image as Docker container on your server. But not the data.

Docker images are by design immutable. Started Docker Images are called Docker Containers. Basically this Docker containers are completely deleted if you stop and remove them. If you have data you would like to persists, then you can use so called bind volumes, for example.

You see, your question is very broad. And there are ways to achieve what you want, but I can only point you to some documentation to go further. Or you can join a local meetup, which would be the fastes way to come aboard.

https://www.slideshare.net/Docker/introduction-to-docker-2017

https://docs.docker.com/

https://events.docker.com/

Title: how to import export docker compose?


问:
insert or update(upsert) in loopback application
I developed an API using Loopback framework, in that i have to insert or update to a table.

My table looks like below:

```<code>userid  bbid saved  id(PK)
  1      5    1000   1
</code>```

So when next time if(bbid = 5) it should update the above row, if bbid =5 is not there it should insert into the above table.

I tried the following:

```<code>app.models.modelname.upsert({
  bbid: bb.id,
  saved: Saved,
  userid: 1
}, function(err, res) {});
</code>```

EDIT for COMPOSITE ID:

```<code>app.models.modelname.upsert({
  bbid: vvvv.bbid,
  userid: 1,
  saved: amountSaved
}, function(err, res) {});
</code>```

Also gone through Loopback doc it says

```<code>    upsert - checks if the instance (record) exists, based on the designated
ID property, which must have a unique value; if the instance already exists,
the method updates that instance.  Otherwise, it inserts a new instance.
</code>```

But in my case it should check for bbid not id

But its inserting everytime. Please share your ideas. Thanks in advance

EDIT FOR UPSERT:

My process is as follows:

```<code>Fetch from table1 and loop that response and calculate the saved and upsert it into another table(table2 (this is where upsert should happen)). Also the fetching from table1 will happen frequently so suppose consider if is happens 2nd time it should update the already present bbid..
</code>```

答:
There are two methods in loopback one is simple upsert and second is upsertWithWhere.To insert or update based on where condition you must use upsertWithWhere method upsert only inserts the data.
you are using

```<code>app.models.modelname.upsert({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});
</code>```

instead use

```<code>app.models.modelname.upsertWithWhere({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});
</code>```

this will solve your problem.

note: this only updates single instance.If multiple instances are returned in where condition result it will throw an error.

ContentLicense: CC BY-SA 4.0

Body:
I developed an API using Loopback framework, in that i have to insert or update to a table.

My table looks like below:

userid  bbid saved  id(PK)
  1      5    1000   1

So when next time if(bbid = 5) it should update the above row, if bbid =5 is not there it should insert into the above table.

I tried the following:

app.models.modelname.upsert({
  bbid: bb.id,
  saved: Saved,
  userid: 1
}, function(err, res) {});

EDIT for COMPOSITE ID:

app.models.modelname.upsert({
  bbid: vvvv.bbid,
  userid: 1,
  saved: amountSaved
}, function(err, res) {});

Also gone through Loopback doc it says

    upsert - checks if the instance (record) exists, based on the designated
ID property, which must have a unique value; if the instance already exists,
the method updates that instance.  Otherwise, it inserts a new instance.

But in my case it should check for bbid not id

But its inserting everytime. Please share your ideas. Thanks in advance

EDIT FOR UPSERT:

My process is as follows:

Fetch from table1 and loop that response and calculate the saved and upsert it into another table(table2 (this is where upsert should happen)). Also the fetching from table1 will happen frequently so suppose consider if is happens 2nd time it should update the already present bbid..

Body:
There are two methods in loopback one is simple upsert and second is upsertWithWhere.To insert or update based on where condition you must use upsertWithWhere method upsert only inserts the data.
you are using

app.models.modelname.upsert({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});

instead use

app.models.modelname.upsertWithWhere({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});

this will solve your problem.

note: this only updates single instance.If multiple instances are returned in where condition result it will throw an error.


问:
Tracking all incoming network traffic on a unbuntu server
I would like to track all incoming traffic on a ubuntu web server, first by the address they are requesting and their ip address.

Is there any way to do so?

Thanks,
Ray

答: You can view packets with tcpdump or if you need a GUI with Wireshark.</p>

ContentLicense: CC BY-SA 2.5


问:
Are there cameras that capture not only color but the actual depth?
Getting into 3D reconstruction techniques, I'm curious whether there are cameras that capture not only color but the depth at the moment of image being captured. It would appear that getting the depth of a particular pixel on the sensor would be far more accurate than needing to reconstruct after the fact by using many images.

Thoughts? Suggestions?

答: There are Microsoft Kinect, and Intel® RealSense™ that you can take a look at. </p>


问:
JMeter - kick off a set number of jobs and then monitor state
Does JMeter have a construct of kicking of 200 jobs concurrently and then checking for the completion of these 200 jobs once they have all been kicked off?

Currently I'm using 1 thread to kick off the entire 200 jobs which is fine.

However I'm not sure how I can track the state from the 200 jobs and then execute a getState HTTP call.

Is this the case for spinning up 200 threads and having each thread check the state of its own job?

答:
JMeter acts on HTTP protocol level which in its turn uses TCP protocol as underlying transport which

guarantees the delivery of data and packets in the same order as they were sent.

So basically JMeter sends a request, waits for response and measures time in-between.

If you testing an application which assumes some asynchronous job, i.e. on first request you get response that job has been started and can query the status later on I would recommend the following:

Start a job normally using HTTP Request sampler. If you need to start multiple jobs concurrently you can use Synchronizing Timer to guarantee that they will be executed at exactly the same moment.

Monitor its status using another HTTP Request sampler under While Controller which is needed to exit the loop when job status changes

You can wrap the whole sequence into Transaction Controller so JMeter would sum up all the time in between starting and finishing the job.


问:
Storing Results of queries into one table
I have multiple different queries and I want to store their results into one table. Results of this queries may have different number of rows and columns.

e.g.
I have three queries:

Q1. select name,id from employee;  (Result has 2 columns and 2 rows)

Q2. select salary from emp_table     (Result has 1 column and 4 rows)

Q3. select country_name,Country_id,count(id) from players group by country_name,Country_id (result has 3 columns and 3 rows)

Now, I want to store these results into one table which has structure like :

```<code>Query_ID | col1  | col2 | col3
-------------------------------
</code>```

In this table query_id is unique id to queries like A1,A2,A3...

When queries have less than three columns as result, remaining column should be filled with null (for first query col3 should be null and for second query col2 and col 3 should be null).

desired output:

```<code>Query_ID | col1   | col2 | col3
----------
A1       | John   | 1356 | NULL
A1       | Mathew | 1667 | NULL
A2       | 1500   | NULL | NULL
A2       | 2000   | NULL | NULL
A2       | 3000   | NULL | NULL
A2       | 3500   | NULL | NULL
A3       | US     | 010  | 25
A3       | UK     | 012  | 26
A3       | GER    | 016  | 16
</code>```

答:
You Use Union All

```<code>SELECT  'A1' AS Query_ID, name AS Col1, id AS Col2, '' AS Col3
FROM employee

UNION ALL

SELECT 'A2' AS Query_ID, salary AS Col1, '' AS Col2, '' AS Col3
FROM emp_table

UNION ALL

SELECT 'A2' AS Query_ID, country_name AS Col1, Country_id AS Col2, count(id) AS Col3
FROM players
GROUP BY country_name, Country_id
</code>```

Body:
I have multiple different queries and I want to store their results into one table. Results of this queries may have different number of rows and columns.

e.g.
I have three queries:

Q1. select name,id from employee;  (Result has 2 columns and 2 rows)

Q2. select salary from emp_table     (Result has 1 column and 4 rows)

Q3. select country_name,Country_id,count(id) from players group by country_name,Country_id (result has 3 columns and 3 rows)

Now, I want to store these results into one table which has structure like :

Query_ID | col1  | col2 | col3
-------------------------------

In this table query_id is unique id to queries like A1,A2,A3...

When queries have less than three columns as result, remaining column should be filled with null (for first query col3 should be null and for second query col2 and col 3 should be null).

desired output:

Query_ID | col1   | col2 | col3
----------
A1       | John   | 1356 | NULL
A1       | Mathew | 1667 | NULL
A2       | 1500   | NULL | NULL
A2       | 2000   | NULL | NULL
A2       | 3000   | NULL | NULL
A2       | 3500   | NULL | NULL
A3       | US     | 010  | 25
A3       | UK     | 012  | 26
A3       | GER    | 016  | 16

Body:
You Use Union All

SELECT  'A1' AS Query_ID, name AS Col1, id AS Col2, '' AS Col3
FROM employee

UNION ALL

SELECT 'A2' AS Query_ID, salary AS Col1, '' AS Col2, '' AS Col3
FROM emp_table

UNION ALL

SELECT 'A2' AS Query_ID, country_name AS Col1, Country_id AS Col2, count(id) AS Col3
FROM players
GROUP BY country_name, Country_id


问:
Regular expression for pattern 123 X 123
I would like to know the regular exp for the input patter 123 X 123.
Only integers allowed before and after X and also space before and after X.
Thanks in advance</p>

答:
[0-9]\s*\s[0-9] is the regex expression for your given question.
learn more at w3 about regex</p>


问:
how to count number values' frequency using python pandas

I want to count the frequency of number values of csv data in my computer.
I tried this code:

```<code>import pandas as pd
data = pd.read_csv("C:/address.csv")
df=pd.DataFrame(data==data)
df.apply(pd.value_counts)
</code>```

I tried to use 'value_counts' but I don't know how to apply it.

Result that I want is
in a row of "number(from 1 to 50): n times"

I hope that I want to solve this problem. Thank you.

答:
You can use the cumcount() function.

```<code>df['number_count'] = df.groupby('col_of_interest').cumcount()
</code>```

Body:
I want to count the frequency of number values of csv data in my computer.
I tried this code:

import pandas as pd
data = pd.read_csv("C:/address.csv")
df=pd.DataFrame(data==data)
df.apply(pd.value_counts)

I tried to use 'value_counts' but I don't know how to apply it.

Result that I want is
in a row of "number(from 1 to 50): n times"

I hope that I want to solve this problem. Thank you.

Body:
You can use the cumcount() function.

df['number_count'] = df.groupby('col_of_interest').cumcount()


问:
Detect device moving detail
I am doing a demo in which when I move device like on top-left, top-right,top-center and bottom-right, bottom-left, bottom-center, center-right, center-left this type of movement I need to detect so that I am looking for accelerometer and gyroscope sensor. Am I going on the right track or not?

Do you have any demo or any link?

答:
Yes accelerometer would be a good option to detect the motion of the phone

You need to override the onSensorChange even in your activity in order to detect accelerometer values.

```<code>public void onSensorChange(SensorEvent sensorEvent) {
  Sensor mySensor = sensorEvent.sensor;

  if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      float x = sensorEvent.values[0];
      float y = sensorEvent.values[1];
      float z = sensorEvent.values[2];
  }
}
</code>```

Get started from here

Sensors Overview

Using the Accelerometer on Android

SensorManager

Also check out this page for a collection of android sensors library.

Title: Detect device moving detail

Body:
Yes accelerometer would be a good option to detect the motion of the phone

You need to override the onSensorChange even in your activity in order to detect accelerometer values.

public void onSensorChange(SensorEvent sensorEvent) {
  Sensor mySensor = sensorEvent.sensor;

  if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      float x = sensorEvent.values[0];
      float y = sensorEvent.values[1];
      float z = sensorEvent.values[2];
  }
}

Get started from here

Sensors Overview

Using the Accelerometer on Android

SensorManager

Also check out this page for a collection of android sensors library.


问:
Adding Html and with accordion to Product tab woocommerce
Adding HTML and with accordion to Product tab woocommerce.But i cannot see panel drop down.Checked code m i making any mistake here.for HTML all results should individually displayed in table.all codes in child theme</p>

```<code>     //This goes in child theme function

 $result = '<div class="custom" >';

 if( ! empty( $Brand) )
     $result .= '<p>'. __('<table class="custom"><span id="si" ><button class="accordion">Brand</button></span> ').'<span id="si1" ><div class="panel">
 <p>'.$Brand.'</p>
  </div>
   </span></table></p>';

 button.accordion {
     background-color: #eee;
     color: #444;
     cursor: pointer;
     padding: 18px;
     width: 100%;
     border: none;
     text-align: left;
     outline: none;
     font-size: 15px;
     transition: 0.4s;
 }

 button.accordion.active, button.accordion:hover {
     background-color: #ccc;
 }

 div.panel {
     padding: 0 18px;
     display: none;
     background-color: white;
 }

   //This goes in child theme function

 ?>
 <script>
 var acc = document.getElementsByClassName("accordion");
 var i;

 for (i = 0; i < acc.length; i++) {
     acc[i].onclick = function(){
         this.classList.toggle("active");
         var panel = this.nextElementSibling;
         if (panel.style.display === "block") {
             panel.style.display = "none";
         } else {
             panel.style.display = "block";
         }
     }
 }
 </script>
 <?php
</code>```

答:
You made some mistake in html table you didnt add tr so all data will come out from table And I made correction on your code so it will work effectively.

Change those PHP code as following

```<code>if( ! empty( $select ) )
{
    $output .= '
    <div class="woo-acc">
        <ul>
            <li class="acc-tit"><span>Brand Name </span> <i class="fa fa-chevron-right"></i><br>
                <div class="acc-cont">'.$select.'</div>
            </li>
        </ul>
    </div>';
}
</code>```

In css change replace with following code

```<code>.woo-acc ul { list-style: none; margin-left: 0px; }
.acc-tit i{font-size: 12px;font-weight: 100;}
.acc-cont{display: none;}
.acc-tit:hover > i:before { content: ""; }
.acc-tit:hover .acc-cont { display: block; }
</code>```

Hope it will help... If you have any issue post back...

Body:
Adding HTML and with accordion to Product tab woocommerce.But i cannot see panel drop down.Checked code m i making any mistake here.for HTML all results should individually displayed in table.all codes in child theme

     //This goes in child theme function

 $result = '
';

 if( ! empty( $Brand) )
     $result .= '
'. __('
<button class="accordion">Brand</button> ').'

'.$Brand.'

';

 button.accordion {
     background-color: #eee;
     color: #444;
     cursor: pointer;
     padding: 18px;
     width: 100%;
     border: none;
     text-align: left;
     outline: none;
     font-size: 15px;
     transition: 0.4s;
 }

 button.accordion.active, button.accordion:hover {
     background-color: #ccc;
 }

 div.panel {
     padding: 0 18px;
     display: none;
     background-color: white;
 }

   //This goes in child theme function

 ?>

 <?php

Body:
You made some mistake in html table you didnt add tr so all data will come out from table And I made correction on your code so it will work effectively.

Change those PHP code as following

if( ! empty( $select ) )
{
    $output .= '
    <div class="woo-acc">
        <ul>
            <li class="acc-tit"><span>Brand Name </span> <i class="fa fa-chevron-right"></i><br>
                <div class="acc-cont">'.$select.'</div>
            </li>
        </ul>
    </div>';
}

In css change replace with following code

.woo-acc ul { list-style: none; margin-left: 0px; }
.acc-tit i{font-size: 12px;font-weight: 100;}
.acc-cont{display: none;}
.acc-tit:hover > i:before { content: ""; }
.acc-tit:hover .acc-cont { display: block; }

Hope it will help... If you have any issue post back...


问:
what should the useragent value be http header for a java client
I am currently writing code to test an REST based API
I am getting a status 404 error when trying to content to the server.
Im pretty sure i have the correct username password base~Url
and account

I dont know what to put in for useragent?
I running a java program on my c drive to connect to the server.
what type of info typically goes into the useragent field?
Is it something to the with my browser.

答:
A 404 error can often mean there is a problem with the URI.

From: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.


问:
Batch File Programming with Findstr and Regex
First off, I am not a batch file and/or regex programmer.  ;)

Using batch file programming to parse filenames beginning with "T" that may be immediately followed by "2" AND "2" may be immediately followed by any of the integers 0-9.  All the files in the folder will be named the same beginning with "T" and followed by integers 1-29.  For example:
T1_... or T12_... or T2_... or T22_....

In this particular case ...

a) Filenames with T2 should fail the regex.  Errorlevel should be 1.

b) Filenames with T12 should fail the regex.  Errorlevel should be 1.

c) Filenames with T20 - T29 should pass the regex.  Errorlevel should be 0.

Problem: These results are not seen.  Errorlevel appears to be 0, always.

```<code>echo on

dir *.bin /b | findstr /r /c:"^[T][2][?=0123456789]*"
if errorlevel 0 goto :regular

:special
   echo special
   pause
   exit /B 0

:regular
   echo regular
   pause
   exit /B 0
</code>```

Two web based regex evaluators say my regex is valid as written when tested against all combinations, pass and fail.

What is going on with the "findstr" regex that it does not produce the outlined behavior (a-c)?  Or, am I not using errorlevel correctly?

Thanks for any insight.

答:
First off, your regex is not right. findstr has limited regex capabilities, but even in a full-fledged regex engine it would not be quite correct. Here's a better one:

```<code>^T2[0-9]_
</code>```

Starts with T, followed by 2, followed by a single character from the 0-9 range, followed by an underscore _ (I figure), followed by anything (implicit).

Next, the /c parameter in findstr means "Uses specified string as a literal search string." and that's contradicting what we actually want.

With that we end up with:

```<code>findstr /r "^T2[0-9]_"
</code>```

Next, filtering the list of files in a directory:

```<code>dir /b *.bin 2>NUL | findstr /r "^T2[0-9]_"
</code>```

Here the 2>NUL redirects STDERR of dir to NUL, so "file not found" or the like is not printed.

By the way, the following would never generate errors in the dir command, simply by moving the file extension check to the regex:

```<code>dir /b | findstr /r "^T2[0-9]_.*\.bin$"
</code>```

Next, doing something depending on whether we matched or not matched:

```<code>dir /b *.bin 2>NUL | findstr /r "^T2[0-9]_" >NUL && (
    @echo Match!
) || (
    @echo No Match!
)
</code>```

This uses the properties of && and ||, namely to check out the errorlevel and run the following command when it is 0 (&&) or otherwise (||). I tend to like that construct better than goto.

Also this uses >NUL to suppress the regular output of findstr.

Next, doing something for each matching filename (that's better than using goto as well):

```<code>for /f "usebackq delims=" %f in (`dir /b *.bin 2^>NUL ^| findstr /r "^T2[0-9]_"`) do (
    @echo Match: %f
)
</code>```

Here, usebackq enables the use of backticks to enclose a command, delims= switches off the default "split at whitespace" behavior of for. This way filenames with a space won't get broken up into tokens. Also note that in a quoted command we must escape special characters like the pipe | and the > with a ^.

Next, the above but for use in a batch file:

```<code>@echo off

for /f "usebackq delims=" %%f in (`dir /b *.bin 2^>NUL ^| findstr /r "^T2[0-9]_"`) do (
    echo Match: %%f
)
</code>```

Here we must escape % as %% (special rule that applies to for loop index variables).

Body:
First off, I am not a batch file and/or regex programmer.  ;)

Using batch file programming to parse filenames beginning with "T" that may be immediately followed by "2" AND "2" may be immediately followed by any of the integers 0-9.  All the files in the folder will be named the same beginning with "T" and followed by integers 1-29.  For example:
T1_... or T12_... or T2_... or T22_....

In this particular case ...

a) Filenames with T2 should fail the regex.  Errorlevel should be 1.

b) Filenames with T12 should fail the regex.  Errorlevel should be 1.

c) Filenames with T20 - T29 should pass the regex.  Errorlevel should be 0.

Problem: These results are not seen.  Errorlevel appears to be 0, always.

echo on

dir *.bin /b | findstr /r /c:"^[T][2][?=0123456789]*"
if errorlevel 0 goto :regular

:special
   echo special
   pause
   exit /B 0

:regular
   echo regular
   pause
   exit /B 0

Two web based regex evaluators say my regex is valid as written when tested against all combinations, pass and fail.

What is going on with the "findstr" regex that it does not produce the outlined behavior (a-c)?  Or, am I not using errorlevel correctly?

Thanks for any insight.

Body:
First off, your regex is not right. findstr has limited regex capabilities, but even in a full-fledged regex engine it would not be quite correct. Here's a better one:

^T2[0-9]_

Starts with T, followed by 2, followed by a single character from the 0-9 range, followed by an underscore _ (I figure), followed by anything (implicit).

Next, the /c parameter in findstr means "Uses specified string as a literal search string." and that's contradicting what we actually want.

With that we end up with:

findstr /r "^T2[0-9]_"

Next, filtering the list of files in a directory:

dir /b *.bin 2>NUL | findstr /r "^T2[0-9]_"

Here the 2>NUL redirects STDERR of dir to NUL, so "file not found" or the like is not printed.

By the way, the following would never generate errors in the dir command, simply by moving the file extension check to the regex:

dir /b | findstr /r "^T2[0-9]_.*\.bin$"

Next, doing something depending on whether we matched or not matched:

dir /b *.bin 2>NUL | findstr /r "^T2[0-9]_" >NUL && (
    @echo Match!
) || (
    @echo No Match!
)

This uses the properties of && and ||, namely to check out the errorlevel and run the following command when it is 0 (&&) or otherwise (||). I tend to like that construct better than goto.

Also this uses >NUL to suppress the regular output of findstr.

Next, doing something for each matching filename (that's better than using goto as well):

for /f "usebackq delims=" %f in (`dir /b *.bin 2^>NUL ^| findstr /r "^T2[0-9]_"`) do (
    @echo Match: %f
)

Here, usebackq enables the use of backticks to enclose a command, delims= switches off the default "split at whitespace" behavior of for. This way filenames with a space won't get broken up into tokens. Also note that in a quoted command we must escape special characters like the pipe | and the > with a ^.

Next, the above but for use in a batch file:

@echo off

for /f "usebackq delims=" %%f in (`dir /b *.bin 2^>NUL ^| findstr /r "^T2[0-9]_"`) do (
    echo Match: %%f
)

Here we must escape % as %% (special rule that applies to for loop index variables).


问:
Disable explicit commit in Solr
I'm currently working on improving the indexing speed of a application where I do not have full control of the code that performs the indexing. I have found out that the indexing code makes a commit after each document, something that I would like to avoid for performance reasons.

Question:

Is it possible in Solr to disable all commits made explicitly from a
  client and instead only rely on auto commits configured in the Solr config?

答:
As of Solr 5.3 (if not earlier) you can add the following to solrconfig.xml:

```<code><updateRequestProcessorChain name="ignore-commit-from-client" default="true">
  <processor class="solr.IgnoreCommitOptimizeUpdateProcessorFactory">
    <int name="statusCode">200</int>
  </processor>
  <processor class="solr.LogUpdateProcessorFactory" />
  <processor class="solr.DistributedUpdateProcessorFactory" />
  <processor class="solr.RunUpdateProcessorFactory" />
</updateRequestProcessorChain>
</code>```

See: https://lucene.apache.org/solr/guide/6_6/shards-and-indexing-data-in-solrcloud.html#ShardsandIndexingDatainSolrCloud-IgnoringCommitsfromClientApplicationsinSolrCloud

Title: Disable explicit commit in Solr

Body:
As of Solr 5.3 (if not earlier) you can add the following to solrconfig.xml:

<updateRequestProcessorChain name="ignore-commit-from-client" default="true">
  <processor class="solr.IgnoreCommitOptimizeUpdateProcessorFactory">
    <int name="statusCode">200</int>
  </processor>
  <processor class="solr.LogUpdateProcessorFactory" />
  <processor class="solr.DistributedUpdateProcessorFactory" />
  <processor class="solr.RunUpdateProcessorFactory" />
</updateRequestProcessorChain>

See: https://lucene.apache.org/solr/guide/6_6/shards-and-indexing-data-in-solrcloud.html#ShardsandIndexingDatainSolrCloud-IgnoringCommitsfromClientApplicationsinSolrCloud


问:
Magento Set Shipping cost when create order programmatically
INFO: Magento 1.7.0.2 CE

I have made a module for importing order from an external feed by cron schedule, i also create a custom carrier.

All works well but i can't set the shipping cost... this is the code:

```<code>        $shippingAddress = $quote->getShippingAddress()->addData($addressData);

        $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
                ->setShippingMethod('customname_customname')
                ->setShippingAmount('10')
                ->setBaseShippingAmount('10');

        $quote->collectTotals();
        $quote->save();
</code>```

$addressData contain the customer infos

I have tried different method but i can't set the shipping cost. HELP!

This is the custom carrier code:

```<code>    protected $_code = 'customname';

    /**
    * Collect rates for this shipping method based on information in $request
    *
    * @param Mage_Shipping_Model_Rate_Request $data
    * @return Mage_Shipping_Model_Rate_Result
    */
    public function collectRates(Mage_Shipping_Model_Rate_Request $request){
        $result = Mage::getModel('shipping/rate_result');
        $method = Mage::getModel('shipping/rate_result_method');
        $method->setCarrier($this->_code);
        $method->setCarrierTitle($this->getConfigData('title'));
        $method->setMethod($this->_code);
        $method->setMethodTitle($this->getConfigData('name'));
        $method->setPrice('0.00');
    $method->setCost('0.00');
        $result->append($method);
        return $result;
    }

    /**
     * Get allowed shipping methods
     *
     * @return array
     */
    public function getAllowedMethods()
    {
        return array($this->_code=>$this->getConfigData('name'));
    }
}
</code>```

答:
You can update shipping cost through these line of code:-

```<code>$order = Mage::getModel('sales/order')->load($incrementId, 'increment_id');
$shippingprice = 30;//custom shipping price
$order->setShippingAmount($shippingprice);
$order->setBaseShippingAmount($shippingprice);
$order->setGrandTotal($order->getGrandTotal() + $shippingprice); //adding shipping price to grand total
$order->save();
</code>```

It will helpful for you.

Body:
INFO: Magento 1.7.0.2 CE

I have made a module for importing order from an external feed by cron schedule, i also create a custom carrier.

All works well but i can't set the shipping cost... this is the code:

        $shippingAddress = $quote->getShippingAddress()->addData($addressData);

        $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
                ->setShippingMethod('customname_customname')
                ->setShippingAmount('10')
                ->setBaseShippingAmount('10');

        $quote->collectTotals();
        $quote->save();

$addressData contain the customer infos

I have tried different method but i can't set the shipping cost. HELP!

This is the custom carrier code:

    protected $_code = 'customname';

    /**
    * Collect rates for this shipping method based on information in $request
    *
    * @param Mage_Shipping_Model_Rate_Request $data
    * @return Mage_Shipping_Model_Rate_Result
    */
    public function collectRates(Mage_Shipping_Model_Rate_Request $request){
        $result = Mage::getModel('shipping/rate_result');
        $method = Mage::getModel('shipping/rate_result_method');
        $method->setCarrier($this->_code);
        $method->setCarrierTitle($this->getConfigData('title'));
        $method->setMethod($this->_code);
        $method->setMethodTitle($this->getConfigData('name'));
        $method->setPrice('0.00');
    $method->setCost('0.00');
        $result->append($method);
        return $result;
    }

    /**
     * Get allowed shipping methods
     *
     * @return array
     */
    public function getAllowedMethods()
    {
        return array($this->_code=>$this->getConfigData('name'));
    }
}

Body:
You can update shipping cost through these line of code:-

$order = Mage::getModel('sales/order')->load($incrementId, 'increment_id');
$shippingprice = 30;//custom shipping price
$order->setShippingAmount($shippingprice);
$order->setBaseShippingAmount($shippingprice);
$order->setGrandTotal($order->getGrandTotal() + $shippingprice); //adding shipping price to grand total
$order->save();

It will helpful for you.


问:
Need the URL of windows phone activesync
I have searched for hours. I am developing an activesync client in order to send sms from PC to a phone that will send it. Specifically a windows phone. Previously I have used Jeyo mobile comp. I have all documentation I need but I can't find the default http address of the activesync server on the Windows phone when it is connected through USB. I should mention that I have a disability and can't access Windows phone itself. The OS is 6 but the whole point of creating the software is so I can upgrade. Many thanks!
alternatively if I am barking up the wrong tree, i need to know what tree to bark. for example serial ports. i would only need code to connect and read/write. otherwise is there a way to detect the information with csharp, ipconfig definitely isn't detecting windows mobile and activesync definitely works.</p>

答:
The question is a bit unclear. But Jeyo Mobile Comp is a remote control software for Windows Mobile (6.x, not Windows Phone 8 or 10).

Another free remote control software you my look at is Sparus EveryWan Remote personal edition (free). It can show the screen of Windows Mobile on your Windows PC and you can use the device remotely using the USB ActiveSync connection.

Another option is MyMobiler (also free).

The ActiveSync connection is made using the IP addresses 169.254.1.1 and 169.254.1.2 or 192.168.55.101/102, depends on Connection Setting:USB:Enhanced Network on device. You will find the IP when the device is connected to your PC, ActiveSync is connected and you start a Windows CMD prompt on the PC; then type "ipconfig" to get a list of IP addresses used by the PC. There will be your IP connected to the LAN/WAN and the one connected to Windows Mobile.

There is NO default http access to the Windows Mobile device.

If you are looking for a programming API, see RAPI at Microsoft (https://msdn.microsoft.com/en-us/library/aa513321.aspx) or OpenNetCF Desktop Communication (https://rapi.codeplex.com/) support.


问:
php array. cant get the output i desire. help me
i have this code

```<code>$dir = "img/ori/";
$dir_thumbs = "img/thumbs/";

$images = array();
$d = dir($dir);
while($name = $d->read()){
    $thumb = "thumb_".$name;
    $images[] = array('name' => $name,'thumb_url' => $dir_thumbs.$thumb);
}
$d->close();
$o = array('images'=>$images);
</code>```

i want to output $name and $thumb_url of all the images. how to do it.? help me

答:
```<code><?php
foreach ($images as $image) {
    echo "{$image['name']} {$image['thumb_url']}";
}
?>
</code>```

Body:
i have this code

$dir = "img/ori/";
$dir_thumbs = "img/thumbs/";

$images = array();
$d = dir($dir);
while($name = $d->read()){
    $thumb = "thumb_".$name;
    $images[] = array('name' => $name,'thumb_url' => $dir_thumbs.$thumb);
}
$d->close();
$o = array('images'=>$images);

i want to output $name and $thumb_url of all the images. how to do it.? help me


问:
How to hide UITableViewSections in Swift?
I have a static grouped table view that has 5 sections (all the sections have headers, no footers). I created all of this using a Storyboard. Now, how can I hide the first/top UITableViewSection (including the header). I tried making an outlet to the UITableViewSection but it tells me that it is not valid (undeclared type):

```<code>@IBOutlet var section: UITableViewSection!
</code>```

I did it this way because I was planning on doing:

```<code>section.hidden = true
</code>```

Can it not be done this way?

My delegates and data sources are set up 100% correctly.

答:
For anyone wanting to hide sections because they are using a static grouped tableView with a dynamic number of sections, the solution below may be of help.  In my case, each section with data to display needed to have a custom header. Any section that did not have data, needed to be hidden fully.

The answer above was of great help in my scenario.  However, for those who don't always know which section(s) will need to be hidden here is a solution for you extending on the above.

In my scenario, I have up to 12 entries in an array that I want to show in up to 12 sections (amongst other sections in a grouped tableView).  If there are less than 12 entries to display, I want to hide the unnecessary sections by giving them 0 height and 0 rows.  I also wanted to hide the headerView.

To do this, I did the following:

Set up your tableView as per the excellent answer @sasquatch gave
above.

In the numberOfRowsInSection(section: Int) and tableView(_
tableView: UITableView, heightForHeaderInSection section: Int) functions, check whether the rows/height should be 0.

In my case, I was using sections 1 - 12 for my dynamic data so I used code as below:

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //For section 0 and 13, just 1 row is ok
    if section == 0 || section == 13 {
        return 1
    }

    //For sections 1 - 12, determine if we have data to populate it, or if we should hide it
    if section <= dynamicDataToDisplay.count {
        return 2
    }

    //If it's section 1 - 12, but we don't have a corresponding data entry in dynamicDataToDisplay, then just return 0 rows
    return 0

}
</code>```

The code for the heightForHeader function is similar in logic:

```<code>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    switch section {

    case 0:
        return 45.0
    case 13:
        return UITableViewAutomaticDimension
    default:
        if dynamicDataToDisplay.count >= section {
           return 25.0
        } else {
            return 0.0
        }

    } //end switch

}
</code>```

Even after setting up these functions, I found that I was still getting headers appearing for the sections I wanted to hide.  I guess I thought that viewForHeaderInSection would not be called if the numberOfRows was 0 and heightOfHeader was also 0, but it was still being called.

Adding the following helped ensure that the header wasn't unnecessarily created:

```<code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    //set up header for dynamic data sections
    if 1 ... 12 ~= section  {

        if tableView.numberOfRows(inSection: section) == 0 {
            return nil
        }
        //Continue with the header set up for valid sections with rows to display data

        ......
    }
}
</code>```

This solution might help anyone who is still getting a header being created despite its height and rows being set to 0.

Body:
I have a static grouped table view that has 5 sections (all the sections have headers, no footers). I created all of this using a Storyboard. Now, how can I hide the first/top UITableViewSection (including the header). I tried making an outlet to the UITableViewSection but it tells me that it is not valid (undeclared type):

@IBOutlet var section: UITableViewSection!

I did it this way because I was planning on doing:

section.hidden = true

Can it not be done this way?

My delegates and data sources are set up 100% correctly.

Body:
For anyone wanting to hide sections because they are using a static grouped tableView with a dynamic number of sections, the solution below may be of help.  In my case, each section with data to display needed to have a custom header. Any section that did not have data, needed to be hidden fully.

The answer above was of great help in my scenario.  However, for those who don't always know which section(s) will need to be hidden here is a solution for you extending on the above.

In my scenario, I have up to 12 entries in an array that I want to show in up to 12 sections (amongst other sections in a grouped tableView).  If there are less than 12 entries to display, I want to hide the unnecessary sections by giving them 0 height and 0 rows.  I also wanted to hide the headerView.

To do this, I did the following:

Set up your tableView as per the excellent answer @sasquatch gave
above.

In the numberOfRowsInSection(section: Int) and tableView(_
tableView: UITableView, heightForHeaderInSection section: Int) functions, check whether the rows/height should be 0.

In my case, I was using sections 1 - 12 for my dynamic data so I used code as below:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //For section 0 and 13, just 1 row is ok
    if section == 0 || section == 13 {
        return 1
    }

    //For sections 1 - 12, determine if we have data to populate it, or if we should hide it
    if section <= dynamicDataToDisplay.count {
        return 2
    }

    //If it's section 1 - 12, but we don't have a corresponding data entry in dynamicDataToDisplay, then just return 0 rows
    return 0

}

The code for the heightForHeader function is similar in logic:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

    switch section {

    case 0:
        return 45.0
    case 13:
        return UITableViewAutomaticDimension
    default:
        if dynamicDataToDisplay.count >= section {
           return 25.0
        } else {
            return 0.0
        }

    } //end switch

}

Even after setting up these functions, I found that I was still getting headers appearing for the sections I wanted to hide.  I guess I thought that viewForHeaderInSection would not be called if the numberOfRows was 0 and heightOfHeader was also 0, but it was still being called.

Adding the following helped ensure that the header wasn't unnecessarily created:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    //set up header for dynamic data sections
    if 1 ... 12 ~= section  {

        if tableView.numberOfRows(inSection: section) == 0 {
            return nil
        }
        //Continue with the header set up for valid sections with rows to display data

        ......
    }
}

This solution might help anyone who is still getting a header being created despite its height and rows being set to 0.


问:
Jmeter: Wait for threads to complete previous steps
I have created a JMeter script for load testing and has following steps,

```<code>Login
Step 1
Step 2
Step 3
Logout
</code>```

I want to perform load test for "Step 3" with 5 users. If i start the scripts with 5 users, the previous steps i.e. login, Step 1 and Step 2  may have different response time and Step 3 will not be triggered at same time.

Is there a way to configure JMeter like below,

```<code>Login
Step 1
Step 2
<Wait for all threads/user to complete Step 2>
Step 3
Logout
</code>```

答: You can add a Synchronising Timer as a child of the Step 3, this way JMeter will pause the threads until specified number is reached so it will act as a "rendezvous point".

Body:
I have created a JMeter script for load testing and has following steps,

Login
Step 1
Step 2
Step 3
Logout

I want to perform load test for "Step 3" with 5 users. If i start the scripts with 5 users, the previous steps i.e. login, Step 1 and Step 2  may have different response time and Step 3 will not be triggered at same time.

Is there a way to configure JMeter like below,

Login
Step 1
Step 2
<Wait for all threads/user to complete Step 2>
Step 3
Logout


问:
JAVA Shopping Cart Exercise Not Compiling When printMenu() Is Called
I am working on an assignment in which I have to create a simple shopping cart with a menu. However, I am very stuck as I can't figure out why my printMenu() method will not compile. Aside from that, I feel pretty good about the rest of the code.

To understand what exactly I'm required to have/use for this assignment, I will have the instructions posted here: https://imgur.com/a/kIZz1

The actual code files can be found here

```<code>import java.util.Scanner;

public class ShoppingCartManager
{

    public static void main(String[] args)
    {
        ShoppingCart cart = new ShoppingCart();
        Scanner scnr = new Scanner(System.in);

        String customerName = "none";
        String currentDate = "January 1, 2017";

        System.out.println("Enter Customer's Name:");
        cart.setCustomerName(scnr.nextLine());
        System.out.println("Enter Today's Date:");
        cart.setDate(scnr.nextLine());
        System.out.println("");
        System.out.println("Customer Name: " + cart.getCustomerName());
        System.out.println("Today's Date: " + cart.getDate());

     cart.printMenu();
    }

}
</code>```

答:
Your printMenu function is static, meaning you call it at the class level, and pass a ShoppingCart as an argument.

```<code>ShoppingCart.printMenu(cart);
</code>```

Body:
I am working on an assignment in which I have to create a simple shopping cart with a menu. However, I am very stuck as I can't figure out why my printMenu() method will not compile. Aside from that, I feel pretty good about the rest of the code.

To understand what exactly I'm required to have/use for this assignment, I will have the instructions posted here: https://imgur.com/a/kIZz1

The actual code files can be found here

import java.util.Scanner;

public class ShoppingCartManager
{

    public static void main(String[] args)
    {
        ShoppingCart cart = new ShoppingCart();
        Scanner scnr = new Scanner(System.in);

        String customerName = "none";
        String currentDate = "January 1, 2017";

        System.out.println("Enter Customer's Name:");
        cart.setCustomerName(scnr.nextLine());
        System.out.println("Enter Today's Date:");
        cart.setDate(scnr.nextLine());
        System.out.println("");
        System.out.println("Customer Name: " + cart.getCustomerName());
        System.out.println("Today's Date: " + cart.getDate());

     cart.printMenu();
    }

}

Body:
Your printMenu function is static, meaning you call it at the class level, and pass a ShoppingCart as an argument.

ShoppingCart.printMenu(cart);


问:
log4net is not logging to log file or console (external log4net.config file)
I created a a file called log4net.config in my project and added the following configuration:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>
</code>```

After that, I added the line below to my AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

In the application, I have the following static class:

```<code>public static class Logger
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void LogInfo(string msg)
        {
            log.Info(msg);
        }

        public static void LogDebug(string msg)
        {
            log.Debug(msg);
        }

        public static void LogWarn(string msg, Exception e)
        {
            log.Warn(msg, e);
        }

        public static void LogError(string msg, Exception e)
        {
            log.Error(msg, e);
        }
    }
</code>```

Then I'm trying to log somewhere in the application in another class using Logger.LogDebug("Error logger working.");

However, I can't see any log file being created or written to it. What am I doing wrong?

UPDATE:

I also added the following in my app.config file but I see nothing at all on my Output console...

```<code><appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
</appSettings>
</code>```

答:
Managed to find out the issue thanks to stuartd's comment. My problem was, my full solution had 2 projects. I had only configured one project (which is not the start-up project) for log4net.

My original log4net configuration did not have any mistake. I simply added log4net reference to my start up project and added log4net configuration to that project as well and it started logging.

Many thanks to everyone who tested my config.

Body:
I created a a file called log4net.config in my project and added the following configuration:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="console" />
      <appender-ref ref="RollingFileAppender" />
    </root>
    <appender name="console" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="${LOCALAPPDATA}\MyApp\LogFile.log" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5level [%d{yyyy-MM-dd hh:mm:ss}] [%thread] (Line:%line) %M: - %m%n" />
      </layout>
    </appender>
  </log4net>
</configuration>

After that, I added the line below to my AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

In the application, I have the following static class:

public static class Logger
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static void LogInfo(string msg)
        {
            log.Info(msg);
        }

        public static void LogDebug(string msg)
        {
            log.Debug(msg);
        }

        public static void LogWarn(string msg, Exception e)
        {
            log.Warn(msg, e);
        }

        public static void LogError(string msg, Exception e)
        {
            log.Error(msg, e);
        }
    }

Then I'm trying to log somewhere in the application in another class using Logger.LogDebug("Error logger working.");

However, I can't see any log file being created or written to it. What am I doing wrong?

UPDATE:

I also added the following in my app.config file but I see nothing at all on my Output console...

<appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
</appSettings>


问:
Ideas on how to measure the time to get 45th Fibonacci number
I'm working on a variation of a problem noted in Problem 19 Chapter 12 of the textbook "Building Java Programs". Essentially, I'm doing a recursion problem using a Fibonacci sequence. Though the program I've made works, part of the problem I'm working on is I also need to measure the time to get 45th Fibonacci number by using the implementations by 1, 2 and the one given in problem, print out how many times your implementations are faster than the one given in the problem . While I've looked at this page (Calculating a Fibonacci number with array), I was wondering is there was a way implement this without a lot of code change. This is the original method used:

```<code>public static int fibonacci (int n) {
      if(n <= 2){
        return 1;
      } else {
         return fib (n - 1) + fib(n - 2);
      }
}
</code>```

And this is what I've done I did the problem using two java files: one that serves as a test main class with and the other with the recursion algorithm :

PrintValues.java

```<code>import java.util.Scanner;

public class PrintValues {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number value: ");
        int n = scan.nextInt();
        HelperBinary.countBinary(n);
        //fib(double nth);
    }
}
</code>```

HelperBinary.Java:

```<code>public class HelperBinary {

    public static void countBinary(int n) {
        if (n < 0) {
            throw new IllegalArgumentException();
        }
        countBinary(new char[n], n);
    }

    private static void countBinary(char[] preFx, int n) {
        if (n == 0) {
            /* This is the base case
            */
            System.out.println(preFx);
        } else {
            /* This is the "recursive" case.
            */
            final int i = preFx.length - n;

            /* Assign a '0' preFx and recurse
            */
            preFx[i] = '0';
            countBinary(preFx, n - 1);

            /*Assign a '1' preFx  and recurse
            */
            preFx[i] = '1';
            countBinary(preFx, n - 1);
        }
    }
}
</code>```

Any help would be seriously appreciated.

答:
There are many subtleties when timing a program (see the question in the duplicate link), but here's two quick'n'dirty ways to get an idea of the run time.

The first way depends on what operating system you are using. If you use Linux or OS X, you could use the time command to measure how long a command takes to execute. Then you could run your java program like this:

```<code>time java -jar myJavaProgram.jar
</code>```

and time will print to the console how long it took.

The second way is to time it in Java.

```<code>class SomeClass {

    private static void main(String[] args) {
        // record the start time
        long startTime = System.currentTimeMillis();

        // run your fibonnaci method and calculate the 45th number
        long fib45 = fib(45);

        // record the finishing time
        long endTime = System.currentTimeMillis();

        // calculate the time taken in milliseconds
        long runTime = endTime - startTime;

        System.out.println("45th Fibonacci number: " + fib45);
        System.out.println("Run time: " + runTime);
    }
}
</code>```

Run it a few times and take the average run time.

Body:
I'm working on a variation of a problem noted in Problem 19 Chapter 12 of the textbook "Building Java Programs". Essentially, I'm doing a recursion problem using a Fibonacci sequence. Though the program I've made works, part of the problem I'm working on is I also need to measure the time to get 45th Fibonacci number by using the implementations by 1, 2 and the one given in problem, print out how many times your implementations are faster than the one given in the problem . While I've looked at this page (Calculating a Fibonacci number with array), I was wondering is there was a way implement this without a lot of code change. This is the original method used:

public static int fibonacci (int n) {
      if(n <= 2){
        return 1;
      } else {
         return fib (n - 1) + fib(n - 2);
      }
}

And this is what I've done I did the problem using two java files: one that serves as a test main class with and the other with the recursion algorithm :

PrintValues.java

import java.util.Scanner;

public class PrintValues {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number value: ");
        int n = scan.nextInt();
        HelperBinary.countBinary(n);
        //fib(double nth);
    }
}

HelperBinary.Java:

public class HelperBinary {

    public static void countBinary(int n) {
        if (n < 0) {
            throw new IllegalArgumentException();
        }
        countBinary(new char[n], n);
    }

    private static void countBinary(char[] preFx, int n) {
        if (n == 0) {
            /* This is the base case
            */
            System.out.println(preFx);
        } else {
            /* This is the "recursive" case.
            */
            final int i = preFx.length - n;

            /* Assign a '0' preFx and recurse
            */
            preFx[i] = '0';
            countBinary(preFx, n - 1);

            /*Assign a '1' preFx  and recurse
            */
            preFx[i] = '1';
            countBinary(preFx, n - 1);
        }
    }
}

Any help would be seriously appreciated.

Body:
There are many subtleties when timing a program (see the question in the duplicate link), but here's two quick'n'dirty ways to get an idea of the run time.

The first way depends on what operating system you are using. If you use Linux or OS X, you could use the time command to measure how long a command takes to execute. Then you could run your java program like this:

time java -jar myJavaProgram.jar

and time will print to the console how long it took.

The second way is to time it in Java.

class SomeClass {

    private static void main(String[] args) {
        // record the start time
        long startTime = System.currentTimeMillis();

        // run your fibonnaci method and calculate the 45th number
        long fib45 = fib(45);

        // record the finishing time
        long endTime = System.currentTimeMillis();

        // calculate the time taken in milliseconds
        long runTime = endTime - startTime;

        System.out.println("45th Fibonacci number: " + fib45);
        System.out.println("Run time: " + runTime);
    }
}

Run it a few times and take the average run time.


问:
How can I send output of a Filebeat in one system to a File in another system?
Generally filebeat can send output to a file in a local system but I want to send output to a file in remote system.
can any one tell me whether it is possible or not?</p>

答: If the remote system is windows, you can create a remote shared folder. </p>


问:
How to remove some character from string using PHP
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);
</code>```

Expected Output

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);
</code>```

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

答:
```<code>$datArr=array(array("name"=>"Ram","id"=>1,"date"=>"12/04/2017 05:31:57 AM"),array("name"=>"Rahim","id"=>5,"date"=>"12/03/2017 12:31:57 PM"),array("name"=>"Raj","id"=>4,"date"=>"12/04/2017 05:31:57 PM"));
</code>```

Traverse the array using foreach loop.
when it comes to date value, do the following

convert the date string to datetime object

```<code>$time = strtotime($dateKeyValueInArray);
</code>```

Now set the date format for this timestamp

```<code>$newformat = date('Y-m-d',$time);
</code>```

See the output by using

```<code>echo $newformat;
</code>```

Reference links are
Converting string to Date and DateTime
https://www.w3schools.com/php/func_date_date_format.asp

Hope it helps :)

Body:
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);

Expected Output

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

Body:
$datArr=array(array("name"=>"Ram","id"=>1,"date"=>"12/04/2017 05:31:57 AM"),array("name"=>"Rahim","id"=>5,"date"=>"12/03/2017 12:31:57 PM"),array("name"=>"Raj","id"=>4,"date"=>"12/04/2017 05:31:57 PM"));

Traverse the array using foreach loop.
when it comes to date value, do the following

convert the date string to datetime object

$time = strtotime($dateKeyValueInArray);

Now set the date format for this timestamp

$newformat = date('Y-m-d',$time);

See the output by using

echo $newformat;

Reference links are
Converting string to Date and DateTime
https://www.w3schools.com/php/func_date_date_format.asp

Hope it helps :)


问:
Wordpress PHP spitting out the same post ID in Bootstrap Carousel
Would anyone know why my code is making my Carousel integration output the same post ID? I tried everything I can but can not figure out what is going on.

I am trying to make it so that my Wordpress theme will output a carousel with "the_post_thumbnail" function. It's working but it repeats the same Post. Any help would be great, I am completely stuck. Thank you.

Here is my PHP code:

```<code><div class="carousel-inner">
    <?php
        $args_cat = array(
            'include' => '7, 9, 6'
        );
        $categories = get_categories( $args_cat );
        //$categories = get_categories();
        $count = 0;
        //$currentPage = (get_query_var( 'paged' )) ? get_query_var( 'paged' ) : 1;
        $args = array( 'posts_per_page'=> 1 );
        query_posts($args);

        foreach($categories as $category):

            $args = array(
                'type' => 'post',
                'posts_per_page' => 1,
            );

            $lastBlog = new WP_Query( $args );

            if( $lastBlog->have_posts() ):

                while( $lastBlog->have_posts() ): $lastBlog->the_post(); ?>
                    <div class="carousel-item <?php if($count == 0): echo 'active'; endif; ?>">
                    <?php // get_template_part( 'post', get_post_format() ); ?>
                    <?php the_post_thumbnail( 'full', ['class' => 'd-block w-100'] ); ?>
                    <?php the_title( sprintf('<h1 class="entry-title"><a href="%s">', esc_url( get_permalink() ) ),'</a></h1>' ); ?>
                    <small><?php // the_category(' '); ?></small>
                    </div>

                <?php endwhile;

            endif;

            wp_reset_postdata();

        $count++;

        endforeach;

    ?>
</div>
</code>```

Here is the output (This has been edited to shorten down):

```<code><div class="carousel-inner">
    <div class="carousel-item active">
        <img src="/sandbox-theme/wp-content/uploads/2017/12/fb-logo-dark.jpg" class="d-block w-100 wp-post-image" alt="" srcset="/sandbox-theme/wp-content/uploads/2017/12/fb-logo-dark.jpg 180w,>
        <h1 class="entry-title"><a href="https://publifiedlabs.com/sandbox-theme/2017/12/02/test-4/">test 4</a></h1>
        <small></small>
    </div>

    <div class="carousel-item ">
        <img .... >test 4</a></h1>
        <small></small>

    </div>

    <div class="carousel-item ">
        <img ..... >test 4</a></h1>
        <small></small>
    </div>

</div>
</code>```

答:
Just make only one change 'post_per_page' should be -1 for all and any other number for many images u want

'posts_per_page' => -1

Body:
Would anyone know why my code is making my Carousel integration output the same post ID? I tried everything I can but can not figure out what is going on.

I am trying to make it so that my Wordpress theme will output a carousel with "the_post_thumbnail" function. It's working but it repeats the same Post. Any help would be great, I am completely stuck. Thank you.

Here is my PHP code:

    <?php
        $args_cat = array(
            'include' => '7, 9, 6'
        );
        $categories = get_categories( $args_cat );
        //$categories = get_categories();
        $count = 0;
        //$currentPage = (get_query_var( 'paged' )) ? get_query_var( 'paged' ) : 1;
        $args = array( 'posts_per_page'=> 1 );
        query_posts($args);

        foreach($categories as $category):

            $args = array(
                'type' => 'post',
                'posts_per_page' => 1,
            );

            $lastBlog = new WP_Query( $args );

            if( $lastBlog->have_posts() ):

                while( $lastBlog->have_posts() ): $lastBlog->the_post(); ?>
                    <div class="carousel-item <?php if($count == 0): echo 'active'; endif; ?>">
                    <?php // get_template_part( 'post', get_post_format() ); ?>
                    <?php the_post_thumbnail( 'full', ['class' => 'd-block w-100'] ); ?>
                    <?php the_title( sprintf('
', esc_url( get_permalink() ) ),'
' ); ?>
                    <?php // the_category(' '); ?>

                <?php endwhile;

            endif;

            wp_reset_postdata();

        $count++;

        endforeach;

    ?>

Here is the output (This has been edited to shorten down):

test 4

        test 4

        test 4


问:
How do I export the data rendered by react component to pdf?
I have a component view which has images, tables, and list styled with CSS. Is there a legit approach to export/save that view to pdf? ctrl+p doesn't really work because it grabs the entire page with navigation etc.
I'm thinking to implement print button which will redirect to another "PrintComponentCleanView" and from there do ctrl+p. This is a 2 step process. I'm sure there is a better approach to accomplish this. Any ideas appreciated.

答:
Adding print styles in your existing stylesheet:

```<code>@media print
{
  .navbar {
    display: none;
  }
  ...
}
</code>```

Adding a different stylesheet for printing:

```<code><link rel="stylesheet" type="text/css" media="print" href="style.css">
</code>```

You can then use window.print(); for opening up the Print dialog.

Body:
Adding print styles in your existing stylesheet:

@media print
{
  .navbar {
    display: none;
  }
  ...
}

Adding a different stylesheet for printing:

<link rel="stylesheet" type="text/css" media="print" href="style.css">

You can then use window.print(); for opening up the Print dialog.


Title: How to remove some character from string using PHP

Body:
You can do it with str_replace() over a foreach loop

Code

foreach ($datArr as &$dat) {
    $dat['date'] = str_replace([' AM', ' PM'], "", $dat['date']);
}

Input

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);

Output

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);


问:
How to get ownership of a moved value back from a closure?
Consider the following program:

```<code>fn primes_up_to(n: usize) -> Vec<usize> {
    let mut ans = Vec::with_capacity(n);

    if n < 2 {
        return ans;
    }

    ans.push(2);

    // https://doc.rust-lang.org/1.22.0/book/first-edition/closures.html#closures-and-their-environment
    // The closure needs ownership of vec to access elements
    let is_prime = |n: usize| -> bool {
        for x in ans {
            if x * x > n {
                break;
            }

            if n % x == 0 {
                return false;
            }
        }

        true
    };

    let mut i = 3;
    while i <= n {
        if is_prime(i) {
            ans.push(i);
        }

        i += 2;
    }

    ans
}

fn main() {
    println!("{:?}", primes_up_to(23));
}
</code>```

(playground)

Compiling the code above gives these compilation errors:

error[E0382]: use of moved value: `is_prime`
  --> src/main.rs:28:12
   |
28 |         if is_prime(i) {
   |            ^^^^^^^^ value moved here in previous iteration of loop
   |
note: closure cannot be invoked more than once because it moves the variable `ans` out of its environment
  --> src/main.rs:13:18
   |
13 |         for x in ans {
   |                  ^^^

error[E0382]: use of moved value: `ans`
  --> src/main.rs:29:13
   |
12 |     let is_prime = |n: usize| -> bool {
   |                    ------------------ value moved (into closure) here
...
29 |             ans.push(i);
   |             ^^^ value used here after move
   |
   = note: move occurs because `ans` has type `std::vec::Vec<usize>`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `ans`
  --> src/main.rs:35:5
   |
12 |     let is_prime = |n: usize| -> bool {
   |                    ------------------ value moved (into closure) here
...
35 |     ans
   |     ^^^ value used here after move
   |
   = note: move occurs because `ans` has type `std::vec::Vec<usize>`, which does not implement the `Copy` trait
```

I know a potential solution would be to pass an immutable reference to ans (&ans) to is_prime. What is the idiomatic way for ownership of ans to pass into is_prime and come back out when is_prime exits every time I call is_prime?

答:
There are some issues with your code, in:

```<code>for x in ans {
</code>```

closure cannot be invoked more than once because it moves the variable
  ans out of its environment:

The iterator invalidates with each ans.push(i);

So you should borrow the ans exactly in this line:

```<code>if is_prime(i) {
</code>```

then give it back to the next line:

```<code>ans.push(i);
</code>```

The solution is to pass it as an argument:

```<code>fn primes_up_to(n: usize) -> Vec<usize> {
    let mut ans = Vec::with_capacity(n);
    if n < 2 {
        return ans;
    }
    ans.push(2);
    let is_prime = |n: usize, v: &[usize]| -> bool {
        for x in v {
            if x * x > n {
                break;
            }
            if n % x == 0 {
                return false;
            }
        }
        true
    };
    let mut i: usize = 3;
    while i <= n {
        if is_prime(i, &ans) {
            ans.push(i);
        }
        i += 2;
    }
    ans
}

fn main() {
    println!("{:?}", primes_up_to(23));
}
</code>```

(playground)

Or try this, it has same ASM footprint as above in release mode on the nightly channel:

```<code>fn primes_up_to(n: usize) -> Vec<usize> {
    let mut ans = Vec::with_capacity(n);
    if n < 2 {
        return ans;
    }
    ans.push(2);
    let is_prime = |n: usize, v: &Vec<usize>| -> bool {
        for x in v {
            if x * x > n {
                break;
            }
            if n % x == 0 {
                return false;
            }
        }
        true
    };
    let mut i: usize = 3;
    while i <= n {
        if is_prime(i, &ans) {
            ans.push(i);
        }
        i += 2;
    }
    ans
}

fn main() {
    println!("{:?}", primes_up_to(23));
}
</code>```

(playground)

output:

[2, 3, 5, 7, 11, 13, 17, 19, 23]
```

And see: Move semantics and Borrowing

Body:
Consider the following program:

fn primes_up_to(n: usize) -> Vec<usize> {
    let mut ans = Vec::with_capacity(n);

    if n < 2 {
        return ans;
    }

    ans.push(2);

    // https://doc.rust-lang.org/1.22.0/book/first-edition/closures.html#closures-and-their-environment
    // The closure needs ownership of vec to access elements
    let is_prime = |n: usize| -> bool {
        for x in ans {
            if x * x > n {
                break;
            }

            if n % x == 0 {
                return false;
            }
        }

        true
    };

    let mut i = 3;
    while i <= n {
        if is_prime(i) {
            ans.push(i);
        }

        i += 2;
    }

    ans
}

fn main() {
    println!("{:?}", primes_up_to(23));
}

(playground)

Compiling the code above gives these compilation errors:

error[E0382]: use of moved value: `is_prime`
  --> src/main.rs:28:12
   |
28 |         if is_prime(i) {
   |            ^^^^^^^^ value moved here in previous iteration of loop
   |
note: closure cannot be invoked more than once because it moves the variable `ans` out of its environment
  --> src/main.rs:13:18
   |
13 |         for x in ans {
   |                  ^^^

error[E0382]: use of moved value: `ans`
  --> src/main.rs:29:13
   |
12 |     let is_prime = |n: usize| -> bool {
   |                    ------------------ value moved (into closure) here
...
29 |             ans.push(i);
   |             ^^^ value used here after move
   |
   = note: move occurs because `ans` has type `std::vec::Vec<usize>`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `ans`
  --> src/main.rs:35:5
   |
12 |     let is_prime = |n: usize| -> bool {
   |                    ------------------ value moved (into closure) here
...
35 |     ans
   |     ^^^ value used here after move
   |
   = note: move occurs because `ans` has type `std::vec::Vec<usize>`, which does not implement the `Copy` trait

I know a potential solution would be to pass an immutable reference to ans (&ans) to is_prime. What is the idiomatic way for ownership of ans to pass into is_prime and come back out when is_prime exits every time I call is_prime?

Body:
There are some issues with your code, in:

for x in ans {

closure cannot be invoked more than once because it moves the variable
  ans out of its environment:

The iterator invalidates with each ans.push(i);

So you should borrow the ans exactly in this line:

if is_prime(i) {

then give it back to the next line:

ans.push(i);

The solution is to pass it as an argument:

fn primes_up_to(n: usize) -> Vec<usize> {
    let mut ans = Vec::with_capacity(n);
    if n < 2 {
        return ans;
    }
    ans.push(2);
    let is_prime = |n: usize, v: &[usize]| -> bool {
        for x in v {
            if x * x > n {
                break;
            }
            if n % x == 0 {
                return false;
            }
        }
        true
    };
    let mut i: usize = 3;
    while i <= n {
        if is_prime(i, &ans) {
            ans.push(i);
        }
        i += 2;
    }
    ans
}

fn main() {
    println!("{:?}", primes_up_to(23));
}

(playground)

Or try this, it has same ASM footprint as above in release mode on the nightly channel:

fn primes_up_to(n: usize) -> Vec<usize> {
    let mut ans = Vec::with_capacity(n);
    if n < 2 {
        return ans;
    }
    ans.push(2);
    let is_prime = |n: usize, v: &Vec<usize>| -> bool {
        for x in v {
            if x * x > n {
                break;
            }
            if n % x == 0 {
                return false;
            }
        }
        true
    };
    let mut i: usize = 3;
    while i <= n {
        if is_prime(i, &ans) {
            ans.push(i);
        }
        i += 2;
    }
    ans
}

fn main() {
    println!("{:?}", primes_up_to(23));
}

(playground)

output:

[2, 3, 5, 7, 11, 13, 17, 19, 23]

And see: Move semantics and Borrowing


问:
Sort by reverse order mongoose

Hi, I am trying to return my query in backwards order from which it was created.

The docs are a little unclear on how to use the sort method:
http://mongoosejs.com/docs/api.html#types_array_MongooseArray.sort

Here is my schema:

```<code>const mongoose = require('mongoose'),
    Schema     = mongoose.Schema,
    ObjectId   = Schema.Types.ObjectId;

let PostSchema = new Schema({
    title      : String,
    description: String,
    image      : String,
    tags       : [String],
    original_poster: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    date: {
       type: Date,
       default: new Date()
   }
})

module.exports = mongoose.model('Post',PostSchema);
</code>```

I have run,

```<code>db.posts.find().sort({date:-1}).pretty()
</code>```

For example, if my model was a 'Post' model and my first post was 'hello world' and my second post was 'this is a post'. I would like to see:

```<code> ['this is a post', 'hello world']
</code>```

However, what I am actually seeing is ['hello world','this is a post']

答:
Figured out the answer

in posts schema add:

```<code>date: {
    type: Date,
    default: Date.now
}
</code>```

then db.posts.find().sort({date:-1}).pretty() will yield the posts sorted from most recent to least recent

Title: Sort by reverse order mongoose

Body:
Hi, I am trying to return my query in backwards order from which it was created.

The docs are a little unclear on how to use the sort method:
http://mongoosejs.com/docs/api.html#types_array_MongooseArray.sort

Here is my schema:

const mongoose = require('mongoose'),
    Schema     = mongoose.Schema,
    ObjectId   = Schema.Types.ObjectId;

let PostSchema = new Schema({
    title      : String,
    description: String,
    image      : String,
    tags       : [String],
    original_poster: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    date: {
       type: Date,
       default: new Date()
   }
})

module.exports = mongoose.model('Post',PostSchema);

I have run,

db.posts.find().sort({date:-1}).pretty()

For example, if my model was a 'Post' model and my first post was 'hello world' and my second post was 'this is a post'. I would like to see:

 ['this is a post', 'hello world']

However, what I am actually seeing is ['hello world','this is a post']

Body:
Figured out the answer

in posts schema add:

date: {
    type: Date,
    default: Date.now
}

then db.posts.find().sort({date:-1}).pretty() will yield the posts sorted from most recent to least recent


问:
bash scripting - how to write an effective case statement to handle multiple conditions
I have a script that reads a main list, call it List A using a while loop.

List A:

```<code>east-1-1
east-1-2
east-1-3
east-1-4
east-1-5
east-1-6
east-1-7
west-1-1
west-1-10
south-1-1
south-1-2
north-1-1
</code>```

What I would like to do is check it against this list:

```<code>east-1-1
east-1-3
east-1-7
west-1-10
south-1-2
</code>```

As listed in my case and for each of those items in my case I would like to flag down with an *

```<code>  case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
  esac
</code>```

I am doing this within a function and using a case statement, however I think I'm doing this wrong and would like to know if there's a better way? Should I be using an if-then-else? Can I do this with the case?

If I could please get some help on this approach or if there's a better way to write this.

CODE IN PROGRESS:

```<code>#!/usr/local/bin/bash

MAP=./.clusterinfo
if ! [ -f "$MAP" ]; then
      echo "Cluster Map not found."
      exit 1
fi

while IFS='' read -r cluster; do
#Function runQuery
runQuery()
{
  getCount=$(PGPASSWORD=Abc123Pa55word psql -h myapp-"${cluster}".foobar.com -U foo -d dev -p 5439 -t -c "select count(*) from pg_database;")

  case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
  esac
    echo "${cluster}:${getCount}"
}

#Execute
runQuery

done < "$MAP"
</code>```

Current Output:

```<code>east-1-1:    50 *
east-1-1:    50
east-1-2:     8
east-1-3:    58 *
east-1-3:    58
east-1-4:     5
east-1-5:     5
east-1-6:     4
east-1-7:    30 *
east-1-7:    30
west-1-1:     4
west-1-10:   50 *
west-1-10:   50
south-1-2:   30 *
south-1-2:   30
</code>```

Expected Output:

```<code>east-1-1:    50 *
east-1-2:     8
east-1-3:    58 *
east-1-4:     5
east-1-5:     5
east-1-6:     4
east-1-7:    30 *
west-1-1:     4
west-1-10:   50 *
south-1-2:   30 *
</code>```

答:
If their action is the same, you can simplify by enumerating all the corresponding cases in the same branch.

```<code>case $cluster in
    east-1-[137] | west-1-10 | south-1-2 )
      echo "$cluster:$getCount * ";;
    *)
      echo "$cluster:$getCount";;
esac
</code>```

(The default handling is copy/pasted from the currently accepted answer.)

Additionally, you might want to factor out the code which is identical in both cases.

```<code>suffix=''
case $cluster in
    east-1-[137] | west-1-10 | south-1-2 )
      suffix=' * ';;
esac
echo "$cluster:$getCount$suffix"
</code>```

Body:
I have a script that reads a main list, call it List A using a while loop.

List A:

east-1-1
east-1-2
east-1-3
east-1-4
east-1-5
east-1-6
east-1-7
west-1-1
west-1-10
south-1-1
south-1-2
north-1-1

What I would like to do is check it against this list:

east-1-1
east-1-3
east-1-7
west-1-10
south-1-2

As listed in my case and for each of those items in my case I would like to flag down with an *

  case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
  esac

I am doing this within a function and using a case statement, however I think I'm doing this wrong and would like to know if there's a better way? Should I be using an if-then-else? Can I do this with the case?

If I could please get some help on this approach or if there's a better way to write this.

CODE IN PROGRESS:

#!/usr/local/bin/bash

MAP=./.clusterinfo
if ! [ -f "$MAP" ]; then
      echo "Cluster Map not found."
      exit 1
fi

while IFS='' read -r cluster; do
#Function runQuery
runQuery()
{
  getCount=$(PGPASSWORD=Abc123Pa55word psql -h myapp-"${cluster}".foobar.com -U foo -d dev -p 5439 -t -c "select count(*) from pg_database;")

  case "${cluster}" in
    east-1-1)
      echo "${cluster}:${getCount} * ";;
    east-1-3)
      echo "${cluster}:${getCount} * ";;
    east-1-7)
      echo "${cluster}:${getCount} * ";;
    west-1-10)
      echo "${cluster}:${getCount} * ";;
    south-1-2)
      echo "${cluster}:${getCount} * ";;
  esac
    echo "${cluster}:${getCount}"
}

#Execute
runQuery

done < "$MAP"

Current Output:

east-1-1:    50 *
east-1-1:    50
east-1-2:     8
east-1-3:    58 *
east-1-3:    58
east-1-4:     5
east-1-5:     5
east-1-6:     4
east-1-7:    30 *
east-1-7:    30
west-1-1:     4
west-1-10:   50 *
west-1-10:   50
south-1-2:   30 *
south-1-2:   30

Expected Output:

east-1-1:    50 *
east-1-2:     8
east-1-3:    58 *
east-1-4:     5
east-1-5:     5
east-1-6:     4
east-1-7:    30 *
west-1-1:     4
west-1-10:   50 *
south-1-2:   30 *

Body:
If their action is the same, you can simplify by enumerating all the corresponding cases in the same branch.

case $cluster in
    east-1-[137] | west-1-10 | south-1-2 )
      echo "$cluster:$getCount * ";;
    *)
      echo "$cluster:$getCount";;
esac

(The default handling is copy/pasted from the currently accepted answer.)

Additionally, you might want to factor out the code which is identical in both cases.

suffix=''
case $cluster in
    east-1-[137] | west-1-10 | south-1-2 )
      suffix=' * ';;
esac
echo "$cluster:$getCount$suffix"


问:
SQL query where ALL records in a join match a condition?
I have what seems to be a simple problem, but can not figure out the proper solution via SQL. I'm using postgresql specifically.

Take the following:

```<code>SELECT *
FROM users INNER JOIN tags
  ON (tags.user_id = users.id)
WHERE tags.name IN ('word1', 'word2')
</code>```

This does not do what I need. I want to find users whose tags are ONLY included in the list. If the user has a tag that is not in the list, the user should not be included.

'user1' tags: word1, word2, word3

'user2' tags: word1

'user3' tags: word1, word2

Given: word1 and word2. I want to prepare a query that returns 'user2' and 'user3'. 'user1' is excluded because it has a tag that is not in the list.

Hopefully I made this clear. Thanks for your help!

答:
```<code>SELECT  user_id
FROM    users
WHERE   id IN
        (
        SELECT  user_id
        FROM    tags
        )
        AND id NOT IN
        (
        SELECT  user_id
        FROM    tags
        WHERE   name NOT IN ('word1', 'word2')
        )
</code>```

or

```<code>SELECT  u.*
FROM    (
        SELECT  DISTINCT user_id
        FROM    tags
        WHERE   name IN ('word1', 'word2')
        ) t
JOIN    users u
ON      u.id = t.user_id
        AND t.user_id NOT IN
        (
        SELECT  user_id
        FROM    tags
        WHERE   name NOT IN ('word1', 'word2')
        )
</code>```

Body:
I have what seems to be a simple problem, but can not figure out the proper solution via SQL. I'm using postgresql specifically.

Take the following:

SELECT *
FROM users INNER JOIN tags
  ON (tags.user_id = users.id)
WHERE tags.name IN ('word1', 'word2')

This does not do what I need. I want to find users whose tags are ONLY included in the list. If the user has a tag that is not in the list, the user should not be included.

'user1' tags: word1, word2, word3

'user2' tags: word1

'user3' tags: word1, word2

Given: word1 and word2. I want to prepare a query that returns 'user2' and 'user3'. 'user1' is excluded because it has a tag that is not in the list.

Hopefully I made this clear. Thanks for your help!

Body:
SELECT  user_id
FROM    users
WHERE   id IN
        (
        SELECT  user_id
        FROM    tags
        )
        AND id NOT IN
        (
        SELECT  user_id
        FROM    tags
        WHERE   name NOT IN ('word1', 'word2')
        )

or

SELECT  u.*
FROM    (
        SELECT  DISTINCT user_id
        FROM    tags
        WHERE   name IN ('word1', 'word2')
        ) t
JOIN    users u
ON      u.id = t.user_id
        AND t.user_id NOT IN
        (
        SELECT  user_id
        FROM    tags
        WHERE   name NOT IN ('word1', 'word2')
        )


问:
Is the  tag purely semantic or can i use it like a
 tag and style it?
Since HTML5 introduced some new tags such as header, footer, aside, nav, etc. I wanted to know if it was good practice to use those tags like they were a div tag?

Let me explain:

I want to have a fixed menu on my website that stays fixed on the top as the user scrolls down the page, so I created a header tag and then i used CSS and gave it a position: fixed; and gave it some other rules...

^Is this recommended? (Giving the header tag some styles)
Or is the header tag only used for markup purposes?

Should I create a div tag inside the header tag and style that div tag? Or is it fine to just style the header tag?

```<code><header>

</header>
</code>```

OR

```<code><header>
 <div id="header>

 </div>
</header>
</code>```

This question also applies to the footer tag and those new HTML5 tags that are used for markup.

答:
A  header tag typically contains heading tag(Not restricted). You can also use the elements like table of contents, logos etc.

You can also style the header

But in legacy browser like (IE <9) to render the  element as a block level element you will need to explicitly declare it as a block in your CSS like so: header { display:block;}

I don't think there is any need of  tag.

Title: Is the <header> tag purely semantic or can i use it like a <div> tag and style it?

Body:
Since HTML5 introduced some new tags such as header, footer, aside, nav, etc. I wanted to know if it was good practice to use those tags like they were a div tag?

Let me explain:

I want to have a fixed menu on my website that stays fixed on the top as the user scrolls down the page, so I created a header tag and then i used CSS and gave it a position: fixed; and gave it some other rules...

^Is this recommended? (Giving the header tag some styles)
Or is the header tag only used for markup purposes?

Should I create a div tag inside the header tag and style that div tag? Or is it fine to just style the header tag?

OR

This question also applies to the footer tag and those new HTML5 tags that are used for markup.


问:
mcrypt is deprecated, what is the alternative?
The mcrypt-extension is deprecated will be removed in PHP 7.2 according to the comment posted here. So I am looking for an alternative way to encrypt passwords.

Right now I am using something like

```<code>mcrypt_encrypt(MCRYPT_RIJNDAEL_128, md5($key, true), $string, MCRYPT_MODE_CBC, $iv)
</code>```

I need your opinion for the best/strongest way to encrypt passwords, the encrypted password should of course supported by PHP 7.xx and should also be decryptable because my customers do want to have an option to 'recover' their passwords without generating a new one.

答:
I was able to translate my Crypto object

Get a copy of php with mcrypt to decrypt the old data.  I went to http://php.net/get/php-7.1.12.tar.gz/from/a/mirror, compiled it, then added the ext/mcrypt extension (configure;make;make install). I think I had to add the extenstion=mcrypt.so line to the php.ini as well.  A series of scripts to build intermediate versions of the data with all data unencrypted.

Build a public and private key for openssl

```<code>openssl genrsa -des3 -out pkey.pem 2048
(set a password)
openssl rsa -in pkey.pem -out pkey-pub.pem -outform PEM -pubout
</code>```

To Encrypt (using public key) use openssl_seal. From what I've read, openssl_encrypt using an RSA key is limited to 11 bytes less than the key length (See http://php.net/manual/en/function.openssl-public-encrypt.php comment by Thomas Horsten)

```<code>$pubKey = openssl_get_publickey(file_get_contents('./pkey-pub.pem'));
openssl_seal($pwd, $sealed, $ekeys, [ $pubKey ]);
$encryptedPassword = base64_encode($sealed);
$key = base64_encode($ekeys[0]);
</code>```

You could probably store the raw binary.

To Decrypt (using private key)

```<code>$passphrase="passphrase here";
$privKey = openssl_get_privatekey(file_get_contents('./pkey.pem'), $passphrase);
// I base64_decode() from my db columns
openssl_open($encryptedPassword, $plain, $key, $privKey);
echo "<h3>Password=$plain</h3>";
</code>```

P.S. You can't encrypt the empty string ("")

P.P.S. This is for a password database not for user validation.

Body:
The mcrypt-extension is deprecated will be removed in PHP 7.2 according to the comment posted here. So I am looking for an alternative way to encrypt passwords.

Right now I am using something like

mcrypt_encrypt(MCRYPT_RIJNDAEL_128, md5($key, true), $string, MCRYPT_MODE_CBC, $iv)

I need your opinion for the best/strongest way to encrypt passwords, the encrypted password should of course supported by PHP 7.xx and should also be decryptable because my customers do want to have an option to 'recover' their passwords without generating a new one.

Body:
I was able to translate my Crypto object

Get a copy of php with mcrypt to decrypt the old data.  I went to http://php.net/get/php-7.1.12.tar.gz/from/a/mirror, compiled it, then added the ext/mcrypt extension (configure;make;make install). I think I had to add the extenstion=mcrypt.so line to the php.ini as well.  A series of scripts to build intermediate versions of the data with all data unencrypted.

Build a public and private key for openssl

openssl genrsa -des3 -out pkey.pem 2048
(set a password)
openssl rsa -in pkey.pem -out pkey-pub.pem -outform PEM -pubout

To Encrypt (using public key) use openssl_seal. From what I've read, openssl_encrypt using an RSA key is limited to 11 bytes less than the key length (See http://php.net/manual/en/function.openssl-public-encrypt.php comment by Thomas Horsten)

$pubKey = openssl_get_publickey(file_get_contents('./pkey-pub.pem'));
openssl_seal($pwd, $sealed, $ekeys, [ $pubKey ]);
$encryptedPassword = base64_encode($sealed);
$key = base64_encode($ekeys[0]);

You could probably store the raw binary.

To Decrypt (using private key)

$passphrase="passphrase here";
$privKey = openssl_get_privatekey(file_get_contents('./pkey.pem'), $passphrase);
// I base64_decode() from my db columns
openssl_open($encryptedPassword, $plain, $key, $privKey);
echo "<h3>Password=$plain</h3>";

P.S. You can't encrypt the empty string ("")

P.P.S. This is for a password database not for user validation.