问:
Sending query parameters to a POST request laravel
I wish to send a query like string to a POST request, this string is in a variable called $info

```<code> $info = firstname=testing123&lastname=testing123&email=testing13@gmail.com&number=123
</code>```

So my routes will be like this

```<code>Route::post('/action/{date}/{time}/{info}', 'Action@confirm');
</code>```

And my form like this

```<code><form action="/confirmation/{{$date}}/{{$time}}/{{$info}}" method="POST">
      {{ csrf_field() }}
      <input type="text" name="action" required>
      <button>Submit</button>
      </form>
</code>```

I cannot pass the $info variable, I get a No such file or directory error.

How can I pass a query like string to a POST request using routes?

答:
Query parameters do not need to be defined in the route. So you can remove the info parameter from the route definition.

```<code>Route::post('/action/{date}/{time}', 'Action@confirm');
</code>```

Then add the query string to your action on the form

```<code><form action="/confirmation/{{$date}}/{{$time}}?{{$info}}" method="POST">
    ...
</form>
</code>```

And in the controller you can access the data the same way you would any other parameter

```<code>$firstname= $request->get('firstname');
</code>```

Alternatively I would consider a different way of transmitting that data. From what you've provided it looks like might be more appropriate to store that data in the session then retrieve it from the session in the Action@confirm method.

Body:
I wish to send a query like string to a POST request, this string is in a variable called $info

 $info = firstname=testing123&lastname=testing123&email=testing13@gmail.com&number=123

So my routes will be like this

Route::post('/action/{date}/{time}/{info}', 'Action@confirm');

And my form like this

<form action="/confirmation/{{$date}}/{{$time}}/{{$info}}" method="POST">
      {{ csrf_field() }}
      <input type="text" name="action" required>
      <button>Submit</button>
      </form>

I cannot pass the $info variable, I get a No such file or directory error.

How can I pass a query like string to a POST request using routes?

Body:
Query parameters do not need to be defined in the route. So you can remove the info parameter from the route definition.

Route::post('/action/{date}/{time}', 'Action@confirm');

Then add the query string to your action on the form

<form action="/confirmation/{{$date}}/{{$time}}?{{$info}}" method="POST">
    ...
</form>

And in the controller you can access the data the same way you would any other parameter

$firstname= $request->get('firstname');

Alternatively I would consider a different way of transmitting that data. From what you've provided it looks like might be more appropriate to store that data in the session then retrieve it from the session in the Action@confirm method.


来源: stackexchange

问:
recursive move command on windows
I need to do a .bat copy of a .sh, I don't know much Windows cmd.
On Linux I could do

```<code>mv ...
</code>```

or

```<code>rsync -a SOURCE/ DEST/ --remove-sent-files --ignore-existing --whole-file
</code>```

but Windows "move" can't do the same

maybe there is a windows simple alternative, simpler and more performant than

```<code>for /R c:\sourceFolder\ %%G in (*) do ( move /Y "%%G" c:\destinationFolder\ )
</code>```

Linux mv seems to update directories pointer, but the above Windows command will do hard stuff? I guess it's not a good idea for the big folders I need to frequently move

答:
```<code>@echo off
setlocal
set DIR=
set OUTPUTDIR=C:\Documents and Settings\<username>\Desktop\sandbox1\output
for /R %DIR% %%a in (*.jpg) do xcopy "%%a" "%OUTPUTDIR%"
</code>```

ContentLicense: CC BY-SA 3.0

Title: recursive move command on windows

Body:
I need to do a .bat copy of a .sh, I don't know much Windows cmd.
On Linux I could do

mv ...

or

rsync -a SOURCE/ DEST/ --remove-sent-files --ignore-existing --whole-file

but Windows "move" can't do the same

maybe there is a windows simple alternative, simpler and more performant than

for /R c:\sourceFolder\ %%G in (*) do ( move /Y "%%G" c:\destinationFolder\ )

Linux mv seems to update directories pointer, but the above Windows command will do hard stuff? I guess it's not a good idea for the big folders I need to frequently move


问:
How to export image in powerpoint using asp.net core 2.0
I have to export some images into powerpoint (.ppt or .pptx format) using asp.net core 2.0. Any ideas welcome!</p>

答:
Maybe you could use SlideMight, a data merge tool for PowerPoint.

You should be able to get 1 slide per image, or 1 table row per image, or 1 table cell, or so. You can also make a thumbnail slide that links to 15 detail slides. You define this in a "pattern file", which is much like a PowerPoint template.

Your asp.net program should write the images to the file system, or have URLs available. It should also create an input data file (XML, JSON or YAML) that refers to these images. Then it should invoke SlideMight to generate the desired presentation. Normally SlideMight runs in a GUI. It should also be able to run as a command line program, although this has not been tested lately (please let me know if you need it).

Would this be of use?

Disclaimer: I am the developer and vendor of SlideMight.


问:
Validate user entry on Worksheet_Change event
Using Excel
I am having a devil of a time trying to get the included code to work.
I am attempting to restrict the values entered into a cell to only "A/B/C"  They can be entered in either upper or lower case.  If the value is entered in lower case then this script does successfully change the value to upper case.

The coding falls over when a value other than "A/B/C" is entered.

What I am trying to achieve is the following:

nothing is entered and passes the sanity check

A is entered and passes the sanity check

B is entered and passes the sanity check

C is entered and passes the sanity check

a is entered and fails the sanity check, is converted to A

b is entered and fails the sanity check, is converted to B

c is entered and fails the sanity check, is converted to C

anything else is entered and fails the sanity check, is converted to "" (Empty)

I have remarked out the line that fails.

```<code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Intersect(Target, Range("C9:C51")) Is Nothing Then
    Else
        With Target
            If UCase(.Text) <> .Text Then
                .Value = UCase(.Text)
            ' ElseIf .Text < "A" Or .Text > "C" Then .Value = ""
            End If
        End With
    End If
End Sub
</code>```

Can anyone suggest a solution to this problem ?

答:
Perhaps:

    Private Sub Worksheet_Change(ByVal Target As Excel.Range)
        If Intersect(Target, Range("C9:C51")) Is Nothing Then
        Else
            With Target
                If UCase(.Text) <> .Text Then
                    .Value = UCase(.Text)
                    If .Value = "A" Or .Value = "B" Or .Value = "C" Then
                    Else
                        .ClearContents
                    End If
                End If
            End With
        End If
    End Sub

EDIT#1:

Based on the comment below, this should be used instead:

```<code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Intersect(Target, Range("C9:C51")) Is Nothing Then
    Else
        With Target
                Application.EnableEvents = False
                    .Value = UCase(.Text)
                    If .Value = "A" Or .Value = "B" Or .Value = "C" Then
                    Else
                        .ClearContents
                    End If
                Application.EnableEvents = True
        End With
    End If
End Sub
</code>```

Body:
Using Excel
I am having a devil of a time trying to get the included code to work.
I am attempting to restrict the values entered into a cell to only "A/B/C"  They can be entered in either upper or lower case.  If the value is entered in lower case then this script does successfully change the value to upper case.

The coding falls over when a value other than "A/B/C" is entered.

What I am trying to achieve is the following:

nothing is entered and passes the sanity check

A is entered and passes the sanity check

B is entered and passes the sanity check

C is entered and passes the sanity check

a is entered and fails the sanity check, is converted to A

b is entered and fails the sanity check, is converted to B

c is entered and fails the sanity check, is converted to C

anything else is entered and fails the sanity check, is converted to "" (Empty)

I have remarked out the line that fails.

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Intersect(Target, Range("C9:C51")) Is Nothing Then
    Else
        With Target
            If UCase(.Text) <> .Text Then
                .Value = UCase(.Text)
            ' ElseIf .Text < "A" Or .Text > "C" Then .Value = ""
            End If
        End With
    End If
End Sub

Can anyone suggest a solution to this problem ?

Body:
Perhaps:

    Private Sub Worksheet_Change(ByVal Target As Excel.Range)
        If Intersect(Target, Range("C9:C51")) Is Nothing Then
        Else
            With Target
                If UCase(.Text) <> .Text Then
                    .Value = UCase(.Text)
                    If .Value = "A" Or .Value = "B" Or .Value = "C" Then
                    Else
                        .ClearContents
                    End If
                End If
            End With
        End If
    End Sub

EDIT#1:

Based on the comment below, this should be used instead:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Intersect(Target, Range("C9:C51")) Is Nothing Then
    Else
        With Target
                Application.EnableEvents = False
                    .Value = UCase(.Text)
                    If .Value = "A" Or .Value = "B" Or .Value = "C" Then
                    Else
                        .ClearContents
                    End If
                Application.EnableEvents = True
        End With
    End If
End Sub


问:
Optimizing MySQL update query
This is currently my MySQL UPDATE query, which is called from program written in Java:

```<code>String query = "UPDATE maxday SET DatePressureREL = (SELECT " +
   "Date FROM ws3600 WHERE PressureREL = (SELECT MAX" +
   "(PressureREL) FROM ws3600 WHERE Date >= '" + Date +
   "') AND Date >= '" + Date + "' ORDER BY Date DESC LIMIT 1), " +
   "PressureREL = (SELECT PressureREL FROM ws3600 WHERE " +
   "PressureREL = (SELECT MAX(PressureREL) FROM ws3600 " +
   "WHERE Date >= '" + Date + "') AND Date >= '" + Date +
   "' ORDER BY Date DESC LIMIT 1), ...";

try {
    s.execute(query);
}
catch (SQLException e) {
    System.out.println("SQL error");
}
catch(Exception e) {
    e.printStackTrace();
}
</code>```

Let me explain first, what does it do. I have two tables, first is ws3600, which holds columns (Date, PressureREL, TemperatureOUT, Dewpoint, ...). Then I have second table, called maxday, which holds columns like DatePressureREL, PressureREL, DateTemperatureOUT, TemperatureOUT,... Now as you can see from an example, I update each column, the question is, is there a faster way? I am asking this, because I am calling MAX twice, first to find the Date for that value and secondly to find the actual value. Now I know that I could write like that:

```<code>SELECT Date, PressureREL FROM ws3600 WHERE PressureREL =
  (SELECT MAX(PressureREL) FROM ws3600 WHERE Date >= '" +
  Date + "') AND Date >= '" + Date + "'
ORDER BY Date DESC LIMIT 1
</code>```

That way I get the Date of the max and the max value at the same time and then update with those values the data in maxday table. But the problem of this solution is, that I have to execute many queries, which as I understand takes alot more time compared to executing one long mysql query because of overhead in sending each query to the server.

If there is no better way, which solution beetwen this two should I choose. The first, which only takes one query but is very unoptimized or the second which is beter in terms of optimization, but needs alot more queries which probably means that the preformance gain is lost because of overhead in sending each query to the server?

答:
If you can get all the values in one select query, this might work.  Use a stored procedure accepting one parameter (date) that does:

One select statement, storing the values in a cursor, and

One update statement, using the values in the cursor.

Cursor Example

ContentLicense: CC BY-SA 2.5

Title: Optimizing MySQL update query

Body:
This is currently my MySQL UPDATE query, which is called from program written in Java:

String query = "UPDATE maxday SET DatePressureREL = (SELECT " +
   "Date FROM ws3600 WHERE PressureREL = (SELECT MAX" +
   "(PressureREL) FROM ws3600 WHERE Date >= '" + Date +
   "') AND Date >= '" + Date + "' ORDER BY Date DESC LIMIT 1), " +
   "PressureREL = (SELECT PressureREL FROM ws3600 WHERE " +
   "PressureREL = (SELECT MAX(PressureREL) FROM ws3600 " +
   "WHERE Date >= '" + Date + "') AND Date >= '" + Date +
   "' ORDER BY Date DESC LIMIT 1), ...";

try {
    s.execute(query);
}
catch (SQLException e) {
    System.out.println("SQL error");
}
catch(Exception e) {
    e.printStackTrace();
}

Let me explain first, what does it do. I have two tables, first is ws3600, which holds columns (Date, PressureREL, TemperatureOUT, Dewpoint, ...). Then I have second table, called maxday, which holds columns like DatePressureREL, PressureREL, DateTemperatureOUT, TemperatureOUT,... Now as you can see from an example, I update each column, the question is, is there a faster way? I am asking this, because I am calling MAX twice, first to find the Date for that value and secondly to find the actual value. Now I know that I could write like that:

SELECT Date, PressureREL FROM ws3600 WHERE PressureREL =
  (SELECT MAX(PressureREL) FROM ws3600 WHERE Date >= '" +
  Date + "') AND Date >= '" + Date + "'
ORDER BY Date DESC LIMIT 1

That way I get the Date of the max and the max value at the same time and then update with those values the data in maxday table. But the problem of this solution is, that I have to execute many queries, which as I understand takes alot more time compared to executing one long mysql query because of overhead in sending each query to the server.

If there is no better way, which solution beetwen this two should I choose. The first, which only takes one query but is very unoptimized or the second which is beter in terms of optimization, but needs alot more queries which probably means that the preformance gain is lost because of overhead in sending each query to the server?


问:
Maximize the minimum element
We have an array of N positive elements. We can perform M operations on this array. In each operation we have to select a subarray(contiguous) of length W and increase each element by 1. Each element of the array can be increased at most K times.
We have to perform these operations such that the minimum element in the array is maximized.

1 <= N, W <= 10^5

1 <= M, K <= 10^5

Time limit: 1 sec

I can think of an O(n^2) solution but it is exceeding time limit. Can somebody provide an O(nlogn) or better solution for this?

P.S.- This is an interview question

答:
What if we kept a copy of the array sorted ascending, pointing each element to its original index? Think about the order of priority when incrementing the elements. Also, does the final order of operations matter?

Once the lowest element reaches the next lowest element, what must then be incremented? And if we apply k operations to any one element does it matter in which w those increments were applied?

Title: Maximize the minimum element


问:
Error with writing Parquet files to local disk
I am writing spark dataframes on local disk and I cannot read it back.

```<code>val path = "file:///mnt/resources/....."
df.write.parquet(path)
val d = spark.read.parquet(path)
</code>```

I get the following error:

```<code>org.apache.spark.sql.AnalysisException: Unable to infer schema for Parquet. It must be specified manually.;
</code>```

I am fine with reading and writing from/to Azure Datalake or Storage, but not with local disk.
Has anyone face the same issue? how to solve it?  I tested with .csv files also, and in that case, it says the file does not exist, even I can see the file when I login to the worker nodes.

答:
TL;DR Writes to local file system are useful only for testing in local mode.

You should not use local file system for writes when using cluster deployment. In that case each executor writes to its own file system, and it just impossible to achieve consistent reads afterwards.

Body:
I am writing spark dataframes on local disk and I cannot read it back.

val path = "file:///mnt/resources/....."
df.write.parquet(path)
val d = spark.read.parquet(path)

I get the following error:

org.apache.spark.sql.AnalysisException: Unable to infer schema for Parquet. It must be specified manually.;

I am fine with reading and writing from/to Azure Datalake or Storage, but not with local disk.
Has anyone face the same issue? how to solve it?  I tested with .csv files also, and in that case, it says the file does not exist, even I can see the file when I login to the worker nodes.


问:
SVN dump of Apache Lucene’s repository
I want to take SVN dump of Apache Lucene’s repository. How to replicate the above repo to my local machine?</p>

答:
You can use the svn command line tool.

```<code>svn export http://svn.apache.org/repos/asf/lucene/dev/trunk/
</code>```

or

```<code>svn co http://svn.apache.org/repos/asf/lucene/dev/trunk/
</code>```

Use the first if you want a disconnected dump.  Use the second if you want to update and commit.

Title: SVN dump of Apache Lucene’s repository

Body:
You can use the svn command line tool.

svn export http://svn.apache.org/repos/asf/lucene/dev/trunk/

or

svn co http://svn.apache.org/repos/asf/lucene/dev/trunk/

Use the first if you want a disconnected dump.  Use the second if you want to update and commit.


问:
UWP - Center Text Vertically in TextBlock
So there is an existing thread which states that in order to vertically align text, you need to wrap in a border.  However, I tried this, and instead of aligning vertically, the TextBlock went in a corner, still vertically aligned to the top.  I don't know if this has something to do with the differences of WPF and UWP, but no matter, it didn't work.  My TextBlock is defined as follows:

```<code><TextBlock x:Name="TextBlock" Margin="855,226,0,0" TextWrapping="Wrap"
     VerticalAlignment="Top" Height="150" Width="150" FontFamily="DOCK11"
     TextAlignment="Center" Padding="0" HorizontalAlignment="Left" Text="Sample Text..."/>`
</code>```

With the given dimensions, would it be possible to vertically align my TextBlock's text?  Thanks in advance.

答:
According to the documentation TextBlock.TextAlignment

Gets or sets a value that indicates the horizontal alignment of text content.

To achieve your goal you indeed should wrap TextBlock with a Border and set it's VerticalAlignment to Center.

```<code>    <Border Height="150"
            Width="150"
            Margin="855,226,0,0">
        <TextBlock TextWrapping="Wrap"
                   FontFamily="DOCK11"
                   TextAlignment="Center"
                   VerticalAlignment="Center"
                   Padding="0"
                   Text="Sample Text..."/>
   </Border>
</code>```

Body:
So there is an existing thread which states that in order to vertically align text, you need to wrap in a border.  However, I tried this, and instead of aligning vertically, the TextBlock went in a corner, still vertically aligned to the top.  I don't know if this has something to do with the differences of WPF and UWP, but no matter, it didn't work.  My TextBlock is defined as follows:

<TextBlock x:Name="TextBlock" Margin="855,226,0,0" TextWrapping="Wrap"
     VerticalAlignment="Top" Height="150" Width="150" FontFamily="DOCK11"
     TextAlignment="Center" Padding="0" HorizontalAlignment="Left" Text="Sample Text..."/>`

With the given dimensions, would it be possible to vertically align my TextBlock's text?  Thanks in advance.

Body:
According to the documentation TextBlock.TextAlignment

Gets or sets a value that indicates the horizontal alignment of text content.

To achieve your goal you indeed should wrap TextBlock with a Border and set it's VerticalAlignment to Center.

    <Border Height="150"
            Width="150"
            Margin="855,226,0,0">
        <TextBlock TextWrapping="Wrap"
                   FontFamily="DOCK11"
                   TextAlignment="Center"
                   VerticalAlignment="Center"
                   Padding="0"
                   Text="Sample Text..."/>
   </Border>


问:
What's the best language/platform for SOA on Linux in a post-Java world?
I need to choose a language/platform for the new development of a series of services in a SOA. I'm looking into Scala and Clojure but don't think the community and products are mature enough for a real-world enterprise product yet.

Update/Clarifications:

Of course we can use many languages/platforms for SOA but some language/platforms are easier and more suited for an SOA. IMO the best ones for SOA should allow interface programming (to ease definition of contracts), should have options for hosting the services (like Felix for Java or WCF in .NET) and scale well (see Twitter issues with RoR).

Java has always been the favourite in the enterprise market. However, many developers are looking into dynamic languages as well as talking about stagnation of Java after v6. As a result many new post Java languages have arrived: Scala, Clojure and Groovy to name a few that still run on JVM but are not Java.

I hope these clarify the question.

答:
Depends what you mean by "mature enough for a real-world enterprise product", and your relative level of tolerance for living on the cutting edge.

For example, I'm currently building a "real-world enterprise product" in Clojure (I'd have been equally happy with Scala, it was only that Clojure fitted my needs slightly better from the concurrency and meta-programming perspective).

I'm very happy with my decision.

Some quick perspectives if you are considering this "post-Java" path:

The communities are great and supportive, but you'll still have to solve problems yourself, if only because nobody else has run into the same problem yet. None of these are likely to be insurmountable, but it does present a bit of extra risk to delivery schedules.

Both Scala and Clojure can be very productive (in terms of value delivered to customers per hour coding), but you can equally well write bad and unmaintainable code in any langauge. Java pretty much forces you to write things in a standardised, somewhat verbose but syntactically simple and understandable way. With Scala and Clojure you get a whole new arsenal of crazy ways to hit your target or shoot yourself in the foot. Is your team going to be able to make the best use of Scala/Clojure advantages?

It's harder (though by no means impossible) to bring skilled people on board with existing Clojure/Scala skills. On the flipside, the people who do have these skills (or are keen to acquire them) are likely to be among the more talented / motivated developers so the search may still be productive.

Be prepared to make tough decisions regarding whether to target language/library features that are "just round the corner". For example, do you wait for the enhanced primitive support coming in Clojure 1.3? Or make do with the perfectly adequate but slower boxed primitive functions in Clojure 1.2?

A great benefit of being on the JVM is that you can still take full advantage of the Java ecosystem without being tied to Java as a language. Don't underestimate how useful this is: for example, I use a number of extremely well tested, mature Java libraries (e.g. Netty) pretty much transparently in my Clojure application. This significantly reduces your risk and the amount of new development that you need to do.


问:
How to use an index on a variable
I have a list which I currently add items to in the following way:

```<code>public GameObject object1 = new GameObject("Example Data");
public GameObject object2 = new GameObject("Example Data");
public GameObject object3 = new GameObject("Example Data");
public GameObject object4 = new GameObject("Example Data");
public GameObject object5 = new GameObject("Example Data");
public GameObject object6 = new GameObject("Example Data");
public GameObject object7 = new GameObject("Example Data");
public GameObject object8 = new GameObject("Example Data");
public GameObject object9 = new GameObject("Example Data");
public GameObject object10 = new GameObject("Example Data");
List<GameObject> Objects = new List<GameObject>();

Objects.Add(object1);
Objects.Add(object2);
Objects.Add(object3);
Objects.Add(object4);
Objects.Add(object5);
Objects.Add(object6);
Objects.Add(object7);
Objects.Add(object8);
Objects.Add(object9);
Objects.Add(object10);
</code>```

How would I do this in C# using a foreach? I tried something like the following example but I couldn't get it to work:

```<code>foreach (var number in Enumerable.Range(1, 10))
{
    Objects.Add("object" + [number]);
}
</code>```

答:
I would recommend a for loop.  Loop through i times and create a new object and add it to your list.

```<code>for(int i = 0; i < 10; i++)
{
    GameObject ob = new GameObject("Example Data " + i);
    Objects.Add(ob);
}
</code>```

Title: How to use an index on a variable

Body:
I have a list which I currently add items to in the following way:

public GameObject object1 = new GameObject("Example Data");
public GameObject object2 = new GameObject("Example Data");
public GameObject object3 = new GameObject("Example Data");
public GameObject object4 = new GameObject("Example Data");
public GameObject object5 = new GameObject("Example Data");
public GameObject object6 = new GameObject("Example Data");
public GameObject object7 = new GameObject("Example Data");
public GameObject object8 = new GameObject("Example Data");
public GameObject object9 = new GameObject("Example Data");
public GameObject object10 = new GameObject("Example Data");
List<GameObject> Objects = new List<GameObject>();

Objects.Add(object1);
Objects.Add(object2);
Objects.Add(object3);
Objects.Add(object4);
Objects.Add(object5);
Objects.Add(object6);
Objects.Add(object7);
Objects.Add(object8);
Objects.Add(object9);
Objects.Add(object10);

How would I do this in C# using a foreach? I tried something like the following example but I couldn't get it to work:

foreach (var number in Enumerable.Range(1, 10))
{
    Objects.Add("object" + [number]);
}

Body:
I would recommend a for loop.  Loop through i times and create a new object and add it to your list.

for(int i = 0; i < 10; i++)
{
    GameObject ob = new GameObject("Example Data " + i);
    Objects.Add(ob);
}


问:
Time missing when running query using Oracle sqlplus
I have the following script that I am running using sqlplus

```<code>set headsep off
set pagesize 0

spool 'c:\file.csv'
select to_char(trunc(created_date, 'hh')) AS reg_date, count(*)
from ORDERS.PRODUCT WHERE CREATED_DATE > TO_DATE('01/APR/2017','dd/mon/yyyy')
group by trunc(created_date, 'hh') ORDER BY reg_date DESC;
spool off
</code>```

The output is missing the hours:

```<code>13-NOV-17,       400
13-NOV-17,       519
13-NOV-17,       126
13-NOV-17,       119
13-NOV-17,       171
13-NOV-17,       183
</code>```

If I run the same script using SQL Developer, I get:

```<code>11/12/2017 17:00:00        396
11/12/2017 16:00:00        402
11/12/2017 15:00:00        459
11/12/2017 14:00:00        462
</code>```

Why the difference? And how can I get the the hours when running using sqlplus?

答:
Adding the following to the top of the script fixed the issue:</p>

```<code> alter session set NLS_DATE_FORMAT = 'mm-dd-yyyy HH24:mi:ss';
</code>```

Body:
I have the following script that I am running using sqlplus

set headsep off
set pagesize 0

spool 'c:\file.csv'
select to_char(trunc(created_date, 'hh')) AS reg_date, count(*)
from ORDERS.PRODUCT WHERE CREATED_DATE > TO_DATE('01/APR/2017','dd/mon/yyyy')
group by trunc(created_date, 'hh') ORDER BY reg_date DESC;
spool off

The output is missing the hours:

13-NOV-17,       400
13-NOV-17,       519
13-NOV-17,       126
13-NOV-17,       119
13-NOV-17,       171
13-NOV-17,       183

If I run the same script using SQL Developer, I get:

11/12/2017 17:00:00        396
11/12/2017 16:00:00        402
11/12/2017 15:00:00        459
11/12/2017 14:00:00        462

Why the difference? And how can I get the the hours when running using sqlplus?

Body:
Adding the following to the top of the script fixed the issue:

 alter session set NLS_DATE_FORMAT = 'mm-dd-yyyy HH24:mi:ss';


问:
Why is accepts_nested_attributes_for not working for me? (rails 3)
I'm using formtastic and haml on a Rails 3 application. I'm trying to make a nested form for surveys and questions, but it's just not working for me. I've watched the railscast and on it and everything, but I can't seem to make it work for my application. So right now, I have the following:

models

```<code>class Survey < ActiveRecord::Base
  attr_accessible :intro, :name, :pubdate, :enddate, :pubid

  belongs_to :user
  has_many :questions, :dependent => :destroy, :autosave => true

  accepts_nested_attributes_for :questions, :allow_destroy => true
end

class Question < ActiveRecord::Base

  belongs_to :survey
  has_many :answers, :dependent => :destroy

  attr_accessible :q_text, :order, :q_type

end
</code>```

relevant controller method

```<code>def update
  @survey = Survey.find(params[:id])
  @user = current_user
  if check_auth_and_redirect @user, @survey
    if @survey.update_attributes(params[:survey])
      flash[:success] = "Survey Updated"
      redirect_to edit_survey_path(@survey)
    else
      @title = "Editing Survey #{@survey.id}"
      render 'edit'
    end
  end
end
</code>```

views

```<code>= semantic_form_for @survey do |f|
  = render "shared/survey_inputs", :object => f
  = f.inputs :for => :questions, :name => "Survey Questions" do |fq|
    %hr
    = fq.input :q_text, :label => "Question text"
    = fq.input :q_type,
               :label => "Question type",
               :as => :select,
               :collection => %w(text scale radio select)
    = fq.input :order, :label => "Question order"
</code>```

The form renders correctly, but when I change a question and click save, the records doesn't reflect my changes. I do have debug(params) turned on, and here is what it comes back as:

```<code>--- !map:ActiveSupport::HashWithIndifferentAccess
      utf8: "\xE2\x9C\x93"
      _method: put
      authenticity_token: CJCc9LvdoPjxwGJkhUnZjR0Z/c5Wt5VBT3bBr/wB4+A=
      survey: !map:ActiveSupport::HashWithIndifferentAccess
        name: This is my survey
        intro: I've got a lovely bunch of coconuts. There they are all standing in a row.
        pubid: smargdab
        pubdate(1i): ""
        pubdate(2i): ""
        pubdate(3i): ""
        enddate(1i): ""
        enddate(2i): ""
        enddate(3i): ""
        questions_attributes: !map:ActiveSupport::HashWithIndifferentAccess
          "0": !map:ActiveSupport::HashWithIndifferentAccess
            q_text: one one one one one one one one one one one
            q_type: text
            order: "3"
            id: "1"
          "1": !map:ActiveSupport::HashWithIndifferentAccess
            q_text: 2 2 2 2 2 2 2 2 2 2
            q_type: text
            order: "1"
            id: "2"
          "2": !map:ActiveSupport::HashWithIndifferentAccess
            q_text: 3 3 3 3 3 3 3 3 3 3
            q_type: text
            order: "2"
            id: "3"
      commit: Update Survey
      action: update
      controller: surveys
      id: "2"
</code>```

What am I doing wrong here? I don't want to have to write these attribute changers manually!

答:
I am looking at some old code of mine that uses accepts_nested_attributes_for and I think what you need to do is change

```<code>attr_accessible :intro, :name, :pubdate, :enddate, :pubid
</code>```

to

```<code>attr_accessible :intro, :name, :pubdate, :enddate, :pubid, :questions_attributes
</code>```

Body:
I'm using formtastic and haml on a Rails 3 application. I'm trying to make a nested form for surveys and questions, but it's just not working for me. I've watched the railscast and on it and everything, but I can't seem to make it work for my application. So right now, I have the following:

models

class Survey < ActiveRecord::Base
  attr_accessible :intro, :name, :pubdate, :enddate, :pubid

  belongs_to :user
  has_many :questions, :dependent => :destroy, :autosave => true

  accepts_nested_attributes_for :questions, :allow_destroy => true
end

class Question < ActiveRecord::Base

  belongs_to :survey
  has_many :answers, :dependent => :destroy

  attr_accessible :q_text, :order, :q_type

end

relevant controller method

def update
  @survey = Survey.find(params[:id])
  @user = current_user
  if check_auth_and_redirect @user, @survey
    if @survey.update_attributes(params[:survey])
      flash[:success] = "Survey Updated"
      redirect_to edit_survey_path(@survey)
    else
      @title = "Editing Survey #{@survey.id}"
      render 'edit'
    end
  end
end

views

= semantic_form_for @survey do |f|
  = render "shared/survey_inputs", :object => f
  = f.inputs :for => :questions, :name => "Survey Questions" do |fq|
    %hr
    = fq.input :q_text, :label => "Question text"
    = fq.input :q_type,
               :label => "Question type",
               :as => :select,
               :collection => %w(text scale radio select)
    = fq.input :order, :label => "Question order"

The form renders correctly, but when I change a question and click save, the records doesn't reflect my changes. I do have debug(params) turned on, and here is what it comes back as:

--- !map:ActiveSupport::HashWithIndifferentAccess
      utf8: "\xE2\x9C\x93"
      _method: put
      authenticity_token: CJCc9LvdoPjxwGJkhUnZjR0Z/c5Wt5VBT3bBr/wB4+A=
      survey: !map:ActiveSupport::HashWithIndifferentAccess
        name: This is my survey
        intro: I've got a lovely bunch of coconuts. There they are all standing in a row.
        pubid: smargdab
        pubdate(1i): ""
        pubdate(2i): ""
        pubdate(3i): ""
        enddate(1i): ""
        enddate(2i): ""
        enddate(3i): ""
        questions_attributes: !map:ActiveSupport::HashWithIndifferentAccess
          "0": !map:ActiveSupport::HashWithIndifferentAccess
            q_text: one one one one one one one one one one one
            q_type: text
            order: "3"
            id: "1"
          "1": !map:ActiveSupport::HashWithIndifferentAccess
            q_text: 2 2 2 2 2 2 2 2 2 2
            q_type: text
            order: "1"
            id: "2"
          "2": !map:ActiveSupport::HashWithIndifferentAccess
            q_text: 3 3 3 3 3 3 3 3 3 3
            q_type: text
            order: "2"
            id: "3"
      commit: Update Survey
      action: update
      controller: surveys
      id: "2"

What am I doing wrong here? I don't want to have to write these attribute changers manually!

Body:
I am looking at some old code of mine that uses accepts_nested_attributes_for and I think what you need to do is change

attr_accessible :intro, :name, :pubdate, :enddate, :pubid

to

attr_accessible :intro, :name, :pubdate, :enddate, :pubid, :questions_attributes


问:
SSIS with C# try to get row count for each file
iam doing the SSIS pakage and i did most the work via C# but what im trying to add is the record count for each output text file. what ever i try never works, i get an error or i get the count of the first out put file on all files. need help please. Thanks
this is my script</p>

```<code>                    // Write the Header Row to File
                    int ColumnCount = d_table.Columns.Count;

                    //  Dts.Events.FireInformation(0, "DataTable Rows", RecordsInserted.ToString(), "", 0, ref fireAgain);

                 //

                    // Write All Rows to the File
                    foreach (DataRow dr in d_table.Rows)
                    {
                        for (int ir = 0; ir < ColumnCount; ir++)
                        {
                            if (!Convert.IsDBNull(dr[ir]))
                            {
                                sw.Write(dr[ir].ToString());
                            }
                            if (ir < ColumnCount - 1)
                            {
                                sw.Write(FileDelimiter);
                            }
                          //  RecordsInserted = dt.Rows.Count;
                          //  Dts.Events.FireInformation(0, "DataTable Rows", RecordsInserted.ToString(), "", 0, ref fireAgain);

                        }

                        sw.Write(sw.NewLine);

                    }
                     /////////////////////
                    sw.Write(",Insurance," + rctn);
                    sw.Write(sw.NewLine);
                   // sw.Write("Row count: " + RowCount.ToString());
              this is some of what i tried but nothing works for me

                    //       sw.Write("Row count: " + RowCount.ToString());

                    sw.Close();
                }

            }

        }
</code>```

答:
Your code example looks incomplete, but I noticed there is no declaration of RowCount anywhere. Is it something like this you need:

```<code>sw.Write("Row count: " + d_table.Rows.Count.ToString());
</code>```

Body:
iam doing the SSIS pakage and i did most the work via C# but what im trying to add is the record count for each output text file. what ever i try never works, i get an error or i get the count of the first out put file on all files. need help please. Thanks
this is my script

                    // Write the Header Row to File
                    int ColumnCount = d_table.Columns.Count;

                    //  Dts.Events.FireInformation(0, "DataTable Rows", RecordsInserted.ToString(), "", 0, ref fireAgain);

                 //

                    // Write All Rows to the File
                    foreach (DataRow dr in d_table.Rows)
                    {
                        for (int ir = 0; ir < ColumnCount; ir++)
                        {
                            if (!Convert.IsDBNull(dr[ir]))
                            {
                                sw.Write(dr[ir].ToString());
                            }
                            if (ir < ColumnCount - 1)
                            {
                                sw.Write(FileDelimiter);
                            }
                          //  RecordsInserted = dt.Rows.Count;
                          //  Dts.Events.FireInformation(0, "DataTable Rows", RecordsInserted.ToString(), "", 0, ref fireAgain);

                        }

                        sw.Write(sw.NewLine);

                    }
                     /////////////////////
                    sw.Write(",Insurance," + rctn);
                    sw.Write(sw.NewLine);
                   // sw.Write("Row count: " + RowCount.ToString());
              this is some of what i tried but nothing works for me

                    //       sw.Write("Row count: " + RowCount.ToString());

                    sw.Close();
                }

            }

        }

Body:
Your code example looks incomplete, but I noticed there is no declaration of RowCount anywhere. Is it something like this you need:

sw.Write("Row count: " + d_table.Rows.Count.ToString());


答:
There is no easy way to convert a string to a variable name, but depending what you are trying to do you could get rid of the object1 variables completely via:

```<code>// Personally I'd use a simple for loop instead of this
foreach (var number in Enumerable.Range(1, 10))
{
    Objects.Add(new GameObject("Example Data"));
}
</code>```

Edit: Using a range of 1..10 is going to confuse you somewhere down the road. In C# everything is 0 based. Just suck it up and don't try to pretend it isn't...

Title: How to use an index on a variable

Body:
There is no easy way to convert a string to a variable name, but depending what you are trying to do you could get rid of the object1 variables completely via:

// Personally I'd use a simple for loop instead of this
foreach (var number in Enumerable.Range(1, 10))
{
    Objects.Add(new GameObject("Example Data"));
}

Edit: Using a range of 1..10 is going to confuse you somewhere down the road. In C# everything is 0 based. Just suck it up and don't try to pretend it isn't...


问:
Which is a better js coding practice?
I need to send api calls to get data from multiple sources.The data that I get are in different format (arrays, objects,nested arrays). One thing I feel good about is to have an function that extract the parts I need from for me.

Now I wonder if I should have this extraction function or simply just extract the data I need when I use it.(Simply put : which one is a better practice?)

I personally prefer the latter one because I will not need to go back and forth to make sure which part of data I need to extract.
Eg.

Inline extraction

```<code>const  data = get("example.com").data[0].Users;
</code>```

Use function to extract data

```<code>const data = getData("example.com";

const getData = async(url)=>{
   const rawData= await get(url);
   switch(url){
    case EXAMPLE_URL:
      return rawData.data[0].Users;
    case OTHER_EXAMPLE_URL:
      return rawData.data;
    case  OTHER_URL:
     return rawData.data[0].Enum;

}
}
</code>```

答:
I'd split that into multiple functions. Imo, the caller should not need to know what url to pass to get some distinct value.

And you don't know whether you'll end up with fetching two different values from the same url.

```<code>//maybe using a simple utility
const getUrlPath = (url, ...path) => {
  let fetchPath = path.reduceRight((next, key) => obj => next(obj[key]), identity);
  return () => get(url).then(fetchPath);
}
const identity = v => v;

//and then creating the different functions to get the different values
const getExample = getUrlPath(EXAMPLE_URL, "data", 0, "Users");
const getOther = getUrlPath(OTHER_EXAMPLE_URL, "data");
...
</code>```

Title: Which is a better js coding practice?

Body:
I need to send api calls to get data from multiple sources.The data that I get are in different format (arrays, objects,nested arrays). One thing I feel good about is to have an function that extract the parts I need from for me.

Now I wonder if I should have this extraction function or simply just extract the data I need when I use it.(Simply put : which one is a better practice?)

I personally prefer the latter one because I will not need to go back and forth to make sure which part of data I need to extract.
Eg.

Inline extraction

const  data = get("example.com").data[0].Users;

Use function to extract data

const data = getData("example.com";

const getData = async(url)=>{
   const rawData= await get(url);
   switch(url){
    case EXAMPLE_URL:
      return rawData.data[0].Users;
    case OTHER_EXAMPLE_URL:
      return rawData.data;
    case  OTHER_URL:
     return rawData.data[0].Enum;

}
}

Body:
I'd split that into multiple functions. Imo, the caller should not need to know what url to pass to get some distinct value.

And you don't know whether you'll end up with fetching two different values from the same url.

//maybe using a simple utility
const getUrlPath = (url, ...path) => {
  let fetchPath = path.reduceRight((next, key) => obj => next(obj[key]), identity);
  return () => get(url).then(fetchPath);
}
const identity = v => v;

//and then creating the different functions to get the different values
const getExample = getUrlPath(EXAMPLE_URL, "data", 0, "Users");
const getOther = getUrlPath(OTHER_EXAMPLE_URL, "data");
...


问:
Wait for response from api using http.post in Angular 4
So I am trying to create packages in rapid succession with a for loop. I try to do this with a for loop and a api call, this api call makes the package. My loop has to wait for the return of each call but it doesn't.

I also dont like to change my backend.service to a Promise instead of a Observable. Is it possible to do this with a Observable?

component.ts

```<code>for (let i = 0; i < this.dataArray.length; i++) {
  this.backend.createPackage(this.package, this.hasPackagePhoto, this.wantsPackageLabel).subscribe(data => {
    let d = data as any;
    this.backend.packageTrackTrace = d.package.tracktrace;
    this.backend.awsLink = d.label;
  }, error => {
    this.backend.showMessage(false, 'Foutcode 2a: Het toevoegen van een pakket is niet gelukt.');
    console.log(error);
    this.errorMsg = "Verkeerde postcode!";
  }
  );
}
</code>```

backend.service.ts

```<code>createPackage(p: Package, photo: Boolean, label: Boolean): Observable<Response> {
    const h = new Headers({ 'Content-Type': 'application/json', 'x-access-token': this.auth.getToken() });
    const options = new RequestOptions({ headers: h });

    const pt: any = {
        type: p.type,
        sender: p.sender,
        recipient: p.recipient,
        weight: p.weight,
        value: p.value,
        photo: photo,
        label: label,
        instructions: p.instructions
    };
    if (p.owner != null) {
        pt.owner = p.owner;
    }
    if (p.size != null) {
        pt.size = p.size;
    }

    return this.http.post(`${this.config.apiBase}/packages`, pt, options)
        .map((res:Response) => {
            this.newPackageCallbacks.forEach(cb => {
                cb();
            });
            return this.parseJSON(res);
        })
        .catch(this.handleError);
}
</code>```

答:
I'd create a recursive function for it:

```<code>createPackages(count: number, i = 0) {
  if (i >= count) return;
  this.backend.createPackage(this.package, this.hasPackagePhoto, this.wantsPackageLabel).subscribe(data => {
    let d = data as any;
    this.backend.packageTrackTrace = d.package.tracktrace;
    this.backend.awsLink = d.label;
    this.createPackages(count, ++i);
  }, error => {
    this.backend.showMessage(false, 'Foutcode 2a: Het toevoegen van een pakket is niet gelukt.');
    console.log(error);
    this.errorMsg = "Verkeerde postcode!";
  });
}
</code>```

and invoke: this.createPackages(this.dataArray.length);

Body:
So I am trying to create packages in rapid succession with a for loop. I try to do this with a for loop and a api call, this api call makes the package. My loop has to wait for the return of each call but it doesn't.

I also dont like to change my backend.service to a Promise instead of a Observable. Is it possible to do this with a Observable?

component.ts

for (let i = 0; i < this.dataArray.length; i++) {
  this.backend.createPackage(this.package, this.hasPackagePhoto, this.wantsPackageLabel).subscribe(data => {
    let d = data as any;
    this.backend.packageTrackTrace = d.package.tracktrace;
    this.backend.awsLink = d.label;
  }, error => {
    this.backend.showMessage(false, 'Foutcode 2a: Het toevoegen van een pakket is niet gelukt.');
    console.log(error);
    this.errorMsg = "Verkeerde postcode!";
  }
  );
}

backend.service.ts

createPackage(p: Package, photo: Boolean, label: Boolean): Observable<Response> {
    const h = new Headers({ 'Content-Type': 'application/json', 'x-access-token': this.auth.getToken() });
    const options = new RequestOptions({ headers: h });

    const pt: any = {
        type: p.type,
        sender: p.sender,
        recipient: p.recipient,
        weight: p.weight,
        value: p.value,
        photo: photo,
        label: label,
        instructions: p.instructions
    };
    if (p.owner != null) {
        pt.owner = p.owner;
    }
    if (p.size != null) {
        pt.size = p.size;
    }

    return this.http.post(`${this.config.apiBase}/packages`, pt, options)
        .map((res:Response) => {
            this.newPackageCallbacks.forEach(cb => {
                cb();
            });
            return this.parseJSON(res);
        })
        .catch(this.handleError);
}

Body:
I'd create a recursive function for it:

createPackages(count: number, i = 0) {
  if (i >= count) return;
  this.backend.createPackage(this.package, this.hasPackagePhoto, this.wantsPackageLabel).subscribe(data => {
    let d = data as any;
    this.backend.packageTrackTrace = d.package.tracktrace;
    this.backend.awsLink = d.label;
    this.createPackages(count, ++i);
  }, error => {
    this.backend.showMessage(false, 'Foutcode 2a: Het toevoegen van een pakket is niet gelukt.');
    console.log(error);
    this.errorMsg = "Verkeerde postcode!";
  });
}

and invoke: this.createPackages(this.dataArray.length);


问:
Manually resending an AWS EC2 spot instance request after its termination, with data persistance
In Amazon Web Services \ EC2, I have a spot instance request that was run and manually terminated (by me). Now, I would like to run the same instance again - without needing to go through the process of creating a new instance (I mean, the process where I choose the AMI, the instant type, configurations, security group, etc.). When using non-stop instances, this is easy, as I can manually terminate or start the instance as many time as I want (and my saved data is persisted between terminations). But with the spot instance, I don't see how this can be done, since after it was terminated, the spot requests page in the EC2 management console shows that the request is closed and I don't see how to resend the same request again.

I know that I can choose a spot request to be persistent, but I understand that this would automatically resend the request when it is terminated, whereas I would want to continue to have manual control over when the request is sent.

To summarize, I'd want to be able to have the following workflow:

Create a spot instance request.

Run the spot instance (when the spot price is smaller than my bidding price).

Have some data saved in the instance.

Terminate the instance (either manually or due to the bid price threshold).

Manually, at my chosen time, resend a request to run the same instance, such that when it is opened, I can still see the data from before.

Return to 2.

How can this be done?

答: The short answer is that you cannot relaunch a spot instance once it is terminated. Terminated means that the instance, data, etc. is destroyed. Your description describes On-Demand instances (except for the price).</p>


问:
Nginx site for PHP-FPM status page returns "File not found"
In /etc/php/7.1/fpm/pool.d/www.conf I have set pm.status_path = /status. And in Nginx I have the following site configuration /etc/nginx/sites-enabled/datadog

```<code>server {
  listen 80;
  server_name localhost;

    location ~ ^/(status|ping)$ {
        access_log off;
        allow 127.0.0.1;
        deny all;
        include fastcgi_params;

        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_pass unix:/run/php/php7.1-fpm.sock;
    }
}
</code>```

I have tested that the status page is correctly setup using

```<code>SCRIPT_NAME=/status \
SCRIPT_FILENAME=/status \
REQUEST_METHOD=GET \
cgi-fcgi -bind -connect /run/php/php7.1-fpm.sock
</code>```

Which returns

```<code>Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, max-age=0
Content-type: text/plain;charset=UTF-8

pool:                 www
process manager:      dynamic
start time:           13/Nov/2017:22:05:44 +0000
start since:          5030
accepted conn:        1789
listen queue:         0
max listen queue:     0
listen queue len:     0
idle processes:       2
active processes:     1
total processes:      3
max active processes: 4
max children reached: 0
slow requests:        0
</code>```

However, if I try to access the Nginx site using curl http://localhost/status I get the following error.

```<code>2017/11/13 23:32:57 [error] 885#885: *35 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /status HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.1-fpm.sock:", host: "localhost"
</code>```

答: You are referencing $document_root but there is no root directive in your server block

Body:
In /etc/php/7.1/fpm/pool.d/www.conf I have set pm.status_path = /status. And in Nginx I have the following site configuration /etc/nginx/sites-enabled/datadog

server {
  listen 80;
  server_name localhost;

    location ~ ^/(status|ping)$ {
        access_log off;
        allow 127.0.0.1;
        deny all;
        include fastcgi_params;

        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        fastcgi_pass unix:/run/php/php7.1-fpm.sock;
    }
}

I have tested that the status page is correctly setup using

SCRIPT_NAME=/status \
SCRIPT_FILENAME=/status \
REQUEST_METHOD=GET \
cgi-fcgi -bind -connect /run/php/php7.1-fpm.sock

Which returns

Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, max-age=0
Content-type: text/plain;charset=UTF-8

pool:                 www
process manager:      dynamic
start time:           13/Nov/2017:22:05:44 +0000
start since:          5030
accepted conn:        1789
listen queue:         0
max listen queue:     0
listen queue len:     0
idle processes:       2
active processes:     1
total processes:      3
max active processes: 4
max children reached: 0
slow requests:        0

However, if I try to access the Nginx site using curl http://localhost/status I get the following error.

2017/11/13 23:32:57 [error] 885#885: *35 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET /status HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.1-fpm.sock:", host: "localhost"


问:
I am trying to move the first two letters of the string to the end if it starts with two consonants. It just returns Not a number, or NaN
Here is my javascript code:

```<code>function lattify(id) {
  var inputTextStr = document.getElementById(id).value;
  var lattiStr = "";
  for (var i = 0; i < inputTextStr.length; i++) {
    console.log(inputTextStr[i]);
    var inputText = inputTextStr[i];
    if (inputTextStr[i + 1] !== "a" || "e" || "i" || "o" || "u") {
      lattiStr = inputTextStr.substr(2) +
        inputTextStr.substr(0, inputTextStr.length);
    }

  }
  console.log(lattiStr);
}
</code>```

Here is my html code:

```<code><form>
  <input type="text" id="latin">
  <button type="button" onclick="lattify('latin'.toString())">Submit</button>
</form>
</code>```

What this program is supposed to do is take the text input from the form into the function 'lattify'. That part works. The part that does not work is the part where the first two letters are added to the end if they are both of them are consonants.

答:
To me this seems like a good place for a regular expression rather than looping. For example this becomes much simpler with:

function lattify(inputTextStr) {
  if (inputTextStr.match(/^[^aeiou]{2}/i)) {
    inputTextStr = inputTextStr.substring(2) + inputTextStr.substring(0, 2)
  }
  return inputTextStr
}

console.log(lattify("MMstring"))
console.log(lattify("MeMstring"))
console.log(lattify("eestring"))
console.log(lattify("eMstring"))```

This is case insensitive, too.

It's also worth noting that the logic of testing for vowels, doesn't guarantee the string starts with consonants. Think about the behavior you want if the string starts with a number or punctuation.

Body:
Here is my javascript code:

function lattify(id) {
  var inputTextStr = document.getElementById(id).value;
  var lattiStr = "";
  for (var i = 0; i < inputTextStr.length; i++) {
    console.log(inputTextStr[i]);
    var inputText = inputTextStr[i];
    if (inputTextStr[i + 1] !== "a" || "e" || "i" || "o" || "u") {
      lattiStr = inputTextStr.substr(2) +
        inputTextStr.substr(0, inputTextStr.length);
    }

  }
  console.log(lattiStr);
}

Here is my html code:

<form>
  <input type="text" id="latin">
  <button type="button" onclick="lattify('latin'.toString())">Submit</button>
</form>

What this program is supposed to do is take the text input from the form into the function 'lattify'. That part works. The part that does not work is the part where the first two letters are added to the end if they are both of them are consonants.

Body:
To me this seems like a good place for a regular expression rather than looping. For example this becomes much simpler with:

function lattify(inputTextStr) {
  if (inputTextStr.match(/^[^aeiou]{2}/i)) {
    inputTextStr = inputTextStr.substring(2) + inputTextStr.substring(0, 2)
  }
  return inputTextStr
}

console.log(lattify("MMstring"))
console.log(lattify("MeMstring"))
console.log(lattify("eestring"))
console.log(lattify("eMstring"))

This is case insensitive, too.

It's also worth noting that the logic of testing for vowels, doesn't guarantee the string starts with consonants. Think about the behavior you want if the string starts with a number or punctuation.


问:
HTMLAgilityPack stripping out html
I'm sure this question has asked before and i've looked before I cant find the answer, or maybe I am just doing something wrong.

```<code>HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(indivdualfix[0]);
                HtmlWeb hwObject = new HtmlWeb();
                HtmlAgilityPack.HtmlDocument htmldocObject = hwObject.Load(indivdualfix[0]);
                HtmlNode body = htmldocObject.DocumentNode.SelectSingleNode("//body");
                body.Attributes.Remove("style");
                foreach (var a in body.Attributes.ToArray())
                    a.Remove();
                string bodywork = body.InnerHtml.ToString();
</code>```

The string body still returns all the html coding.  I might be missing something really small here.  What needs to be doen to remove all the html coding basically.

答: Use body.InnerText not body.InnerHtml

Title: HTMLAgilityPack stripping out html

Body:
I'm sure this question has asked before and i've looked before I cant find the answer, or maybe I am just doing something wrong.

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(indivdualfix[0]);
                HtmlWeb hwObject = new HtmlWeb();
                HtmlAgilityPack.HtmlDocument htmldocObject = hwObject.Load(indivdualfix[0]);
                HtmlNode body = htmldocObject.DocumentNode.SelectSingleNode("//body");
                body.Attributes.Remove("style");
                foreach (var a in body.Attributes.ToArray())
                    a.Remove();
                string bodywork = body.InnerHtml.ToString();

The string body still returns all the html coding.  I might be missing something really small here.  What needs to be doen to remove all the html coding basically.

Body: Use body.InnerText not body.InnerHtml


问:
How to find index of clickable element on delegation?
How can I find index of clickable element? I would need to get the index of li when its button was clicked, so I can delete it from array.

```<code>    var template = document.querySelector('#template');
    this.element.addEventListener('click', function(e) {
        if(e.target && e.target.nodeName == 'BUTTON' && e.target.className == 'remove') {
            //var index = ??
            //this.deleteTask(index);
        }
    }.bind(this));

    <script id="template" type="x-tmpl-mustache">
        <ul>
            {{ #tasks }}
                <li>{{ . }} - <button class="remove">X</button></li>
            {{ /tasks }}
        </ul>
    </script>
</code>```

答:
If you use @index, you can attach it to the button itself with a data attribute, and then use that:

```<code>var template = document.querySelector('#template');
this.element.addEventListener('click', function(e) {
    if(e.target && e.target.nodeName == 'BUTTON' && e.target.className == 'remove') {
        var index = e.target.dataset.index;
        // or possibly e.target.getAttribute('data-index');
        this.deleteTask(parseInt(index, 10));
    }
}.bind(this));

<script id="template" type="x-tmpl-mustache">
    <ul>
        {{ #tasks }}
            <li>{{ . }} - <button class="remove" data-index="{{ @index }}">X</button></li>
        {{ /tasks }}
    </ul>
</script>
</code>```

Body:
How can I find index of clickable element? I would need to get the index of li when its button was clicked, so I can delete it from array.

    var template = document.querySelector('#template');
    this.element.addEventListener('click', function(e) {
        if(e.target && e.target.nodeName == 'BUTTON' && e.target.className == 'remove') {
            //var index = ??
            //this.deleteTask(index);
        }
    }.bind(this));

Body:
If you use @index, you can attach it to the button itself with a data attribute, and then use that:

var template = document.querySelector('#template');
this.element.addEventListener('click', function(e) {
    if(e.target && e.target.nodeName == 'BUTTON' && e.target.className == 'remove') {
        var index = e.target.dataset.index;
        // or possibly e.target.getAttribute('data-index');
        this.deleteTask(parseInt(index, 10));
    }
}.bind(this));

<script id="template" type="x-tmpl-mustache">
    <ul>
        {{ #tasks }}
            <li>{{ . }} - <button class="remove" data-index="{{ @index }}">X</button></li>
        {{ /tasks }}
    </ul>
</script>


问:
Wrap Eigen's tensor class to create dynamic rank tensors?
Eigen's tensor module supports static rank tensors through the use of template arguments, with something like Eigen::Tensor<typename T,int dims>. I'm only going to be using Eigen::Tensor<double, n>, where n isn't necessarily known at compile time. Is there anyway to make a class like:

```<code>class TensorWrapper{
    Eigen::Tensor<double,??????> t; //not sure what could go here
    TensorWrapper(int dimensions){
        t = Eigen::Tensor<double,dimensions>(); //wouldn't work either way
    }
};
</code>```

I know that Eigen::Tensor<double,2> and Eigen::Tensor<double,3> have absolutely nothing to do with each other because they are templated, and that I can't have template arguments determined at run-time, so the above would fail in every possible way. I also know that tensors in Tensorflow support this, but they don't have tensor contraction in c++ (which is why I need tensors in the first place). Is there any way to do what I wanted to above, even for a limited number of dimensions (I won't need more than 5 or 6)? If not, are there any tensor libraries for c++ that support dynamic rank and tensor contraction?

答:
Hi I wrote this multidimensional tensor library (its not full fledged) it supports basic operations like dotproduct and pointwise elements.

https://github.com/josephjaspers/BlackCat_Tensors

```<code>Tensor<float> tensor3 = {3, 4, 5};   -- generates a 3 dimensional tensor (3 rows, 4 columns, 5 pages)
Tensor<float> tensor5 = {1,2,3,4,5}; -- generate a 5d tensors (1 rows, 2 columns, 3 pages, etc)
tensor3[1] = 3;                      -- returns the second matrix and sets all the values to 3.
tensor3[1][2];                       -- returns the second matrx and then then 3rd column of that matrix
tensor3({1,2,3},{2,2});              -- at index 1,2,3, returns a sub-matrix of dimensions 2x2
</code>```

All of the accessor operators [] (int index) and ({initializer_list index},{initializer_list shape}) return seperate tensors but they all refer to the same internal array. Therefor you can modify the original tensor from these sub_tensors.

All the data is allocated on a single array. If you want to use dotproduct you need to link it to BLAS. Here's the header file, it details most of the methods. https://github.com/josephjaspers/BlackCat_Tensors/blob/master/BC_Headers/Tensor.h

However, it is not particularly fast, personally I use this personal library just for prototyping NeuralNetworks (https://github.com/josephjaspers/BlackCat_NeuralNetworks).

Body:
Eigen's tensor module supports static rank tensors through the use of template arguments, with something like Eigen::Tensor<typename T,int dims>. I'm only going to be using Eigen::Tensor<double, n>, where n isn't necessarily known at compile time. Is there anyway to make a class like:

class TensorWrapper{
    Eigen::Tensor<double,??????> t; //not sure what could go here
    TensorWrapper(int dimensions){
        t = Eigen::Tensor<double,dimensions>(); //wouldn't work either way
    }
};

I know that Eigen::Tensor<double,2> and Eigen::Tensor<double,3> have absolutely nothing to do with each other because they are templated, and that I can't have template arguments determined at run-time, so the above would fail in every possible way. I also know that tensors in Tensorflow support this, but they don't have tensor contraction in c++ (which is why I need tensors in the first place). Is there any way to do what I wanted to above, even for a limited number of dimensions (I won't need more than 5 or 6)? If not, are there any tensor libraries for c++ that support dynamic rank and tensor contraction?

Body:
Hi I wrote this multidimensional tensor library (its not full fledged) it supports basic operations like dotproduct and pointwise elements.

https://github.com/josephjaspers/BlackCat_Tensors

Tensor<float> tensor3 = {3, 4, 5};   -- generates a 3 dimensional tensor (3 rows, 4 columns, 5 pages)
Tensor<float> tensor5 = {1,2,3,4,5}; -- generate a 5d tensors (1 rows, 2 columns, 3 pages, etc)
tensor3[1] = 3;                      -- returns the second matrix and sets all the values to 3.
tensor3[1][2];                       -- returns the second matrx and then then 3rd column of that matrix
tensor3({1,2,3},{2,2});              -- at index 1,2,3, returns a sub-matrix of dimensions 2x2

All of the accessor operators [] (int index) and ({initializer_list index},{initializer_list shape}) return seperate tensors but they all refer to the same internal array. Therefor you can modify the original tensor from these sub_tensors.

All the data is allocated on a single array. If you want to use dotproduct you need to link it to BLAS. Here's the header file, it details most of the methods. https://github.com/josephjaspers/BlackCat_Tensors/blob/master/BC_Headers/Tensor.h

However, it is not particularly fast, personally I use this personal library just for prototyping NeuralNetworks (https://github.com/josephjaspers/BlackCat_NeuralNetworks).


问:
C# - Pass data to JS and wait result to process
Is there anyway to pass something from C# to JS, then do something in JS and give it back to the C# code?

I'm working on MVC and I'm trying to encrypt the password in the view, before sending, so no one can peek. My idea was:

When hitting submit, an AJAX call ask to the server the generation of a new RSA key pair

The server generates the new key pair and sends the public key to the client, waiting for a response

The client recieves the public key, encrypts in the js file the password and sends the encrypted password to the server

The server recieves the data it was waiting for and decrypts the password

I think is the "best" way to do it, but I don't know if it's possible to start a thread with Ajax and then keep it waiting until it recieves a response, or dies after x amount of time. And I think that's the best way because it will generate an unique key pair each time that you need to submit the password and will never be stored, so if someone picks at the request you sent, they'll get an encrypted password that can't be used for nothing.

答:
Your question is malformed. You do not want to server send anything to client, but client sending something to server.
Like your scenario, which seems good:

Client asks Server: Give me Public Key

Server responds: Here's the key and ID you need for me to be able to select private key

Client encrypts, Server doesn't care what is happening here.

Client sends to server: Here's encrypted password and ID you gave me before.

Server looks up its key cache for given key ID

Server decrypts the password using private key retrieved from cache and Client waits for response.

Server responds: Password is OK or Password is wrong OR if couldn't find provided ID should return some timeout or other error.

Of course if you'd like to generate RSA keys on the fly, randomly for every request you'd need to hold somewhere the key to decrypt and some session key (which would Client know too), so you could match them up, but it should work.

Built-in .NET Memory Cache seems perfectly designed for this task. You can put data in the cache, retrieve it, remove it and set up validity time, after which .NET manages itself to remove object from the cache.

Please refer to .NET documentation available: https://msdn.microsoft.com/pl-pl/library/system.runtime.caching.memorycache(v=vs.110).aspx in this matter.

It is possible to create request in Ajax and make it wait for completion or timeout, but you must keep in mind, that server is unable to contact the client, unless client is asking for contact (sending request) or you are using websockets (which, I think, are like cannon to kill a fly, for this task).


问:
How to fill in an incrementing integer in Pandas
Given a pd.DataFrame such as:

```<code>print(pd.DataFrame([['a', 0, 'b'], ['c', 1, 'd'], ['f', 4, 'e']]))
   0  1  2
0  a  0  b
1  c  1  d
2  f  4  e
</code>```

I would like to "fill in" rows by incrementing on the integer column. That is, I would like to obtain:

```<code>     0  1    2
0    a  0    b
1    c  1    d
2  NaN  2  NaN
3  NaN  3  NaN
4    f  4    e
</code>```

As I am will use this within a groupby operation in a large dataset I am looking for the most efficient code to do this.

答:
You could turn your 1 column into an index and reindex using it:

```<code>In [33]: df.set_index(1).reindex(range(df[1].iloc[0], df[1].iloc[-1]+1)).reset_index()
Out[33]:
   1    0    2
0  0    a    b
1  1    c    d
2  2  NaN  NaN
3  3  NaN  NaN
4  4    f    e
</code>```

and then you could reorder the columns if you cared.

Don't know about performance, but frankly custom groupby operations are pretty slow to start with.  If speed is really critical, your best bet is to move this incrementing operation out of the groupby entirely if you can pull it off.

Body:
Given a pd.DataFrame such as:

print(pd.DataFrame([['a', 0, 'b'], ['c', 1, 'd'], ['f', 4, 'e']]))
   0  1  2
0  a  0  b
1  c  1  d
2  f  4  e

I would like to "fill in" rows by incrementing on the integer column. That is, I would like to obtain:

     0  1    2
0    a  0    b
1    c  1    d
2  NaN  2  NaN
3  NaN  3  NaN
4    f  4    e

As I am will use this within a groupby operation in a large dataset I am looking for the most efficient code to do this.

Body:
You could turn your 1 column into an index and reindex using it:

In [33]: df.set_index(1).reindex(range(df[1].iloc[0], df[1].iloc[-1]+1)).reset_index()
Out[33]:
   1    0    2
0  0    a    b
1  1    c    d
2  2  NaN  NaN
3  3  NaN  NaN
4  4    f    e

and then you could reorder the columns if you cared.

Don't know about performance, but frankly custom groupby operations are pretty slow to start with.  If speed is really critical, your best bet is to move this incrementing operation out of the groupby entirely if you can pull it off.


OwnerDisplayName: Alexander

Title: What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Body:
What is the RegEx pattern for DateTime (2008-09-01 12:35:45 ) ?

I get this error:

No ending delimiter '^' found

Using:

preg_match('(?n:^(?=\d)((?<day>31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(?<sep>[/.-])(?<month>0?[1-9]|1[012])\2(?<year>(1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(?<time>((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45');

Gives this error:

Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19

LastEditorDisplayName: Alexander

Body:
regarding to Imran answer from Sep  1th 2008 at 12:33
there is a missing : in the pattern
the correct patterns are

preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', '2008-09-01 12:35:45', $m1);
print_r( $m1 );
preg_match('/\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}:\d{2}/', '2008-09-01 12:35:45', $m2);
print_r( $m2 );
preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', '2008-09-01 12:35:45', $m3);
print_r( $m3 );

this returns

Array ( [0] => 2008-09-01 12:35:45 )
Array ( [0] => 2008-09-01 12:35:45 )
Array ( [0] => 2008-09-01 12:35:45 )


问:
Unit testing only controller file instead of express framework
I am trying to unit test my controller file that handles a particular request. I do not want to test express as we have another mechanism for testing our Apis. I am stubbing the data using sinon. But the response is not what I am expecting.. I am always getting back a 200 status instead of the 201 that I am supposed to receive. Am I missing out on any specific part? I am using Typescript and mocha

my spec.ts file is

```<code>import {expect} from 'chai';
import {HiringCompanyJobHandler} from
"../../source/Handlers/HiringCompanyJobHandler";
import * as httpMocks from 'node-mocks-http';
import * as sinon from 'sinon';
import Jobs from "../../source/DAL/model/job";
import * as mongoose from 'mongoose';
import {Response, Request, Express} from 'express';

describe("Hiring Company Job Handler Unit Test Cases", () => {
let request = null;
let response = null;

beforeEach(function () {
    response = httpMocks.createResponse();
});

it("Should return the job details that belong to a particular company", (done) => {
    request = {
        query: {
            UserName: 'HiringCompany',
            CompanyID: '1'
        }
    };

    let expectedJobs = [
        {
            'hiringCompanyId': '1',
            'companyJobId': 'T1',
            'jobName': 'Plumber',
            'jobType': 'Permanent'
        }, {
            'hiringCompanyId': '1',
            'companyJobId': 'T2',
            'jobName': 'Electrician',
            'jobType': 'Temporary'
        }
    ];

    sinon.mock(Jobs)
        .expects('find')
        .resolves(expectedJobs);

    let hiringCompanyJobHandler = new HiringCompanyJobHandler();
    hiringCompanyJobHandler.GetBasicJobInformationForHiringCompany(request, response);

    expect(response.statusCode).to.equal(201);
    done();

})
});
</code>```

My controller code is as follows

```<code>import { NextFunction, Request, Response } from "express";
import { isNullOrUndefined } from "util";
import JobDal from "../DAL/jobdal";

export class HiringCompanyJobHandler {
constructor() {

}

public GetBasicJobInformationForHiringCompany(req: Request, res: Response) {
    let userName = req.query.UserName;
    let companyID = req.query.CompanyID;
    let status = req.query.status;
    let jobDal = new JobDal();
    jobDal.GetHiringCompanyJobDetails(companyID,status).then((details) => {
        if (details.length > 0) {
            res.status(201).send({ details });
        }else {
            res.status(200).send({ status: "No jobs found!" });
        }
    }).catch((error: any) => {
        console.log(error);
        res.status(500).send(error);
    });
}
</code>```

}

```<code>export default new HiringCompanyJobHandler();
</code>```

答:
resolves does not appear to be available for mocks (check the api here).
I guess that you want to modify the behavior of the method find in Job, and that this method is called inside GetHiringCompanyJobDetails. Is that correct?

I think though that you should stub the method GetHiringCompanyJobDetails instead, so your test is pure unit test, since in here you are unit testing the method GetBasicJobInformationForHiringCompany. But this would be part of a different discussion.

In any case, you should use a stub if you want to modify the behavior of a method to meet the requirements of the path you want to test.
Check the sinon API for stubs here. I hope this solves your issue. :)

Body:
I am trying to unit test my controller file that handles a particular request. I do not want to test express as we have another mechanism for testing our Apis. I am stubbing the data using sinon. But the response is not what I am expecting.. I am always getting back a 200 status instead of the 201 that I am supposed to receive. Am I missing out on any specific part? I am using Typescript and mocha

my spec.ts file is

import {expect} from 'chai';
import {HiringCompanyJobHandler} from
"../../source/Handlers/HiringCompanyJobHandler";
import * as httpMocks from 'node-mocks-http';
import * as sinon from 'sinon';
import Jobs from "../../source/DAL/model/job";
import * as mongoose from 'mongoose';
import {Response, Request, Express} from 'express';

describe("Hiring Company Job Handler Unit Test Cases", () => {
let request = null;
let response = null;

beforeEach(function () {
    response = httpMocks.createResponse();
});

it("Should return the job details that belong to a particular company", (done) => {
    request = {
        query: {
            UserName: 'HiringCompany',
            CompanyID: '1'
        }
    };

    let expectedJobs = [
        {
            'hiringCompanyId': '1',
            'companyJobId': 'T1',
            'jobName': 'Plumber',
            'jobType': 'Permanent'
        }, {
            'hiringCompanyId': '1',
            'companyJobId': 'T2',
            'jobName': 'Electrician',
            'jobType': 'Temporary'
        }
    ];

    sinon.mock(Jobs)
        .expects('find')
        .resolves(expectedJobs);

    let hiringCompanyJobHandler = new HiringCompanyJobHandler();
    hiringCompanyJobHandler.GetBasicJobInformationForHiringCompany(request, response);

    expect(response.statusCode).to.equal(201);
    done();

})
});

My controller code is as follows

import { NextFunction, Request, Response } from "express";
import { isNullOrUndefined } from "util";
import JobDal from "../DAL/jobdal";

export class HiringCompanyJobHandler {
constructor() {

}

public GetBasicJobInformationForHiringCompany(req: Request, res: Response) {
    let userName = req.query.UserName;
    let companyID = req.query.CompanyID;
    let status = req.query.status;
    let jobDal = new JobDal();
    jobDal.GetHiringCompanyJobDetails(companyID,status).then((details) => {
        if (details.length > 0) {
            res.status(201).send({ details });
        }else {
            res.status(200).send({ status: "No jobs found!" });
        }
    }).catch((error: any) => {
        console.log(error);
        res.status(500).send(error);
    });
}

}

export default new HiringCompanyJobHandler();


问:
Android - Close first activity
I have created an android application which has two activities, one of them is MainActivity and the other one is Article activity

In this application  you can open unlimited number of activities. So it's like an article app, inside an article there are also other articles so you can follow unlimited number of articles. Every article opens a new Article activity.

Now what I want to do is this: When the 10th Article is opened I want to close the first Article activity (not MainActivity).

I have also read this question, but it works only if you have different activities (i.e. ActivityA, ActivityB, ActivityC...).

Is there any way I can do this?

答:
this is a hack only to get it working but you may want to try fragment from your description;

Create a new class called ActivityHandler.java

```<code>public class ActivityHandler {
private static ActivityHandler uniqueInstance;
private static List<Activity> mListActivity;
private static int SIZE_LIMIT = 10;

public static ActivityHandler getInstance() {
    if (uniqueInstance == null) {
        synchronized (ActivityHandler.class) {
            if (uniqueInstance == null) {
                uniqueInstance = new ActivityHandler();
            }
        }
    }
    return uniqueInstance;
}

private Activityhandler() {
    if (mListActivity == null ) {
        mListActivity = new ArrayList();
    }
}

public static void add (Activity activity){
    mListActivity.add(activity);
    if (mListActivity.size() > 10){
        Activity firstActivity = mListActivity.remove(0);
        firstActivity.finish();
    }
}
}
</code>```

In your ArticleActivity's OnCreateMethod:

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.article_activity);
    ActivityHandler.getInstance().add(this);

}
</code>```

Title: Android - Close first activity

Body:
this is a hack only to get it working but you may want to try fragment from your description;

Create a new class called ActivityHandler.java

public class ActivityHandler {
private static ActivityHandler uniqueInstance;
private static List<Activity> mListActivity;
private static int SIZE_LIMIT = 10;

public static ActivityHandler getInstance() {
    if (uniqueInstance == null) {
        synchronized (ActivityHandler.class) {
            if (uniqueInstance == null) {
                uniqueInstance = new ActivityHandler();
            }
        }
    }
    return uniqueInstance;
}

private Activityhandler() {
    if (mListActivity == null ) {
        mListActivity = new ArrayList();
    }
}

public static void add (Activity activity){
    mListActivity.add(activity);
    if (mListActivity.size() > 10){
        Activity firstActivity = mListActivity.remove(0);
        firstActivity.finish();
    }
}
}

In your ArticleActivity's OnCreateMethod:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.article_activity);
    ActivityHandler.getInstance().add(this);

}


问:
Batch Copy and Add to sub folder
hope you can help me with this, i can't make it work what i need

I need to copy all the .pdf files from a source folder, create a folder with part of the name "T-123456" and add the respective PDF files found in the correct folder in the destination folder, but sometimes the name it varies or the reference change "SM17-123".

Example of files

HC002T-1234562436787004332

MV002T-1234562436787004332

PP _002_T-123456_24_3678_7004332

Types of direfents files

HC123CLG-32-172436787004259

HC123SM17-1802436787004044

i have this code created but it makes part of the job because the name varies and create folders incorrect for that files, sometimes the files have more digits in the beggining example 001 or 0001, so i dont know how to omit the other references files and only work whith files "T-123456" also i need the batch continuously working for new files created in the source folder and if i have another routhe where i have other types of file and copy to the correct reference it would be great.

```<code>@echo off
title Electronic File

:loop
cls
timeout -t 1 >nul
color b
for %%A in (*.pdf) do (
   echo File Found %%A
   for /f "delims=" %%B in ("%%A") do set fname=%%~nB
   for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
   for /f "tokens=1* delims=" %%D in ("!fname:~5,8!") do set folname=%%D
   echo Name folder !folname!
   if not exist "!folname!" (
      echo Folder !folname! dont exist, creating
      md "!folname!" 2>nul
   ) else (
      echo Folder !folname! exists
   )
   echo Copying file %%A to folder !folname!
   xcopy "%%A" "!folname!"
   )

echo on

md "C:\test %All%"

xcopy /s /y "X:\test\pdf" "W:\Electronic File %All%"

goto :loop

pause
</code>```

答:
for %%A in (*.pdf) do (
   echo File Found %%A
   set fname=%%~nA
   set fextn=%%~xA
   set folname=!fname:~5,8!
   ECHO !folname!|FINDSTR /i /r "[A-Z]-[0-9][0-9][0-9][0-9][0-9][0-9]" >NUL
   IF ERRORLEVEL 1 (
    ECHO %%A - !folname! excluded
   ) ELSE (
    echo Name folder !folname!
    if not exist "!folname!" (
       echo Folder !folname! dont exist, creating
       ECHO md "!folname!" 2>nul
    ) else (
       echo Folder !folname! exists
    )
    echo Copying file %%A to folder !folname!
    ECHO xcopy "%%A" "!folname!"
   )
)
```

<p>Here's the meat of the matter. <code>delayedexpansion</code> needs to be on - you don't show that in your original code.</p>

<p>Note that there is no requirement for <code>%%B</code>, <code>%%C</code>, <code>%%D</code> as within the loop, <code>%%A</code> contains the filename and hence you can <code>set</code> the variables from that name.</p>

<p>Note that <code>fextn</code> will apparently always be <code>.pdf</code> since that is the extension you specify in your filemask <code>*.pdf</code> so setting it seems superfluous.</p>

<p>The syntax <code>SET "var=value"</code> (where value may be empty) may be used to ensure that any stray trailing spaces are NOT included in the value assigned.</p>

<p>The change I've introduced is to <code>echo</code> the directoryname to <code>findstr</code>, searching <code>/i</code> case-insensitively for <code>/r</code> a regular-expression  which is one letter, a dash and then 6 numerics. If the directoryname matches then <code>errorlevel</code> will be set to <code>0</code> by <code>findstr</code>, otherwise, it will be set to <code>1</code>.</p>

<p>The <code>if errorlevel 1</code> means "if errorlevel is 1 or greater" and if that is so, the match was <strong>UN</strong>successful, so report the filename and extracted directoryname; otherwise, go through your logic (I've changed it to simply <code>echo</code> the <code>md</code> and <code>xcopy</code> commands, for testing).</p>

<hr>

<p>Given that we now have a variable structure,</p>

```for %%A in (*.pdf) do (
   echo File Found %%A
   set "copied="
   set fname=%%~nA
   set fextn=%%~xA
   set folname=!fname:~5,8!
   ECHO !folname!|FINDSTR /i /r "[A-Z]-[0-9][0-9][0-9][0-9][0-9][0-9]" >NUL
   IF not ERRORLEVEL 1 call :process "%%A"

   rem repeat this section for each match required - begin
   if not defined copied (
    set folname=!fname:~5,9!
    ECHO !folname!|FINDSTR /i /r "[A-Z][A-Z][A-Z]-[0-9][0-9]-[0-9][0-9]" >NUL
    IF not ERRORLEVEL 1 call :process "%%A"
   )
   rem repeat this section for each match required - end

   if not defined copied ECHO %%A - !folname! excluded
)
goto :eof

:process
echo Name folder %folname%
if not exist "%folname%" (
 echo Folder %folname% dont exist, creating
 ECHO md "%folname%" 2>nul
) else (
  echo Folder %folname% exists
)
echo Copying file %~1 to folder %folname%
ECHO xcopy "%~1" "%folname%"
set "copied=Y"
goto :eof
```

In your extended examples, it's not clear where the PP fits into the scheme.

The formula is reasonably simple. The start position is the first argument in the set (counting from first character=0) and the second the length to select. The regex match may be either a single character (matched literally) or [rangestart-rangeend] . matches any one character, so the first block I've shown selects from  HC123CLG-32-172436787004259 from the 5th character (starting at 0) for 9 characters =CLG-32-17 and matches this against alpha,alpha,alpha,-,numeric,numeric,-,numeric,numeric.

On a match, errorlevel is set to 0, so the :process subroutine is called, with a parameter of %%A in quotes. The subroutine uses the value in folname and copies the file (name now in %1 - %~1 removes the quotes) as before.

So - it's as simple as repeating the block of code, altering the start and length of the string to be selected and changing the regex to suit the required pattern.

Title: Batch Copy and Add to sub folder

Body:
hope you can help me with this, i can't make it work what i need

I need to copy all the .pdf files from a source folder, create a folder with part of the name "T-123456" and add the respective PDF files found in the correct folder in the destination folder, but sometimes the name it varies or the reference change "SM17-123".

Example of files

HC002T-1234562436787004332

MV002T-1234562436787004332

PP _002_T-123456_24_3678_7004332

Types of direfents files

HC123CLG-32-172436787004259

HC123SM17-1802436787004044

i have this code created but it makes part of the job because the name varies and create folders incorrect for that files, sometimes the files have more digits in the beggining example 001 or 0001, so i dont know how to omit the other references files and only work whith files "T-123456" also i need the batch continuously working for new files created in the source folder and if i have another routhe where i have other types of file and copy to the correct reference it would be great.

@echo off
title Electronic File

:loop
cls
timeout -t 1 >nul
color b
for %%A in (*.pdf) do (
   echo File Found %%A
   for /f "delims=" %%B in ("%%A") do set fname=%%~nB
   for /f "delims=" %%C in ("%%A") do set fextn=%%~xC
   for /f "tokens=1* delims=" %%D in ("!fname:~5,8!") do set folname=%%D
   echo Name folder !folname!
   if not exist "!folname!" (
      echo Folder !folname! dont exist, creating
      md "!folname!" 2>nul
   ) else (
      echo Folder !folname! exists
   )
   echo Copying file %%A to folder !folname!
   xcopy "%%A" "!folname!"
   )

echo on

md "C:\test %All%"

xcopy /s /y "X:\test\pdf" "W:\Electronic File %All%"

goto :loop

pause

Body:
for %%A in (*.pdf) do (
   echo File Found %%A
   set fname=%%~nA
   set fextn=%%~xA
   set folname=!fname:~5,8!
   ECHO !folname!|FINDSTR /i /r "[A-Z]-[0-9][0-9][0-9][0-9][0-9][0-9]" >NUL
   IF ERRORLEVEL 1 (
    ECHO %%A - !folname! excluded
   ) ELSE (
    echo Name folder !folname!
    if not exist "!folname!" (
       echo Folder !folname! dont exist, creating
       ECHO md "!folname!" 2>nul
    ) else (
       echo Folder !folname! exists
    )
    echo Copying file %%A to folder !folname!
    ECHO xcopy "%%A" "!folname!"
   )
)

Here's the meat of the matter. delayedexpansion needs to be on - you don't show that in your original code.

Note that there is no requirement for %%B, %%C, %%D as within the loop, %%A contains the filename and hence you can set the variables from that name.

Note that fextn will apparently always be .pdf since that is the extension you specify in your filemask *.pdf so setting it seems superfluous.

The syntax SET "var=value" (where value may be empty) may be used to ensure that any stray trailing spaces are NOT included in the value assigned.

The change I've introduced is to echo the directoryname to findstr, searching /i case-insensitively for /r a regular-expression  which is one letter, a dash and then 6 numerics. If the directoryname matches then errorlevel will be set to 0 by findstr, otherwise, it will be set to 1.

The if errorlevel 1 means "if errorlevel is 1 or greater" and if that is so, the match was UNsuccessful, so report the filename and extracted directoryname; otherwise, go through your logic (I've changed it to simply echo the md and xcopy commands, for testing).

Given that we now have a variable structure,

for %%A in (*.pdf) do (
   echo File Found %%A
   set "copied="
   set fname=%%~nA
   set fextn=%%~xA
   set folname=!fname:~5,8!
   ECHO !folname!|FINDSTR /i /r "[A-Z]-[0-9][0-9][0-9][0-9][0-9][0-9]" >NUL
   IF not ERRORLEVEL 1 call :process "%%A"

   rem repeat this section for each match required - begin
   if not defined copied (
    set folname=!fname:~5,9!
    ECHO !folname!|FINDSTR /i /r "[A-Z][A-Z][A-Z]-[0-9][0-9]-[0-9][0-9]" >NUL
    IF not ERRORLEVEL 1 call :process "%%A"
   )
   rem repeat this section for each match required - end

   if not defined copied ECHO %%A - !folname! excluded
)
goto :eof

:process
echo Name folder %folname%
if not exist "%folname%" (
 echo Folder %folname% dont exist, creating
 ECHO md "%folname%" 2>nul
) else (
  echo Folder %folname% exists
)
echo Copying file %~1 to folder %folname%
ECHO xcopy "%~1" "%folname%"
set "copied=Y"
goto :eof

In your extended examples, it's not clear where the PP fits into the scheme.

The formula is reasonably simple. The start position is the first argument in the set (counting from first character=0) and the second the length to select. The regex match may be either a single character (matched literally) or [rangestart-rangeend] . matches any one character, so the first block I've shown selects from  HC123CLG-32-172436787004259 from the 5th character (starting at 0) for 9 characters =CLG-32-17 and matches this against alpha,alpha,alpha,-,numeric,numeric,-,numeric,numeric.

On a match, errorlevel is set to 0, so the :process subroutine is called, with a parameter of %%A in quotes. The subroutine uses the value in folname and copies the file (name now in %1 - %~1 removes the quotes) as before.

So - it's as simple as repeating the block of code, altering the start and length of the string to be selected and changing the regex to suit the required pattern.


问:
MS Word web add-in javascript search multiple strings at the same time
I have been able to run the Github project Word-Add-in-JS-Redact successfully. Now, I need to make a change in the code. Need help for that.

At present the code finds multiple occurrences of a single string in a Word Doc and highlights those. But, I need to search multiple strings (can be hard coded inside the js file as well) in the document with a single button click, and highlight those. For example, I want to find both strings 'this' and 'that' in the document at the same time, and highlight them.

The current code, which searches for a single string:

```<code>Word.run(function (context) {
                //search string
                var searchInput = "hello";
                // Search the document.
                var searchResults = context.document.body.search(searchInput, {matchWildCards: true});

            // Load the search results and get the font property values.
            context.load(searchResults, "");

            // Synchronize the document state by executing the queued-up commands,
            // and return a promise to indicate task completion.
            return context.sync()
                .then(function () {
                    var count = searchResults.items.length;
                    // // Queue a set of commands to change the font for each found item.
                    for (var i = 0; i < count; i++) {
                        searchResults.items[i].font.highlightColor = '#FFFF00'; //Yellow
                    }
                    return count;
                })
                .then(context.sync)
                .then(reportWordsFound);
</code>```

A couple of ways I have tried so far with no luck:

Ran context.document.body.search(searchInput, in a loop of the search strings, and tried to append the searchResults strings using + and push. This attempt gave an error saying, I cannot add multiple context results to a single object.

I tried to be creative with WildCards operators, but nothing was suitable for this. Many posts are talking about JS regex \(string1|string2/), but this seems to be invalid in Word context.

答:
I could solve the problem at last, by creating a parent function, which calls the search function in a loop. My mistake was to create the loop inside the search function itself.

Here is the working code:

```<code>function searchStrings(){
    searchString('hello world');
    searchString('Goodbye');
}
RedactAddin.searchStrings = searchStrings;

function searchString(input) {
    // Run a batch operation against the Word object model.
    Word.run(function (context) {
   //...... (same as the original) ...............
</code>```

Body:
I have been able to run the Github project Word-Add-in-JS-Redact successfully. Now, I need to make a change in the code. Need help for that.

At present the code finds multiple occurrences of a single string in a Word Doc and highlights those. But, I need to search multiple strings (can be hard coded inside the js file as well) in the document with a single button click, and highlight those. For example, I want to find both strings 'this' and 'that' in the document at the same time, and highlight them.

The current code, which searches for a single string:

Word.run(function (context) {
                //search string
                var searchInput = "hello";
                // Search the document.
                var searchResults = context.document.body.search(searchInput, {matchWildCards: true});

            // Load the search results and get the font property values.
            context.load(searchResults, "");

            // Synchronize the document state by executing the queued-up commands,
            // and return a promise to indicate task completion.
            return context.sync()
                .then(function () {
                    var count = searchResults.items.length;
                    // // Queue a set of commands to change the font for each found item.
                    for (var i = 0; i < count; i++) {
                        searchResults.items[i].font.highlightColor = '#FFFF00'; //Yellow
                    }
                    return count;
                })
                .then(context.sync)
                .then(reportWordsFound);

A couple of ways I have tried so far with no luck:

Ran context.document.body.search(searchInput, in a loop of the search strings, and tried to append the searchResults strings using + and push. This attempt gave an error saying, I cannot add multiple context results to a single object.

I tried to be creative with WildCards operators, but nothing was suitable for this. Many posts are talking about JS regex \(string1|string2/), but this seems to be invalid in Word context.

Body:
I could solve the problem at last, by creating a parent function, which calls the search function in a loop. My mistake was to create the loop inside the search function itself.

Here is the working code:

function searchStrings(){
    searchString('hello world');
    searchString('Goodbye');
}
RedactAddin.searchStrings = searchStrings;

function searchString(input) {
    // Run a batch operation against the Word object model.
    Word.run(function (context) {
   //...... (same as the original) ...............