问:
How many output nodes should my Convolutional Neural Network have?
I am using the Passenger Screening Challenge from the Kaggle website for a class project.

I've implemented an out-of-the-box Convolutional Neural Network from this tutorial: https://www.r-bloggers.com/image-recognition-tutorial-in-r-using-deep-convolutional-neural-networks-mxnet-package/.

Here is the code from the tutorial for the architecture:

```<code># 1st convolutional layer
conv_1 <- mx.symbol.Convolution(data = data, kernel = c(5, 5), num_filter = 20)
tanh_1 <- mx.symbol.Activation(data = conv_1, act_type = "tanh")
pool_1 <- mx.symbol.Pooling(data = tanh_1, pool_type = "max", kernel = c(2, 2), stride = c(2, 2))
# 2nd convolutional layer
conv_2 <- mx.symbol.Convolution(data = pool_1, kernel = c(5, 5), num_filter = 50)
tanh_2 <- mx.symbol.Activation(data = conv_2, act_type = "tanh")
pool_2 <- mx.symbol.Pooling(data=tanh_2, pool_type = "max", kernel = c(2, 2), stride = c(2, 2))
# 1st fully connected layer
flatten <- mx.symbol.Flatten(data = pool_2)
fc_1 <- mx.symbol.FullyConnected(data = flatten, num_hidden = 500)
tanh_3 <- mx.symbol.Activation(data = fc_1, act_type = "tanh")
# 2nd fully connected layer
fc_2 <- mx.symbol.FullyConnected(data = tanh_3, num_hidden = 40)
# Output. Softmax output since we'd like to get some probabilities.
NN_model <- mx.symbol.SoftmaxOutput(data = fc_2)
</code>```

However, I have a question about the num_hidden on the fc_2. In the tutorial, this number was 40 because there were 40 classes.

In my example, I'm determining if there is a threat present on an image or not.  Would my num_hidden in the last fully connected layer be 2 (threat present or no threat) or 1 (probability that there is a threat present?  Am I overthinking?

答: Yes, if you are classifying a binary problem then the number of neurons in the fc2 layer should 2 instead of 40. </p>

Body:
I am using the Passenger Screening Challenge from the Kaggle website for a class project.

I've implemented an out-of-the-box Convolutional Neural Network from this tutorial: https://www.r-bloggers.com/image-recognition-tutorial-in-r-using-deep-convolutional-neural-networks-mxnet-package/.

Here is the code from the tutorial for the architecture:

# 1st convolutional layer
conv_1 <- mx.symbol.Convolution(data = data, kernel = c(5, 5), num_filter = 20)
tanh_1 <- mx.symbol.Activation(data = conv_1, act_type = "tanh")
pool_1 <- mx.symbol.Pooling(data = tanh_1, pool_type = "max", kernel = c(2, 2), stride = c(2, 2))
# 2nd convolutional layer
conv_2 <- mx.symbol.Convolution(data = pool_1, kernel = c(5, 5), num_filter = 50)
tanh_2 <- mx.symbol.Activation(data = conv_2, act_type = "tanh")
pool_2 <- mx.symbol.Pooling(data=tanh_2, pool_type = "max", kernel = c(2, 2), stride = c(2, 2))
# 1st fully connected layer
flatten <- mx.symbol.Flatten(data = pool_2)
fc_1 <- mx.symbol.FullyConnected(data = flatten, num_hidden = 500)
tanh_3 <- mx.symbol.Activation(data = fc_1, act_type = "tanh")
# 2nd fully connected layer
fc_2 <- mx.symbol.FullyConnected(data = tanh_3, num_hidden = 40)
# Output. Softmax output since we'd like to get some probabilities.
NN_model <- mx.symbol.SoftmaxOutput(data = fc_2)

However, I have a question about the num_hidden on the fc_2. In the tutorial, this number was 40 because there were 40 classes.

In my example, I'm determining if there is a threat present on an image or not.  Would my num_hidden in the last fully connected layer be 2 (threat present or no threat) or 1 (probability that there is a threat present?  Am I overthinking?


来源: stackexchange

问:
Retrieving servlet context, session and request in a POJO outside container
Is there any way to retrieve a session from a POJO? Or ultimately to retrieve a bean from a POJO.

To clarify:

Basically I am creating a bean from a servlet and I need to access the properties of that bean from outside of the web container (from a POJO). I cannot pass the request to the pojo; and the request is needed to retrieve the session.

More specifically I have a web application that uses the Cactus framework to run JUnit tests from a web interface. However the servlet that invokes the JUnit test runner is compiled in a jar; I added extra drop down menus to change settings from which the JUnit test will read from to switch between different environments (WLI clusters), so given that the runner servlet is already compiled I cannot modify it to handle the extra parameters from the multiple environments. I have tried the persistence approach of writing to a .dat file fro which the JUnit test will read from by way of a Reader class; also I have have tried the bean approach which ultimately was not accessible from the JUnit test.

答:
A Pojo is a Plain Old Java Object.  POJOS have nothing to do with sessions.

The https session is available on the request object.

Check out this

http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.6/api/index.html

specifically the HttpServletRequest interface, and the getSession() method.

For the 'bean' part of your question.  A bean is a java class that conforms to 3 standards.

No arg constructor

setters and getters to access private fields

Implements serializable.

A POJO is a bean if it follows those conventions.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
hiding s3 path in aws cloudfront url
I am trying to make sure I did not miss anything in the AWS CloudFront documentation or anywhere else ...

I have a (not public) S3 bucket configured as origin in a CloudFront web distribution (i.e. I don't think it matters but I am using signed urls).

Let's say a have a file in a S3 path like
/someRandomString/someCustomerName/someProductName/somevideo.mp4

So, perhaps the url generated by CloudFront would be something like:

https://my.domain.com/someRandomString/someCustomerName/someProductName/somevideo.mp4?Expires=1512062975&Signature=unqsignature&Key-Pair-Id=keyid

Is there a way to obfuscate the path to actual file on the generated URL. All 3 parts before the filename can change, so I prefer not to use "Origin Path" on Origin Settings to hide the begging of the path. With that approach, I would have to create a lot of origins mapped to the same bucket but different paths. If that's the only way, then the limit of 25 origins per distribution would be a problem.

Ideally, I would like to get something like

https://my.domain.com/someRandomObfuscatedPath/somevideo.mp4?Expires=1512062975&Signature=unqsignature&Key-Pair-Id=keyid

Note: I am also using my own domain/CNAME.

Thanks
Cris

答:
Obfuscation is not a form of security.

If you wish to control which objects users can access, you should use Pre-Signed URLs or Cookies. This way, you can grant access to private objects via S3 or CloudFront and not worry about people obtaining access to other objects.

See: Serving Private Content through CloudFront

Title: hiding s3 path in aws cloudfront url


问:
Hive array specifying multiple delimiter in collection
I have dataset contains two arrays, both arrays separated by different delimiter..
Ex: 14-20-50-60 is 1st array seperated by -
12#2#333#4 is 2nd array seperated by #..

While creating table how do we specify delimiter in
Collection items terminated by '' ?

input
14-20-50-60,12#2#333#4

```<code>create table test(first array<string>, second array<string>)
row format delimited
fields terminated by ','
collection items terminated by '-' (How to specify two delimiters in the collection)
</code>```

答:
You cannot use multiple delimiters for the collection items. You can achieve what you are trying to do as below though. I have used the SPLIT function to create the array using different delimiters.

Data

```<code>14-20-50-60,12#2#333#4
</code>```

SQL - CREATE TABLE

```<code>create external table test1(first string, second string)
row format delimited
fields terminated by ','
LOCATION  '/user/cloudera/ramesh/test1';
</code>```

SQL - SELECT

```<code>WITH v_test_array AS
(SELECT split(first, "-") AS first_array,
        split(second, "#") AS second_array
   FROM test1)
SELECT first_array[0], second_array[0]
  FROM v_test_array;
</code>```

OUTPUT

```<code>14  12
</code>```

Hope this helps.

Body:
I have dataset contains two arrays, both arrays separated by different delimiter..
Ex: 14-20-50-60 is 1st array seperated by -
12#2#333#4 is 2nd array seperated by #..

While creating table how do we specify delimiter in
Collection items terminated by '' ?

input
14-20-50-60,12#2#333#4

create table test(first array<string>, second array<string>)
row format delimited
fields terminated by ','
collection items terminated by '-' (How to specify two delimiters in the collection)

Body:
You cannot use multiple delimiters for the collection items. You can achieve what you are trying to do as below though. I have used the SPLIT function to create the array using different delimiters.

Data

14-20-50-60,12#2#333#4

SQL - CREATE TABLE

create external table test1(first string, second string)
row format delimited
fields terminated by ','
LOCATION  '/user/cloudera/ramesh/test1';

SQL - SELECT

WITH v_test_array AS
(SELECT split(first, "-") AS first_array,
        split(second, "#") AS second_array
   FROM test1)
SELECT first_array[0], second_array[0]
  FROM v_test_array;

OUTPUT

14  12

Hope this helps.


问:
How to save H.264 stream to mp4 container using Accord.FFMPEG.Video
I am receiving raw H.264 frames in a callback in C#. I can save the stream to a *.264 file where I can see the video using Elecard StreamEye.

Is it possible to save the video to an mp4 container using Accord.FFMPEG.Video VideoFileWriter or VideoFileSource without re-encoding it?

I would rather not have to implement it using p/Invokes to libav unless there is no alternative.

答:
Check out this link. In general, ffmpeg is smart enough to output .mp4 based on the output extension specified. Also giving -copy avoids re-encoding.

https://askubuntu.com/questions/690015/how-can-i-convert-264-file-to-mp4


问:
Weblogic 12c REP-501: The specified database cannot be connected
I have a problem when executing it outside the form builder,

from the call

http: // localhost: 9001 / forms / frmservlet? Config = webutil_webstart

the report works well from the formbuilder and runs smoothly

but when executing it from the direct url, I do not run the report,

I do the validation on the server with showjobs the error that I have is

The report ended in error:
REP-501: The specified database can not be connected ..

Maybe you can give me a hand where I would be missing some configuration.

thanks a lot.

答:
look at your db alias(assume mydb01) in tnsnames.ora file under these paths:

$ORACLE_INSTANCE/config for Linux or Solaris.

maybe like C:\Oracle\Middleware\asinst_1\config for Windows.

Try to ping that alias like :

```<code>tnsping mydb01
</code>```

if succeeds, use it for your connections.

During call of run_report_object() you have some parameter settings, whilst you may have such alike statement :

```<code>hidden_action := hidden_action ||’&userid=’
||get_application_property(username)||’/’||
get_application_property(password)||’@’||
get_application_property(connect_string);
</code>```

Look at this arguments (connect_string,username&password) whether be set truely.

Body:
look at your db alias(assume mydb01) in tnsnames.ora file under these paths:

$ORACLE_INSTANCE/config for Linux or Solaris.

maybe like C:\Oracle\Middleware\asinst_1\config for Windows.

Try to ping that alias like :

tnsping mydb01

if succeeds, use it for your connections.

During call of run_report_object() you have some parameter settings, whilst you may have such alike statement :

hidden_action := hidden_action ||’&userid=’
||get_application_property(username)||’/’||
get_application_property(password)||’@’||
get_application_property(connect_string);

Look at this arguments (connect_string,username&password) whether be set truely.


问:
Pointer as generic type argument
I have a bunch of external C functions that in C# become something like this:

```<code>public extern static int clGetDeviceInfo(
    IntPtr device,
    uint param_name,
    IntPtr param_value_size,
    void* param_value,
    out IntPtr param_value_size_ret);
</code>```

Because there are a bunch of similar looking function, I wanted to create a method which reads the data provided by these C functions. This is what I went with:

```<code>unsafe public static ErrorCode GetInfoString(
    IntPtr handle, uint property,
    Func<IntPtr, uint, IntPtr, void*, IntPtr, int> infoFunc,
    out string value)
{
    // reading logic
}
</code>```

My problem is that C# does not allow me to use the void* as a generic argument of Func. Is there any way around this problem?

I can neither change the signature of external C function nor the signature of the C# function (I'm using a library).

答:
My problem is that C# does not allow me to use the void* as a generic argument of Func. Is there any way around this problem?

Yes. Use IntPtr everywhere that you are at present using void*.  Don't use void* in C# if you can possibly avoid it.

I can't change the signature of the functions I'm trying to pass as arguments, so that won't work.

Sure it does.  You have

```<code>public extern static int clGetDeviceInfo(
    IntPtr device,
    uint param_name,
    IntPtr param_value_size,
    void* param_value,
    out IntPtr param_value_size_ret);
</code>```

You can't change it because it is in a library. Fine. What can you change? You can change your own code. So write your own code! You're a computer programmer; that's what you do:

```<code>private static int MyClGetDeviceInfo(
    IntPtr device,
    uint param_name,
    IntPtr param_value_size,
    IntPtr param_value,
    out IntPtr param_value_size_ret)
{
  unsafe
  {
    return clGetDeviceInfo(device, param_name, param_value_size,
      (void*)param_value, out param_value_size_ret);
  }
}
</code>```

There, now you have a method that has a signature you can make a Func out of.

Title: Pointer as generic type argument

Body:
I have a bunch of external C functions that in C# become something like this:

public extern static int clGetDeviceInfo(
    IntPtr device,
    uint param_name,
    IntPtr param_value_size,
    void* param_value,
    out IntPtr param_value_size_ret);

Because there are a bunch of similar looking function, I wanted to create a method which reads the data provided by these C functions. This is what I went with:

unsafe public static ErrorCode GetInfoString(
    IntPtr handle, uint property,
    Func<IntPtr, uint, IntPtr, void*, IntPtr, int> infoFunc,
    out string value)
{
    // reading logic
}

My problem is that C# does not allow me to use the void* as a generic argument of Func. Is there any way around this problem?

I can neither change the signature of external C function nor the signature of the C# function (I'm using a library).

Body:
My problem is that C# does not allow me to use the void* as a generic argument of Func. Is there any way around this problem?

Yes. Use IntPtr everywhere that you are at present using void*.  Don't use void* in C# if you can possibly avoid it.

I can't change the signature of the functions I'm trying to pass as arguments, so that won't work.

Sure it does.  You have

public extern static int clGetDeviceInfo(
    IntPtr device,
    uint param_name,
    IntPtr param_value_size,
    void* param_value,
    out IntPtr param_value_size_ret);

You can't change it because it is in a library. Fine. What can you change? You can change your own code. So write your own code! You're a computer programmer; that's what you do:

private static int MyClGetDeviceInfo(
    IntPtr device,
    uint param_name,
    IntPtr param_value_size,
    IntPtr param_value,
    out IntPtr param_value_size_ret)
{
  unsafe
  {
    return clGetDeviceInfo(device, param_name, param_value_size,
      (void*)param_value, out param_value_size_ret);
  }
}

There, now you have a method that has a signature you can make a Func out of.


问:
Use VBA to Clear Immediate Window?
Does anyone know how to clear the immediate window using VBA?

While I can always clear it myself manually, I am curious if there is a way to do this programmatically.

答:
For cleaning Immediate window I use (VBA Excel 2016) next function:

```<code>Private Sub ClrImmediate()
   With Application.VBE.Windows("Immediate")
       .SetFocus
       Application.SendKeys "^g", True
       Application.SendKeys "^a", True
       Application.SendKeys "{DEL}", True
   End With
End Sub
</code>```

But direct call of ClrImmediate() like this:

```<code>Sub ShowCommandBarNames()
    ClrImmediate
 '--   DoEvents
    Debug.Print "next..."
End Sub
</code>```

works only if i put the breakpoint on Debug.Print, otherwise the clearing will be done after execution of ShowCommandBarNames()  - NOT before Debug.Print.
 Unfortunately, call of DoEvents() did not help me... And no matter: TRUE or FALSE is set for SendKeys.

To solve this I use next couple of calls:

```<code>Sub ShowCommandBarNames()
 '--    ClrImmediate
    Debug.Print "next..."
End Sub

Sub start_ShowCommandBarNames()
   ClrImmediate
   Application.OnTime Now + TimeSerial(0, 0, 1), "ShowCommandBarNames"
End Sub
</code>```

It seems to me that using Application.OnTime might be very useful in programming for VBA IDE. In this case it's can be used even TimeSerial(0, 0, 0).

Title: Use VBA to Clear Immediate Window?

Body:
For cleaning Immediate window I use (VBA Excel 2016) next function:

Private Sub ClrImmediate()
   With Application.VBE.Windows("Immediate")
       .SetFocus
       Application.SendKeys "^g", True
       Application.SendKeys "^a", True
       Application.SendKeys "{DEL}", True
   End With
End Sub

But direct call of ClrImmediate() like this:

Sub ShowCommandBarNames()
    ClrImmediate
 '--   DoEvents
    Debug.Print "next..."
End Sub

works only if i put the breakpoint on Debug.Print, otherwise the clearing will be done after execution of ShowCommandBarNames()  - NOT before Debug.Print.
 Unfortunately, call of DoEvents() did not help me... And no matter: TRUE or FALSE is set for SendKeys.

To solve this I use next couple of calls:

Sub ShowCommandBarNames()
 '--    ClrImmediate
    Debug.Print "next..."
End Sub

Sub start_ShowCommandBarNames()
   ClrImmediate
   Application.OnTime Now + TimeSerial(0, 0, 1), "ShowCommandBarNames"
End Sub

It seems to me that using Application.OnTime might be very useful in programming for VBA IDE. In this case it's can be used even TimeSerial(0, 0, 0).


问:
Rake cp permission denied on windows
Here's the rake file.

```<code>task :default  => :release

task :release do
    target = 'releases/' + Time.new.strftime('%Y%m%d')
    mkdir_p target
    cp Dir["web"], target
end
</code>```

I get "permission denied - web".
what do I have to do to give rake the same rights I have when it runs, in windows.

答:
I had this problem, as simple as the target was readonly. In this case web might not exist, or might not be readable.

I'm no expert in rake, but where is Dir declared?

Title: Rake cp permission denied on windows

Body:
Here's the rake file.

task :default  => :release

task :release do
    target = 'releases/' + Time.new.strftime('%Y%m%d')
    mkdir_p target
    cp Dir["web"], target
end

I get "permission denied - web".
what do I have to do to give rake the same rights I have when it runs, in windows.


问:
Vba Loop to Edit Excel files fails on Second Iteration
I am trying to build a routine that opens each excel file in a folder, searches ( using the Find command) for the string
 “# Issues”, selects the entire row where it finds the string, then delete that row and the next two additional rows. It runs successfully the first iteration, but fails the second time through the loop st the Find command.

I have struggled with this failure on second iteration several times with different code, making me think I am making some kind of mistake in defining my objects.

My code:

Function CleanFilesInAGivenFolder(strFolder As String, _
         strCellLoc As String, _
         strNewValue As String)

Dim strReportType As String
Dim myfile
Dim mypath
Dim strPathFileName As String

If Right(strFolder, 1) <> "\" Then
   strFolder = strFolder & "\"
End If
mypath = strFolder
ChDir (strFolder)

myfile = Dir(mypath)
ChDir (mypath)
myfile = Dir("")

Do While myfile <> ""

        'Format the excel report
            strPathFileName = mypath & myfile

            Dim appExcel As Excel.Application
            Dim wkb As Excel.Workbook
            Dim sht As Worksheet
            Dim rng As Range
            Dim FoundCell As Range

          'Define the file and location
            strPathFileName = mypath & myfile

           'define the excel session
            Set appExcel = New Excel.Application
            appExcel.Visible = True

           'Define the workbook
            Set wkb = appExcel.Workbooks.Open(strPathFileName)
                          'Make sheet 1 the active sheet
                          Set wkb = ActiveWorkbook
           Set sht = ActiveSheet

           'Find the row with "# Issues" in column A,
           'delete row this next 2 rows
           'Only works the first iteration of loop

    With sht
         Set FoundCell = Selection.Find(What:="# Issues", _
         After:=[a1],
         LookIn:=xlValues, _
         LookAt:=xlPart, _
         SearchOrder:=xlByRows, _
         SearchDirection:=xlNext, _
         MatchCase:=False, _
         SearchFormat:=False)
         ActiveCell.EntireRow.Select
     End With

If Not FoundCell Is Nothing Then
    Selection.Delete Shift:=xlUp
    Selection.Delete Shift:=xlUp
    Selection.Delete Shift:=xlUp
End If
          'Clear Objects
            appExcel.DisplayAlerts = False
            wkb.Save
            wkb.Close
            appExcel.DisplayAlerts = True
            Set rng = Nothing
            Set sht = Nothing
            Set wkb = Nothing
            appExcel.Quit
            Set appExcel = Nothing

     myfile = Dir()

Loop
End Function
```

答:
Here is the working code. I removed the select and active statements, and replaced the Selection.Find in the Find statement with .Cells.Find</p>

```<code>Function CleanFilesInAGivenFolder(strFolder As String, _
         strCellLoc As String, strNewValue As String)

Dim strReportType As String
Dim strCell As String
Dim strValue As String
Dim myfile
Dim mypath
Dim strPathFileName As String

strCell = strCellLoc
strValue = strNewValue

'if it needs a backslash on the end, add one
If Right(strFolder, 1) <> "\" Then
   strFolder = strFolder & "\"
End If

mypath = strFolder
ChDir (strFolder)

myfile = Dir(mypath)
ChDir (mypath)
myfile = Dir("")

Do While myfile <> ""

        'Format the excel report
            strPathFileName = mypath & myfile

            Dim appExcel As Excel.Application
            Dim wkb As Excel.Workbook
            Dim sht As Worksheet
            Dim rng As Range
            Dim FoundCell As Range

          'Define the file and location
            strPathFileName = mypath & myfile

           'define the excel session
            Set appExcel = New Excel.Application
            appExcel.Visible = True

           'Define the workbook
            Set wkb = appExcel.Workbooks.Open(strPathFileName)

Set sht = wkb.Sheets(1)
  With sht
     Set FoundCell = .Cells.Find(What:="# Issues", _
     After:=.Cells(1, 1), _
    LookIn:=xlFormulas, _
    LookAt:=xlPart, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False)

    If Not FoundCell Is Nothing Then
        FoundCell.Offset(2, 0).Delete Shift:=xlUp
        FoundCell.Offset(1, 0).Delete Shift:=xlUp
        FoundCell.Delete Shift:=xlUp
    End If
 End With
          'Clear Objects
            appExcel.DisplayAlerts = False
            wkb.Save
            wkb.Close
            appExcel.DisplayAlerts = True
            Set rng = Nothing
            Set sht = Nothing
            Set wkb = Nothing
            Set FoundCell = Nothing
            appExcel.Quit
            Set appExcel = Nothing
        myfile = Dir()
   Loop
   MsgBox "The Excel File Edits Are Completed", vbExclamation
End Function
</code>```

Body:
Here is the working code. I removed the select and active statements, and replaced the Selection.Find in the Find statement with .Cells.Find

Function CleanFilesInAGivenFolder(strFolder As String, _
         strCellLoc As String, strNewValue As String)

Dim strReportType As String
Dim strCell As String
Dim strValue As String
Dim myfile
Dim mypath
Dim strPathFileName As String

strCell = strCellLoc
strValue = strNewValue

'if it needs a backslash on the end, add one
If Right(strFolder, 1) <> "\" Then
   strFolder = strFolder & "\"
End If

mypath = strFolder
ChDir (strFolder)

myfile = Dir(mypath)
ChDir (mypath)
myfile = Dir("")

Do While myfile <> ""

        'Format the excel report
            strPathFileName = mypath & myfile

            Dim appExcel As Excel.Application
            Dim wkb As Excel.Workbook
            Dim sht As Worksheet
            Dim rng As Range
            Dim FoundCell As Range

          'Define the file and location
            strPathFileName = mypath & myfile

           'define the excel session
            Set appExcel = New Excel.Application
            appExcel.Visible = True

           'Define the workbook
            Set wkb = appExcel.Workbooks.Open(strPathFileName)

Set sht = wkb.Sheets(1)
  With sht
     Set FoundCell = .Cells.Find(What:="# Issues", _
     After:=.Cells(1, 1), _
    LookIn:=xlFormulas, _
    LookAt:=xlPart, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False)

    If Not FoundCell Is Nothing Then
        FoundCell.Offset(2, 0).Delete Shift:=xlUp
        FoundCell.Offset(1, 0).Delete Shift:=xlUp
        FoundCell.Delete Shift:=xlUp
    End If
 End With
          'Clear Objects
            appExcel.DisplayAlerts = False
            wkb.Save
            wkb.Close
            appExcel.DisplayAlerts = True
            Set rng = Nothing
            Set sht = Nothing
            Set wkb = Nothing
            Set FoundCell = Nothing
            appExcel.Quit
            Set appExcel = Nothing
        myfile = Dir()
   Loop
   MsgBox "The Excel File Edits Are Completed", vbExclamation
End Function


问:
Installing python patch to retrieve dates before 1900 in Pycharm
My python code shown below is not retrieving any dates before the year 1900. I learned that this is a limitation of datetime.strptime().

I have tried to follow some of the workaround mentioned in similar posts , Is there any way to use a strftime-like function for dates before 1900 in Python? but they seem a bit complicated for me to follow. I also learned that there is a patch available to fix this issue. https://bugs.python.org/file10253/strftime-pre-1900.patch

I tried to install the patch in Pycharm by copying the patch to a text file,  but I am getting the following error message. Any ideas on what I need to do to run the patch successfully to get dates before 1900 ?

Pycharm Patch Error Screenshot

My Code:

```<code>from datetime import datetime

import csv

with open('train.csv', 'r') as f_input, open('sample.txt', 'w') as f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)

for row in csv_input:
    for date_format in ['%Y']:
        try:
            converted = datetime.strptime(row[3], date_format)
            csv_output.writerow([row[0], row[1], row[2], converted.strftime(date_format)])
        except ValueError:
            pass
</code>```

答:
I realize this isn't what you asked, but I'll put it out there anyway since I'm assuming that if the answers to the linked question are too complicated to follow, the idea to patch your problem away successfully is probably unrealistic.

The limitation you are seeing is present in Python2:

```<code>Python 2.7.12 (default, Nov 20 2017, 18:23:56)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: year=1899 is before 1900; the datetime strftime() methods require year >= 1900
</code>```

It is somewhat rectified in Python3.2, and fully rectified in Python3.3 and onward:

```<code>Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
'1899-01-01'
</code>```

Parsing works too:

```<code>>>> d = datetime.strptime('0113-01-01','%Y-%m-%d')
>>> d
datetime.datetime(113, 1, 1, 0, 0)
>>> d.isoformat()
'0113-01-01T00:00:00'
>>> d.strftime('%Y-%m-%d')
'113-01-01'
</code>```

So if that is an acceptable option, you could switch over to Python3.3+ and you won't have this issue.

Body:
My python code shown below is not retrieving any dates before the year 1900. I learned that this is a limitation of datetime.strptime().

I have tried to follow some of the workaround mentioned in similar posts , Is there any way to use a strftime-like function for dates before 1900 in Python? but they seem a bit complicated for me to follow. I also learned that there is a patch available to fix this issue. https://bugs.python.org/file10253/strftime-pre-1900.patch

I tried to install the patch in Pycharm by copying the patch to a text file,  but I am getting the following error message. Any ideas on what I need to do to run the patch successfully to get dates before 1900 ?

Pycharm Patch Error Screenshot

My Code:

from datetime import datetime

import csv

with open('train.csv', 'r') as f_input, open('sample.txt', 'w') as f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)

for row in csv_input:
    for date_format in ['%Y']:
        try:
            converted = datetime.strptime(row[3], date_format)
            csv_output.writerow([row[0], row[1], row[2], converted.strftime(date_format)])
        except ValueError:
            pass

Body:
I realize this isn't what you asked, but I'll put it out there anyway since I'm assuming that if the answers to the linked question are too complicated to follow, the idea to patch your problem away successfully is probably unrealistic.

The limitation you are seeing is present in Python2:

Python 2.7.12 (default, Nov 20 2017, 18:23:56)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: year=1899 is before 1900; the datetime strftime() methods require year >= 1900

It is somewhat rectified in Python3.2, and fully rectified in Python3.3 and onward:

Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
'1899-01-01'

Parsing works too:

>>> d = datetime.strptime('0113-01-01','%Y-%m-%d')
>>> d
datetime.datetime(113, 1, 1, 0, 0)
>>> d.isoformat()
'0113-01-01T00:00:00'
>>> d.strftime('%Y-%m-%d')
'113-01-01'

So if that is an acceptable option, you could switch over to Python3.3+ and you won't have this issue.


问:
Vim on Ubuntu: Text rendering bug, repeating and disappearing weirdly
I had vim installed on ubuntu 12.04 not long ago. Sometimes when I run my cursor (using keyboard, not mouse) over code, text disappears, as though there is a problem rendering the character. When I run the cursor back again, it usually reappears.

This seems to happen quite randomly but is often enough to make it irritating.

To make it clearer, here's an example:

1.Original text:

Hi! How are you today.

2.Text after cursor runs over it

H ! How re yo today.

3.After running the cursor over the sentence again

i! How ar  you tod y.

Finally, after running the cursor over the sentence a few times, it is back to normal

.vimrc file:

```<code>set nocompatible               " be iMproved
 syntax on        "Syntax highlighting
 filetype off
 set rtp+=~/.vim/bundle/vundle/
 call vundle#rc()

 colorscheme evening

 "font
 set nu
 set guifont=Monospace\ 12
 set foldmethod=indent
 set foldlevel=99
 set lines=50 columns=80
 set ignorecase "searching is not case sensitive
 set smartcase "if a pattern contains uppercase, searching IS case sensitive
 set autoindent
 set tabstop=4

 winpos 1068 24
 " Type 'za' to open and close a fold
 " let Vundle manage Vundle

 Bundle 'gmarik/vundle'

 " original repos on github
 Bundle 'tpope/vim-fugitive'
 " vim-scripts repos
 Bundle 'L9'
 Bundle 'FuzzyFinder'
 " git repos on your local machine (ie. when working on your own plugin)

 "Bundles I install
 Bundle 'https://github.com/scrooloose/nerdtree.git'
 Bundle 'scrooloose/syntastic'
 Bundle 'dbakker/vim-lint'
 Bundle 'Lokaltog/powerline', {'rtp': 'powerline/bindings/vim/'}

 "snipmate
 Bundle "MarcWeber/vim-addon-mw-utils"
 Bundle "tomtom/tlib_vim"
 Bundle "snipmate-snippets"

"Install snipmate:
 Bundle "garbas/vim-snipmate"

 Bundle "sudar/vim-arduino-snippets"

 "PYTHON
 filetype plugin indent on
 Bundle 'klen/python-mode'
 autocmd BufRead *.py nmap <F5> :!python %<CR>
 set laststatus=2
 " :BundleList          - list configured bundles
 " :BundleInstall(!)    - install(update) bundles
 " :BundleSearch(!) foo - search(or refresh cache first) for foo
 " :BundleClean(!)      - confirm(or auto-approve) removal of unused bundles
 " see :h vundle for more details or wiki for FAQ
 " NOTE: comments after Bundle command are not allowed..
 " ARDUINO
 autocmd! BufNewFile,BufRead *.pde,*.ino  setlocal ft=arduino
</code>```

Edit:

I tried to take a screenshot of the problem, but realized that after taking a screenshot, gvim would sort of "refresh", and missing fonts appear again. Alt-Tabbing helps too. But I have not found a permanent solution to this problem.

Also, moving my cursor over the line of text with characters missing would sometimes cause other characters to go missing while old characters appear. Sometimes the cursor would also leave behind static images of other cursors.

I've also got vim installed on windows, shall try it there to see if the same problem appears.

Screenshot, notice the empty rectangle in the bottom left:

Update: So I've reinstalled ubuntu (this time to 14.04), gvim and vim. There are still some annoying rendering issues, although it manifests differently (see screenshot 2). Line numbers and percentages go haywire and scroll along with the page when I scroll down using "j". Only happens for vim so far. Gvim is working okay.

答:
Maybe a late reply.
I'm running ubuntu 16.04 on a virtualbox machine, and had the same issue with the default VI. Fixed by just installing VIM on top:

sudo apt-get install vim

Body:
I had vim installed on ubuntu 12.04 not long ago. Sometimes when I run my cursor (using keyboard, not mouse) over code, text disappears, as though there is a problem rendering the character. When I run the cursor back again, it usually reappears.

This seems to happen quite randomly but is often enough to make it irritating.

To make it clearer, here's an example:

1.Original text:

Hi! How are you today.

2.Text after cursor runs over it

H ! How re yo today.

3.After running the cursor over the sentence again

i! How ar  you tod y.

Finally, after running the cursor over the sentence a few times, it is back to normal

.vimrc file:

set nocompatible               " be iMproved
 syntax on        "Syntax highlighting
 filetype off
 set rtp+=~/.vim/bundle/vundle/
 call vundle#rc()

 colorscheme evening

 "font
 set nu
 set guifont=Monospace\ 12
 set foldmethod=indent
 set foldlevel=99
 set lines=50 columns=80
 set ignorecase "searching is not case sensitive
 set smartcase "if a pattern contains uppercase, searching IS case sensitive
 set autoindent
 set tabstop=4

 winpos 1068 24
 " Type 'za' to open and close a fold
 " let Vundle manage Vundle

 Bundle 'gmarik/vundle'

 " original repos on github
 Bundle 'tpope/vim-fugitive'
 " vim-scripts repos
 Bundle 'L9'
 Bundle 'FuzzyFinder'
 " git repos on your local machine (ie. when working on your own plugin)

 "Bundles I install
 Bundle 'https://github.com/scrooloose/nerdtree.git'
 Bundle 'scrooloose/syntastic'
 Bundle 'dbakker/vim-lint'
 Bundle 'Lokaltog/powerline', {'rtp': 'powerline/bindings/vim/'}

 "snipmate
 Bundle "MarcWeber/vim-addon-mw-utils"
 Bundle "tomtom/tlib_vim"
 Bundle "snipmate-snippets"

"Install snipmate:
 Bundle "garbas/vim-snipmate"

 Bundle "sudar/vim-arduino-snippets"

 "PYTHON
 filetype plugin indent on
 Bundle 'klen/python-mode'
 autocmd BufRead *.py nmap <F5> :!python %<CR>
 set laststatus=2
 " :BundleList          - list configured bundles
 " :BundleInstall(!)    - install(update) bundles
 " :BundleSearch(!) foo - search(or refresh cache first) for foo
 " :BundleClean(!)      - confirm(or auto-approve) removal of unused bundles
 " see :h vundle for more details or wiki for FAQ
 " NOTE: comments after Bundle command are not allowed..
 " ARDUINO
 autocmd! BufNewFile,BufRead *.pde,*.ino  setlocal ft=arduino

Edit:

I tried to take a screenshot of the problem, but realized that after taking a screenshot, gvim would sort of "refresh", and missing fonts appear again. Alt-Tabbing helps too. But I have not found a permanent solution to this problem.

Also, moving my cursor over the line of text with characters missing would sometimes cause other characters to go missing while old characters appear. Sometimes the cursor would also leave behind static images of other cursors.

I've also got vim installed on windows, shall try it there to see if the same problem appears.

Screenshot, notice the empty rectangle in the bottom left:

Update: So I've reinstalled ubuntu (this time to 14.04), gvim and vim. There are still some annoying rendering issues, although it manifests differently (see screenshot 2). Line numbers and percentages go haywire and scroll along with the page when I scroll down using "j". Only happens for vim so far. Gvim is working okay.


问:
install odl-ovsdb-southbound-impl exception
In opendaylight carbon when installing
 feature:install odl-ovsdb-southbound-impl

I get the following exception

```<code>Exception in thread "Thread-133" java.net.BindException: Address already in use   at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:433)
at sun.nio.ch.Net.bind(Net.java:425)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:128)
at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:554)
at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1258)
at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:502)
at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:487)
at io.netty.handler.logging.LoggingHandler.bind(LoggingHandler.java:191)
at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:502)
at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:487)
at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:980)
at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:250)
at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:365)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:445)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
at java.lang.Thread.run(Thread.java:748)
</code>```

I also get it each time I start the ODL

答: The java.net.BindException: Address already in use means that something on the host you are running already holds one of the ports which OpenDaylight wants to open.  This could also happen if you start OpenDaylight twice.  Often the actual port is shown in this kind of error, and then you can use (on Linux) netstat to find what process is already on that port.  In this case for some reason its not showing which port; I don't know why.  So you could just do some trial and error and stop other things you are running one after the other one, and retry ODL, until you'll find what it is.

Body:
In opendaylight carbon when installing
 feature:install odl-ovsdb-southbound-impl

I get the following exception

Exception in thread "Thread-133" java.net.BindException: Address already in use   at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:433)
at sun.nio.ch.Net.bind(Net.java:425)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
at io.netty.channel.socket.nio.NioServerSocketChannel.doBind(NioServerSocketChannel.java:128)
at io.netty.channel.AbstractChannel$AbstractUnsafe.bind(AbstractChannel.java:554)
at io.netty.channel.DefaultChannelPipeline$HeadContext.bind(DefaultChannelPipeline.java:1258)
at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:502)
at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:487)
at io.netty.handler.logging.LoggingHandler.bind(LoggingHandler.java:191)
at io.netty.channel.AbstractChannelHandlerContext.invokeBind(AbstractChannelHandlerContext.java:502)
at io.netty.channel.AbstractChannelHandlerContext.bind(AbstractChannelHandlerContext.java:487)
at io.netty.channel.DefaultChannelPipeline.bind(DefaultChannelPipeline.java:980)
at io.netty.channel.AbstractChannel.bind(AbstractChannel.java:250)
at io.netty.bootstrap.AbstractBootstrap$2.run(AbstractBootstrap.java:365)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:403)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:445)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
at java.lang.Thread.run(Thread.java:748)

I also get it each time I start the ODL


问:
Complex query with filters in Entity Framework Core
I have a model with only 3 classes: User, Filter and FilterEntry.

```<code>class Filter
{
    public List<FilterEntry> Inclusions { get; set; }
    public List<FilterEntry> Exclusions { get; set; }
}

public class FilterEntry
{
    public string Name { get; set; }
    public int? Age { get; set; }
}

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}
</code>```

A Filter is filter that was persisted to the DB, you can see it like a definition of a filter. It contains one or more FilterEntries that define the filter. The Inclusions and Exclusions are the restrictions that apply to the filter.

An example:

```<code>var filter = new Filter
    {
       Inclusions = new[] { new FilterEntry { Age = 33 } },
       Exclusions = new[] { new FilterEntry { Name = "John" }, new FilterEntry { Name = "Peter" } },
    };
</code>```

This defines a Filter that will represent people aged 33, except for who are called "John" or "Peter". So, when this filter is applied to the Users, it should return all the users that are 33, except for Johns and Peters.

Now the problem. How do I create a query using Entity Framework that, given a Filter, returns the Users according to it?

I don't even know how to start! All I have is this:

```<code>Filter filter = dbContext.Filters.First(x => x.FilterId == filterId);
var filteredUsers = from u in dbContext.Users
     where ... // user is any of the in filter.Inclusions
     where ... // user is not in any of the filter.Exclusions
     select u;
</code>```

NOTICE that Filter and FilterEntry keep a 1-N relationship. I omitted the keys to simplify the code.

答:
You want to build a dynamic where clause, so I would recommend PredicateBuilder.  I haven't tested the code below, but you would want something like...

```<code>Filter filter = dbContext.Filters.First(x => x.FilterId == filterId);

var pb = new PredicateBuilder<User>();

foreach(var inclusion in filter.Inclusions)
{
    if(inclusion.Age.HasValue)
    {
        pb = pb.And(p => p.Age == inclusion.Age.Value);
    }
    if(!string.IsNullOrWhiteSpace(inclusion.Name))
    {
        pb = pb.And(p => p.Name == inclusion.Name);
    }
}

foreach(var exclusion in filter.Exclusions)
{
    if(exclusion.Age.HasValue)
    {
        pb = pb.And(p => p.Age != exclusion.Age.Value);
    }
    if(!string.IsNullOrWhiteSpace(exclusion.Name))
    {
        pb = pb.And(p => p.Name != exclusion.Name);
    }
}

var filteredUsers = dbContext.Users.AsExpandable().Where(pb);
</code>```

Body:
I have a model with only 3 classes: User, Filter and FilterEntry.

class Filter
{
    public List<FilterEntry> Inclusions { get; set; }
    public List<FilterEntry> Exclusions { get; set; }
}

public class FilterEntry
{
    public string Name { get; set; }
    public int? Age { get; set; }
}

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

A Filter is filter that was persisted to the DB, you can see it like a definition of a filter. It contains one or more FilterEntries that define the filter. The Inclusions and Exclusions are the restrictions that apply to the filter.

An example:

var filter = new Filter
    {
       Inclusions = new[] { new FilterEntry { Age = 33 } },
       Exclusions = new[] { new FilterEntry { Name = "John" }, new FilterEntry { Name = "Peter" } },
    };

This defines a Filter that will represent people aged 33, except for who are called "John" or "Peter". So, when this filter is applied to the Users, it should return all the users that are 33, except for Johns and Peters.

Now the problem. How do I create a query using Entity Framework that, given a Filter, returns the Users according to it?

I don't even know how to start! All I have is this:

Filter filter = dbContext.Filters.First(x => x.FilterId == filterId);
var filteredUsers = from u in dbContext.Users
     where ... // user is any of the in filter.Inclusions
     where ... // user is not in any of the filter.Exclusions
     select u;

NOTICE that Filter and FilterEntry keep a 1-N relationship. I omitted the keys to simplify the code.

Body:
You want to build a dynamic where clause, so I would recommend PredicateBuilder.  I haven't tested the code below, but you would want something like...

Filter filter = dbContext.Filters.First(x => x.FilterId == filterId);

var pb = new PredicateBuilder<User>();

foreach(var inclusion in filter.Inclusions)
{
    if(inclusion.Age.HasValue)
    {
        pb = pb.And(p => p.Age == inclusion.Age.Value);
    }
    if(!string.IsNullOrWhiteSpace(inclusion.Name))
    {
        pb = pb.And(p => p.Name == inclusion.Name);
    }
}

foreach(var exclusion in filter.Exclusions)
{
    if(exclusion.Age.HasValue)
    {
        pb = pb.And(p => p.Age != exclusion.Age.Value);
    }
    if(!string.IsNullOrWhiteSpace(exclusion.Name))
    {
        pb = pb.And(p => p.Name != exclusion.Name);
    }
}

var filteredUsers = dbContext.Users.AsExpandable().Where(pb);


问:
How do I style numbers?
I am trying to change the styling of numbers.

I want to add some space between every 3 digits.

I will know exactly where the numbers will be located in the html.

When I retrieve the number from the html it needs to be the exact same number as I entered. So I only want to style the number, not modify the number.

I may use javascript and/or css to try an achieve this

//test for success . . . do not remove
if(document.getElementById('number').innerHTML !== "1000"){
  alert('Wrong answer, you changed the number!!!');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="number">1000<p>

<p>The 1000 above should show up like 1 000<p></code>```

答:
I suggest to use display:flex so that the "sep" character is in auto-determined font-size.

The idea is that turn
1000
 into
1000
 by js.

Then, add "sep" character visually by css generated content. span:nth-last-of-type(3n) { content:<sep>; ..}. This way, the <sep>(can be any character actually) will have same font-size as number text.

demo

Title: How do I style numbers?

Body:
I am trying to change the styling of numbers.

I want to add some space between every 3 digits.

I will know exactly where the numbers will be located in the html.

When I retrieve the number from the html it needs to be the exact same number as I entered. So I only want to style the number, not modify the number.

I may use javascript and/or css to try an achieve this

//test for success . . . do not remove
if(document.getElementById('number').innerHTML !== "1000"){
  alert('Wrong answer, you changed the number!!!');
}

1000

The 1000 above should show up like 1 000

Body:
I suggest to use display:flex so that the "sep" character is in auto-determined font-size.

The idea is that turn <p>1000</p> into <p><span>1</span><span>0</span><span>0</span><span>0</span></p> by js.

Then, add "sep" character visually by css generated content. span:nth-last-of-type(3n) { content:<sep>; ..}. This way, the <sep>(can be any character actually) will have same font-size as number text.

demo


问:
Log4j2 configuration location
I am using a Spring boot app with log4j logging enabled.
All is well when I run my Spring boot app, I see the log lines in the correct layout. However, when I run a test, I get:

log4j:WARN No appenders could be found for logger (be.delijn.ritsimulator.util.LoadTimeTest).
  log4j:WARN Please initialize the log4j system properly.
  log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

I have tried moving the log4j2.xml file to every possible place on the classpath but I cannot seem to resolve this issue. I placed it in the root, under resources etc.
I just want to be able to have 1 log4j2.xml file instead of one for main and one for test.
Also, I do not want to set it using the system property.

Is this possible?
If so, how can I achieve this?

Thanks in advance!
Regards

答:
The warning you are seeing is a Log4j 1.2 warning. Somewhere in your classpath there’s a log4j-1.2.x.jar that gets loaded before the Log4j2 jars. This is not good. </p>

<p>Please remove the log4j-1.2.x.jar and add the log4j-1.2-api-2.x.jar: this is a compatibility jar that will route log4j 1.2 API calls to the Log4j2 implementation. </p>

Title: Log4j2 configuration location

Body:
The warning you are seeing is a Log4j 1.2 warning. Somewhere in your classpath there’s a log4j-1.2.x.jar that gets loaded before the Log4j2 jars. This is not good.

Please remove the log4j-1.2.x.jar and add the log4j-1.2-api-2.x.jar: this is a compatibility jar that will route log4j 1.2 API calls to the Log4j2 implementation.


问:
Is it possible to add custom metadata to file?
I know that each file has metadata like title, subject, keywords and comments:

But what if I need custom metadata like tags for example?

Is it possible to do it with C#?

答:
As per Jesper's comment, you can use the DSOFile library to read and write to Custom properties that are stored in ADS.

Works well for me though note the fact that the properties are lost when file is transferred to a different file system, including email.
see http://www.keysolutions.com/blogs/kenyee.nsf/d6plinks/KKYE-79KRU6 for a 64bit implementation, link to MS original and comments.

ContentLicense: CC BY-SA 4.0


问:
Audio metadata storage
I checked through the questions asked on SO on audio metadata, but could not find one which answers my doubt. Where exactly is the metadata of audio files stored, and in what form? Is it in the form of files or in a database? And where is this database of files stored?</p>

答:
As far as I know, audio file formats :

May support metadata standards (e.g. ID3v1, ID3v2, APEtag, iXML)

May also have their own native metadata format (e.g. MP4 boxes / Quicktime atoms, OGG/FLAC/OPUS/Speex/Theora VorbisComment, WMA native metadata, AIFF / AIFC native metadata...)

=> In these two cases, metadata is stored directly into the audio file itself.

HydrogenAudio maintains a field mapping table between the most common formats : http://wiki.hydrogenaud.io/index.php?title=Tag_Mapping

That being said, many audio players (e.g. iTunes, foobar2000) allow their users to edit any metadata field in any file, regardless of whether said fields are supported or not by the underlying tagging standards (e.g. adding an "Album Artist" field in an S3M file).

In order to do that, these audio players store metadata in their internal database, thus giving the illusion that the audio file has been "enriched" while its actual content remain unchanged.

Another classic use of audio player databases is to store the following fields :

Rating

Number of times played

Last time played

=> In that case, you'll find metadata in the audio player's internal database

Title: Audio metadata storage


问:
umbrella header for module 'myFramework' does not include header 'otherFramework.h'
My Swift / iOS9 framework 'viewer_protocol' uses another and external Objective-C framework (CocoaAsyncSocket). I'm using Carthage to build CocoaAsyncSocket. So far everything works fine: In have an example App inside my framework Xcode Project using my framework without any problems.

Now I want to use my Framework in a different Xcode Project - although using Carthage. I include only my Framework as a dependency and Carthage automatically resolves the dependencies to CocoaAsyncSocket. I embedded both frameworks into this new Xcode Project and build my App: Everything works fine here - except one warning I can't rid off:

```<code>/Users/John/Repositories/my_project/<module-includes>:1:1:
Umbrella header for module 'my_project' does not include header 'GCDAsyncSocket.h'
</code>```

This is my framework header:

```<code>#import <UIKit/UIKit.h>

//! Project version number for my_project.
FOUNDATION_EXPORT double my_projectVersionNumber;

//! Project version string for my_project.
FOUNDATION_EXPORT const unsigned char my_projectVersionString[];

// In this header, you should import all the public headers of your framework
using statements like #import <my_project/PublicHeader.h>
#import <CocoaAsyncSocket/CocoaAsyncSocket.h>
</code>```

As you can see CocoaAsyncSocket.h is imported. Furthermore inside my framework the CocoaAsyncSocket.h file is included:

What I am missing here? I'm using several others external frameworks inside my framework, there're no warnings for them - all of these external frameworks are written in Swift - CocoaAsyncSocket is pure Objective-C.

This is my frameworks module.modulemap:

```<code> framework module my_project {
   umbrella header "my_project.h"

   export *
   module * { export * }
 }

 module viewer_protocol.Swift {
     header "my_project-Swift.h"
 }
</code>```

Update

I found a solution: Changing the import statement in my framework header from

```<code>#import <CocoaAsyncSocket/CocoaAsyncSocket.h>
</code>```

to

```<code>#import "CocoaAsyncSocket/CocoaAsyncSocket.h"
</code>```

Now Xcode finds the header file and the warning disappears.

答:
Take a look at this post:

@import vs #import - iOS 7

It goes over the concepts of the new module importing.
I had my own custom framework and after adopting the new method to import objective-c framework

old:
#import <MyFramework/MyFramework.h>

new:
@import MyFramework;

it took care of the warning/

Body:
My Swift / iOS9 framework 'viewer_protocol' uses another and external Objective-C framework (CocoaAsyncSocket). I'm using Carthage to build CocoaAsyncSocket. So far everything works fine: In have an example App inside my framework Xcode Project using my framework without any problems.

Now I want to use my Framework in a different Xcode Project - although using Carthage. I include only my Framework as a dependency and Carthage automatically resolves the dependencies to CocoaAsyncSocket. I embedded both frameworks into this new Xcode Project and build my App: Everything works fine here - except one warning I can't rid off:

/Users/John/Repositories/my_project/<module-includes>:1:1:
Umbrella header for module 'my_project' does not include header 'GCDAsyncSocket.h'

This is my framework header:

#import <UIKit/UIKit.h>

//! Project version number for my_project.
FOUNDATION_EXPORT double my_projectVersionNumber;

//! Project version string for my_project.
FOUNDATION_EXPORT const unsigned char my_projectVersionString[];

// In this header, you should import all the public headers of your framework
using statements like #import <my_project/PublicHeader.h>
#import <CocoaAsyncSocket/CocoaAsyncSocket.h>

As you can see CocoaAsyncSocket.h is imported. Furthermore inside my framework the CocoaAsyncSocket.h file is included:

What I am missing here? I'm using several others external frameworks inside my framework, there're no warnings for them - all of these external frameworks are written in Swift - CocoaAsyncSocket is pure Objective-C.

This is my frameworks module.modulemap:

 framework module my_project {
   umbrella header "my_project.h"

   export *
   module * { export * }
 }

 module viewer_protocol.Swift {
     header "my_project-Swift.h"
 }

Update

I found a solution: Changing the import statement in my framework header from

#import <CocoaAsyncSocket/CocoaAsyncSocket.h>

to

#import "CocoaAsyncSocket/CocoaAsyncSocket.h"

Now Xcode finds the header file and the warning disappears.


答:
I had a similar scenario arise where I wanted to be able to specify dynamic filters like that. I ended up using the System.Linq.Dynamic.Core NuGet package to help (https://github.com/StefH/System.Linq.Dynamic.Core). This allows you to run Linq queries using string inputs. Then, rather than having to build a Linq expression tree from your Filter, you just need to construct a where clause as a string.

```<code>public class Filter
{
    public List<FilterEntry> Inclusions { get; set; }
    public List<FilterEntry> Exclusions { get; set; }

    public IQueryable<User> ApplyTo<User>(IQueryable<User> queryable)
    {
        // TODO: Dynamically build this string instead of hard-coding it.
        //       You would probably iterate through Inclusions and Exclusions
        //       appending to the where clause as you go.
        var whereClause = "Age == @0 && Name != @1 && Name != @2";
        var params = new object[] { 33, "John", "Peter" };

        return queryable.Where(whereClause, params);
    }
}
</code>```

I realise this isn't a working solution, but hopefully it at least gives you a place to start.

Title: Complex query with filters in Entity Framework Core

Body:
I had a similar scenario arise where I wanted to be able to specify dynamic filters like that. I ended up using the System.Linq.Dynamic.Core NuGet package to help (https://github.com/StefH/System.Linq.Dynamic.Core). This allows you to run Linq queries using string inputs. Then, rather than having to build a Linq expression tree from your Filter, you just need to construct a where clause as a string.

public class Filter
{
    public List<FilterEntry> Inclusions { get; set; }
    public List<FilterEntry> Exclusions { get; set; }

    public IQueryable<User> ApplyTo<User>(IQueryable<User> queryable)
    {
        // TODO: Dynamically build this string instead of hard-coding it.
        //       You would probably iterate through Inclusions and Exclusions
        //       appending to the where clause as you go.
        var whereClause = "Age == @0 && Name != @1 && Name != @2";
        var params = new object[] { 33, "John", "Peter" };

        return queryable.Where(whereClause, params);
    }
}

I realise this isn't a working solution, but hopefully it at least gives you a place to start.


问:
Tensorflow lite example with custom model - "input_product_scale < output_scale was not true"
How to reproduce:

retrain a mobilenet with command:

```<code>python tensorflow/tensorflow/examples/image_retraining/retrain.py
—image_dir (data-pwd)
—learning_rate=0.001 —testing_percentage=20
—validation_percentage=20 —train_batch_size=32
—validation_batch_size=-1 —flip_left_right True
—random_scale=30 —random_brightness=30
—eval_step_interval=100 —how_many_training_steps=200
—architecture mobilenet_1.0_224_quantized —default_ranges_min=0
—default_ranges_max=6 —std_values=224
—mean_values=224
</code>```

mean values and std_values don't really make a difference - tried different combinations.

then I converted the resulting .pb file like so:

```<code>bazel-bin/tensorflow/contrib/lite/toco/toco --input_file=(path)/output_graph.pb --input_format=TENSORFLOW_GRAPHDEF
--output_format=TFLITE
--output_file=./mobilenet_quantized_224.tflite --inference_type=QUANTIZED_UINT8
--input_type=QUANTIZED_UINT8 --input_array=Placeholder --output_array=final_result
--input_shape=1,224,224,3
--output_array=final_result --input_shape=1,224,224,3
</code>```

Then I've replaced in both stock apps: iOS simple and Android camera example app the tflite model with the generated one. This leads both to the same error:

Error:

Android:

```<code>Can not allocate memory for the given inputs:
tensorflow/contrib/lite/kernels/kernel_util.cc:34
input_product_scale < output_scale was not true.
</code>```

iOS:

```<code>/Library/Developer/CoreSimulator/Devices/10888914-22EB-4CA7-B019-F95D5A8A6F5C/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles

nnapi error: unable to open library libneuralnetworks.so
Loaded model resolved reportertensorflow/contrib/lite/kernels
/kernel_util.cc:34 input_product_scale < output_scale was not
true.Failed to allocate tensors!(lldb)
</code>```

Question:

How to solve... error? :)

Edit as I'm adding a bounty:
The goal would be to get an explanation on how to retrain a model and get it running with tensorflow lite. I'm aware this is very new, but I'm running left and right into errors with the docs.

答:
Does the following not work for you?

bazel-bin/tensorflow/contrib/lite/toco/toco --input_file=(path)/output_graph.pb --input_format=TENSORFLOW_GRAPHDEF --output_format=TFLITE --output_file=./mobilenet_quantized_224.tflite --inference_type=QUANTIZED_UINT8 --input_type=QUANTIZED_UINT8 --input_array=Placeholder --output_array=final_result --input_shape=1,224,224,3 --mean_values=128 --std_values=128 --default_ranges_min=0 --default_ranges_max=6

I've reproduced the error you are seeing and was able to get it to work with the following commands:

```<code>python tensorflow/tensorflow/examples/image_retraining/retrain.py \
  --image_dir /tmp/flower_photos \
  --learning_rate=0.001 \
  --testing_percentage=20 \
  --validation_percentage=20 \
  --train_batch_size=32 \
  --validation_batch_size=-1 \
  --flip_left_right True \
  --random_scale=30 \
  --random_brightness=30 \
  --eval_step_interval=100 \
  --how_many_training_steps=200 \
  --architecture mobilenet_1.0_224_quantized
</code>```

and

```<code>bazel-bin/tensorflow/contrib/lite/toco/toco \
  --input_file=/tmp/output_graph.pb \
  --input_format=TENSORFLOW_GRAPHDEF \
  --output_format=TFLITE \
  --output_file=/tmp/mobilenet_quantized_224.tflite \
  --inference_type=QUANTIZED_UINT8 \
  --input_type=QUANTIZED_UINT8 \
  --input_array=Placeholder \
  --output_array=final_result \
  --input_shape=1,224,224,3 \
  --mean_value=128 \
  --std_value=128 \
  --default_ranges_min=0 \
  --default_ranges_max=6
</code>```

Let me know if that works for you.

Body:
How to reproduce:

retrain a mobilenet with command:

python tensorflow/tensorflow/examples/image_retraining/retrain.py
—image_dir (data-pwd)
—learning_rate=0.001 —testing_percentage=20
—validation_percentage=20 —train_batch_size=32
—validation_batch_size=-1 —flip_left_right True
—random_scale=30 —random_brightness=30
—eval_step_interval=100 —how_many_training_steps=200
—architecture mobilenet_1.0_224_quantized —default_ranges_min=0
—default_ranges_max=6 —std_values=224
—mean_values=224

mean values and std_values don't really make a difference - tried different combinations.

then I converted the resulting .pb file like so:

bazel-bin/tensorflow/contrib/lite/toco/toco --input_file=(path)/output_graph.pb --input_format=TENSORFLOW_GRAPHDEF
--output_format=TFLITE
--output_file=./mobilenet_quantized_224.tflite --inference_type=QUANTIZED_UINT8
--input_type=QUANTIZED_UINT8 --input_array=Placeholder --output_array=final_result
--input_shape=1,224,224,3
--output_array=final_result --input_shape=1,224,224,3

Then I've replaced in both stock apps: iOS simple and Android camera example app the tflite model with the generated one. This leads both to the same error:

Error:

Android:

Can not allocate memory for the given inputs:
tensorflow/contrib/lite/kernels/kernel_util.cc:34
input_product_scale < output_scale was not true.

iOS:

/Library/Developer/CoreSimulator/Devices/10888914-22EB-4CA7-B019-F95D5A8A6F5C/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles

nnapi error: unable to open library libneuralnetworks.so
Loaded model resolved reportertensorflow/contrib/lite/kernels
/kernel_util.cc:34 input_product_scale < output_scale was not
true.Failed to allocate tensors!(lldb)

Question:

How to solve... error? :)

Edit as I'm adding a bounty:
The goal would be to get an explanation on how to retrain a model and get it running with tensorflow lite. I'm aware this is very new, but I'm running left and right into errors with the docs.

Body:
Does the following not work for you?

bazel-bin/tensorflow/contrib/lite/toco/toco --input_file=(path)/output_graph.pb --input_format=TENSORFLOW_GRAPHDEF --output_format=TFLITE --output_file=./mobilenet_quantized_224.tflite --inference_type=QUANTIZED_UINT8 --input_type=QUANTIZED_UINT8 --input_array=Placeholder --output_array=final_result --input_shape=1,224,224,3 --mean_values=128 --std_values=128 --default_ranges_min=0 --default_ranges_max=6

I've reproduced the error you are seeing and was able to get it to work with the following commands:

python tensorflow/tensorflow/examples/image_retraining/retrain.py \
  --image_dir /tmp/flower_photos \
  --learning_rate=0.001 \
  --testing_percentage=20 \
  --validation_percentage=20 \
  --train_batch_size=32 \
  --validation_batch_size=-1 \
  --flip_left_right True \
  --random_scale=30 \
  --random_brightness=30 \
  --eval_step_interval=100 \
  --how_many_training_steps=200 \
  --architecture mobilenet_1.0_224_quantized

and

bazel-bin/tensorflow/contrib/lite/toco/toco \
  --input_file=/tmp/output_graph.pb \
  --input_format=TENSORFLOW_GRAPHDEF \
  --output_format=TFLITE \
  --output_file=/tmp/mobilenet_quantized_224.tflite \
  --inference_type=QUANTIZED_UINT8 \
  --input_type=QUANTIZED_UINT8 \
  --input_array=Placeholder \
  --output_array=final_result \
  --input_shape=1,224,224,3 \
  --mean_value=128 \
  --std_value=128 \
  --default_ranges_min=0 \
  --default_ranges_max=6

Let me know if that works for you.


问:
Call of Overloaded Functions is Ambiguous
I'm getting the error call of overloaded function is ambiguous and I understand it's because the compiler can't differentiate between them, but is there a way to work around this while maintaining the same parameters? I have to use the declarations I've provided below and it's confusing me as to how I can use them both if I met with this error every time.

I've shortened my code to show the constructors that are posing the issue.

ErrorMessage.h

```<code>class ErrorMessage {
        char* message_; //pointer that holds the address of the message stored in current object
    public:
        ErrorMessage();
        explicit ErrorMessage(const char* errorMessage = nullptr); //receive address of a C-style nullterminate string holding an error message
}
</code>```

ErrorMessage.cpp

namespace sict {

```<code>ErrorMessage::ErrorMessage() {
    message_ = nullptr;
}

ErrorMessage::ErrorMessage(const char* errorMessage) {
    if(errorMessage == nullptr) {
        message_ = nullptr;
    }
    else {
        message(errorMessage);
    }
    const char* ErrorMessage::message() const {
        return message_;
    }
}
</code>```

答:
Just remove the constructor which takes no parameters. The second constructor already does everything the first constructor does.

If it receives a nullptr, it tests it and sets the local variable, if not it continues with its logic. The first constructor is completely superfluous.

Body:
I'm getting the error call of overloaded function is ambiguous and I understand it's because the compiler can't differentiate between them, but is there a way to work around this while maintaining the same parameters? I have to use the declarations I've provided below and it's confusing me as to how I can use them both if I met with this error every time.

I've shortened my code to show the constructors that are posing the issue.

ErrorMessage.h

class ErrorMessage {
        char* message_; //pointer that holds the address of the message stored in current object
    public:
        ErrorMessage();
        explicit ErrorMessage(const char* errorMessage = nullptr); //receive address of a C-style nullterminate string holding an error message
}

ErrorMessage.cpp

namespace sict {

ErrorMessage::ErrorMessage() {
    message_ = nullptr;
}

ErrorMessage::ErrorMessage(const char* errorMessage) {
    if(errorMessage == nullptr) {
        message_ = nullptr;
    }
    else {
        message(errorMessage);
    }
    const char* ErrorMessage::message() const {
        return message_;
    }
}


问:
Regex to remove word from XSLT
I need help writing regex to remove a word using XSLT.

I need to change the output of my XML file's "detailpath" from:

/events/262/26207

...to simply:

262/26207

The XSL is:

```<code><xsl:value-of select="detailpath"/>
</code>```

How can I remove "/events/"?

Thanks in advance.

答:
Another XPath 1.0 solution (assuming there is only one instance of the string to replace) that would work regardless of where the text fragment is in the string:</p>

```<code><xsl:value-of select="concat(substring-before(detailpath,'/events/'),
                             substring-after(detailpath,'/events/'))" />
</code>```

Title: Regex to remove word from XSLT

Body:
I need help writing regex to remove a word using XSLT.

I need to change the output of my XML file's "detailpath" from:

/events/262/26207

...to simply:

262/26207

The XSL is:

<xsl:value-of select="detailpath"/>

How can I remove "/events/"?

Thanks in advance.

Body:
Another XPath 1.0 solution (assuming there is only one instance of the string to replace) that would work regardless of where the text fragment is in the string:

<xsl:value-of select="concat(substring-before(detailpath,'/events/'),
                             substring-after(detailpath,'/events/'))" />


问:
Where to put bin, include and lib directories from virtual environment into development repository?
I have a Django project which I've been running on a local virtual environment, here's how the root directory looks (draft1 is my app). I'm now ready to push this project to a repo so I can start to develop it on a public server - so my question is - where do the bin, include and lib directories go? How do they translate from local development to when using a public server?

答: You shouldn't ship with your dependencies, just ship with the requirements.txt, and make sure you run pip install -r requirements.txt in a virtual env in server everytime you deploy.


问:
Spring JPA Auditing empty createdBy
I am using the auditing capabilities of Spring Data and have a class similar to this:

```
@Entity
@Audited
@EntityListeners(AuditingEntityListener.class)
@Table(name="Student")
public class Student {
    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    private Long id;

    @CreatedBy
    private String createdBy;

    @CreatedDate
    private Date createdDate;

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    private Date lastModifiedDate;
...
```

Now, I believe I have configured auditing fine because I can see that createdBy, createdDate, lastModifiedBy and lastModifiedDate all are getting the correct values when I update the domain objects.

However, my problem is that when I update an object I am losing the values of createdBy and createdDate. So, when I first create the object I have all four values, but when I update it createdBy and createdDate are nullified ! I am also using the Hibernate envers to keep a history of the domain objects.

Do you know why do I get this behavior ? Why do createdBy and createdDate are empty when I update the domain object  ?

Update: To answer @m-deinum 's questions: Yes spring data JPA is configured correctly - everything else works fine - I really wouldn't like to post the configuration because as you udnerstand it will need a lot of space.

My AuditorAwareImpl is this

```
@Component
public class AuditorAwareImpl implements AuditorAware {
    Logger logger = Logger.getLogger(AuditorAwareImpl.class);

    @Autowired
    ProfileService profileService;

    @Override
    public String getCurrentAuditor() {
        return profileService.getMyUsername();
    }
}
```

Finally, here's my update controller implementation:

```
    @Autowired
    private StudentFormValidator validator;
    @Autowired
    private StudentRepository studentRep;

@RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
public String updateFromForm(
         @PathVariable("id")Long id,
         @Valid Student student, BindingResult result,
         final RedirectAttributes redirectAttributes)   {

     Student s =  studentRep.secureFind(id);
     if(student == null || s == null) {
         throw new ResourceNotFoundException();
     }
     validator.validate(student, result);
     if (result.hasErrors()) {
         return "students/form";
     }
     student.setId(id);
     student.setSchool(profileService.getMySchool());
     redirectAttributes.addFlashAttribute("message", "Επιτυχής προσθήκη!");
     studentRep.save(student);
     return "redirect:/students/list";
}
```

Update 2: Please take a look at a newer version

```
@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
     public ModelAndView editForm(@PathVariable("id")Long id)  {
         ModelAndView mav = new ModelAndView("students/form");
         Student student =  studentRep.secureFind(id);
         if(student == null) {
             throw new ResourceNotFoundException();
         }
         mav.getModelMap().addAttribute(student);
         mav.getModelMap().addAttribute("genders", GenderEnum.values());
         mav.getModelMap().addAttribute("studentTypes", StudEnum.values());
         return mav;
     }

     @RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
     public String updateFromForm(
             @PathVariable("id")Long id,
             @Valid @ModelAttribute Student student, BindingResult result,
             final RedirectAttributes redirectAttributes, SessionStatus status)   {

         Student s =  studentRep.secureFind(id);
         if(student == null || s == null) {
             throw new ResourceNotFoundException();
         }

         if (result.hasErrors()) {
             return "students/form";
         }
         //student.setId(id);
         student.setSchool(profileService.getMySchool());
         studentRep.save(student);
         redirectAttributes.addFlashAttribute("message", "Επιτυχής προσθήκη!");
         status.setComplete();
         return "redirect:/students/list";
     }
```

This still leaves empty the createdBy and createdDate fields when I do an update :(

Also it does not get the School value (which is not contained in my form because it is related to the user currently editing) so I need to get it again from the SecurityContext... Have I done anything wrong ?

Update 3: For reference and to not miss it in the comments: The main problem was that I needed to include the @SessionAttributes annotation to my controller.

答:
Use updatable attribute of @Column annotation like below.

```<code>@Column(name = "created_date", updatable = false)
private Date createdDate;
</code>```

This will retain the created date on update operation.

Title: Spring JPA Auditing empty createdBy

Body:
I am using the auditing capabilities of Spring Data and have a class similar to this:

@Entity
@Audited
@EntityListeners(AuditingEntityListener.class)
@Table(name="Student")
public class Student {
    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    private Long id;

    @CreatedBy
    private String createdBy;

    @CreatedDate
    private Date createdDate;

    @LastModifiedBy
    private String lastModifiedBy;

    @LastModifiedDate
    private Date lastModifiedDate;
...

Now, I believe I have configured auditing fine because I can see that createdBy, createdDate, lastModifiedBy and lastModifiedDate all are getting the correct values when I update the domain objects.

However, my problem is that when I update an object I am losing the values of createdBy and createdDate. So, when I first create the object I have all four values, but when I update it createdBy and createdDate are nullified ! I am also using the Hibernate envers to keep a history of the domain objects.

Do you know why do I get this behavior ? Why do createdBy and createdDate are empty when I update the domain object  ?

Update: To answer @m-deinum 's questions: Yes spring data JPA is configured correctly - everything else works fine - I really wouldn't like to post the configuration because as you udnerstand it will need a lot of space.

My AuditorAwareImpl is this

@Component
public class AuditorAwareImpl implements AuditorAware {
    Logger logger = Logger.getLogger(AuditorAwareImpl.class);

    @Autowired
    ProfileService profileService;

    @Override
    public String getCurrentAuditor() {
        return profileService.getMyUsername();
    }
}

Finally, here's my update controller implementation:

    @Autowired
    private StudentFormValidator validator;
    @Autowired
    private StudentRepository studentRep;

@RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
public String updateFromForm(
         @PathVariable("id")Long id,
         @Valid Student student, BindingResult result,
         final RedirectAttributes redirectAttributes)   {

     Student s =  studentRep.secureFind(id);
     if(student == null || s == null) {
         throw new ResourceNotFoundException();
     }
     validator.validate(student, result);
     if (result.hasErrors()) {
         return "students/form";
     }
     student.setId(id);
     student.setSchool(profileService.getMySchool());
     redirectAttributes.addFlashAttribute("message", "Επιτυχής προσθήκη!");
     studentRep.save(student);
     return "redirect:/students/list";
}

Update 2: Please take a look at a newer version

@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
     public ModelAndView editForm(@PathVariable("id")Long id)  {
         ModelAndView mav = new ModelAndView("students/form");
         Student student =  studentRep.secureFind(id);
         if(student == null) {
             throw new ResourceNotFoundException();
         }
         mav.getModelMap().addAttribute(student);
         mav.getModelMap().addAttribute("genders", GenderEnum.values());
         mav.getModelMap().addAttribute("studentTypes", StudEnum.values());
         return mav;
     }

     @RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
     public String updateFromForm(
             @PathVariable("id")Long id,
             @Valid @ModelAttribute Student student, BindingResult result,
             final RedirectAttributes redirectAttributes, SessionStatus status)   {

         Student s =  studentRep.secureFind(id);
         if(student == null || s == null) {
             throw new ResourceNotFoundException();
         }

         if (result.hasErrors()) {
             return "students/form";
         }
         //student.setId(id);
         student.setSchool(profileService.getMySchool());
         studentRep.save(student);
         redirectAttributes.addFlashAttribute("message", "Επιτυχής προσθήκη!");
         status.setComplete();
         return "redirect:/students/list";
     }

This still leaves empty the createdBy and createdDate fields when I do an update :(

Also it does not get the School value (which is not contained in my form because it is related to the user currently editing) so I need to get it again from the SecurityContext... Have I done anything wrong ?

Update 3: For reference and to not miss it in the comments: The main problem was that I needed to include the @SessionAttributes annotation to my controller.

Body:
Use updatable attribute of @Column annotation like below.

@Column(name = "created_date", updatable = false)
private Date createdDate;

This will retain the created date on update operation.


问:
Wordpress: how to call a plugin function with an ajax call?
I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function.

I'm stuck with the ajax query. I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin?

(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.)

I've got my code[1] set up as follows:

mu-plugins/sample.php:

```<code><?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
  class SamplePlugin {
    function SamplePlugin() {}
    function addHeaderCode() {
      echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
             '/wp-content/mu-plugins/sample/sample.css" />\n';
      wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
             '/wp-content/mu-plugins/sample/sample-ajax.js.php',
             array('jquery'), '1.0');

    }
    // adds the link to post content.
    function addLink($content = '') {
        $content .= "<span class='foobar clicked'><a href='#'>click</a></span>";
        return $content;
    }
    function doAjax() { //
        echo "<a href='#'>AJAX!</a>";
    }
  }
}
if (class_exists("SamplePlugin")) {
  $sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
  add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
  add_filter('the_content', array(&$sample_plugin, 'addLink'));
}
</code>```

mu-plugins/sample/sample-ajax.js.php:

```<code><?php
if (!function_exists('add_action')) {
    require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
    jQuery(".foobar").bind("click", function() {
        var aref = this;
        jQuery(this).toggleClass('clicked');
        jQuery.ajax({
          url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
          success: function(value) {
            jQuery(aref).html(value);
          }
        });
    });
});
</code>```

mu-plugins/sample/sample-ajax.php:

```<code><?php
if (!function_exists('add_action')) {
  require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
  $sample_plugin->doAjax();
} else {
  echo "unset";
}
?>
</code>```

[1] Note: The following tutorial got me this far, but I'm stumped at this point.
http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin

答:
Just to add an information.
If you want to receive an object from a php class method function :

js file

```<code>jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
    var data = {
        'action': 'getAllOptionsByAjax',
        'arg1': 'val1',
        'arg2': $(this).val()
    };
    jQuery.post( ajaxurl, data, function(response) {
       var jsonObj = JSON.parse( response );
    });
});
</code>```

php file

```<code>public static function getAllOptionsByAjax(){

    global $wpdb;

    // Start query string
    $query_string  =  "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";

    // Return results
    $a_options = $wpdb->get_results( $query_string, ARRAY_A );
    $f_options = array();
    $f_options[null] =  __( 'Please select an item', 'my_domain' );
    foreach ($a_options as $option){
        $f_options [$option['id']] = $option['name'];
    }
    $json = json_encode( $f_options );
    echo $json;
    wp_die();
}
</code>```

Body:
I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function.

I'm stuck with the ajax query. I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin?

(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.)

I've got my code[1] set up as follows:

mu-plugins/sample.php:

<?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
  class SamplePlugin {
    function SamplePlugin() {}
    function addHeaderCode() {
      echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
             '/wp-content/mu-plugins/sample/sample.css" />\n';
      wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
             '/wp-content/mu-plugins/sample/sample-ajax.js.php',
             array('jquery'), '1.0');

    }
    // adds the link to post content.
    function addLink($content = '') {
        $content .= "click";
        return $content;
    }
    function doAjax() { //
        echo "AJAX!";
    }
  }
}
if (class_exists("SamplePlugin")) {
  $sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
  add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
  add_filter('the_content', array(&$sample_plugin, 'addLink'));
}

mu-plugins/sample/sample-ajax.js.php:

<?php
if (!function_exists('add_action')) {
    require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
    jQuery(".foobar").bind("click", function() {
        var aref = this;
        jQuery(this).toggleClass('clicked');
        jQuery.ajax({
          url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
          success: function(value) {
            jQuery(aref).html(value);
          }
        });
    });
});

mu-plugins/sample/sample-ajax.php:

<?php
if (!function_exists('add_action')) {
  require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
  $sample_plugin->doAjax();
} else {
  echo "unset";
}
?>

[1] Note: The following tutorial got me this far, but I'm stumped at this point.
http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin

Body:
Just to add an information.
If you want to receive an object from a php class method function :

js file

jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
    var data = {
        'action': 'getAllOptionsByAjax',
        'arg1': 'val1',
        'arg2': $(this).val()
    };
    jQuery.post( ajaxurl, data, function(response) {
       var jsonObj = JSON.parse( response );
    });
});

php file

public static function getAllOptionsByAjax(){

    global $wpdb;

    // Start query string
    $query_string  =  "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";

    // Return results
    $a_options = $wpdb->get_results( $query_string, ARRAY_A );
    $f_options = array();
    $f_options[null] =  __( 'Please select an item', 'my_domain' );
    foreach ($a_options as $option){
        $f_options [$option['id']] = $option['name'];
    }
    $json = json_encode( $f_options );
    echo $json;
    wp_die();
}


问:
Mocking HttpClient in unit tests
I have some issues trying to wrap my code to be used in unit tests. The issues is this. I have the interface IHttpHandler:

```<code>public interface IHttpHandler
{
    HttpClient client { get; }
}
</code>```

And the class using it, HttpHandler:

```<code>public class HttpHandler : IHttpHandler
{
    public HttpClient client
    {
        get
        {
            return new HttpClient();
        }
    }
}
</code>```

And then the Connection class, which uses simpleIOC to inject the client implementation:

```<code>public class Connection
{
    private IHttpHandler _httpClient;

    public Connection(IHttpHandler httpClient)
    {
        _httpClient = httpClient;
    }
}
</code>```

And then I have a unit test project which has this class:

```<code>private IHttpHandler _httpClient;

[TestMethod]
public void TestMockConnection()
{
    var client = new Connection(_httpClient);

    client.doSomething();

    // Here I want to somehow create a mock instance of the http client
    // Instead of the real one. How Should I approach this?

}
</code>```

Now obviously I will have methods in the Connection class that will retrieve data (JSON) from my backend. However, I want to write unit tests for this class, and obviously I don't want to write tests against the real back end, rather a mocked one. I have tried to google a good answer to this without great success. I can and have used Moq to mock before, but never on something like HttpClient. How should I approach this problem?

答:
One alternative would be to setup a stub HTTP server that returns canned responses based on pattern matching the request url, meaning you test real HTTP requests not mocks. Historically this would have taken significant develoment effort and would have been far to slow to be considered for unit testing, however OSS library WireMock.net is easy to use and fast enough to be run with lots of tests so may be worth considering. Setup is a few lines of code:

```<code>var server = FluentMockServer.Start();
server.Given(
      Request.Create()
      .WithPath("/some/thing").UsingGet()
   )
   .RespondWith(
       Response.Create()
       .WithStatusCode(200)
       .WithHeader("Content-Type", "application/json")
       .WithBody("{'attr':'value'}")
   );
</code>```

You can find a more details and guidance on using wiremock in tests here.

Title: Mocking HttpClient in unit tests

Body:
I have some issues trying to wrap my code to be used in unit tests. The issues is this. I have the interface IHttpHandler:

public interface IHttpHandler
{
    HttpClient client { get; }
}

And the class using it, HttpHandler:

public class HttpHandler : IHttpHandler
{
    public HttpClient client
    {
        get
        {
            return new HttpClient();
        }
    }
}

And then the Connection class, which uses simpleIOC to inject the client implementation:

public class Connection
{
    private IHttpHandler _httpClient;

    public Connection(IHttpHandler httpClient)
    {
        _httpClient = httpClient;
    }
}

And then I have a unit test project which has this class:

private IHttpHandler _httpClient;

[TestMethod]
public void TestMockConnection()
{
    var client = new Connection(_httpClient);

    client.doSomething();

    // Here I want to somehow create a mock instance of the http client
    // Instead of the real one. How Should I approach this?

}

Now obviously I will have methods in the Connection class that will retrieve data (JSON) from my backend. However, I want to write unit tests for this class, and obviously I don't want to write tests against the real back end, rather a mocked one. I have tried to google a good answer to this without great success. I can and have used Moq to mock before, but never on something like HttpClient. How should I approach this problem?

Body:
One alternative would be to setup a stub HTTP server that returns canned responses based on pattern matching the request url, meaning you test real HTTP requests not mocks. Historically this would have taken significant develoment effort and would have been far to slow to be considered for unit testing, however OSS library WireMock.net is easy to use and fast enough to be run with lots of tests so may be worth considering. Setup is a few lines of code:

var server = FluentMockServer.Start();
server.Given(
      Request.Create()
      .WithPath("/some/thing").UsingGet()
   )
   .RespondWith(
       Response.Create()
       .WithStatusCode(200)
       .WithHeader("Content-Type", "application/json")
       .WithBody("{'attr':'value'}")
   );

You can find a more details and guidance on using wiremock in tests here.


问:
Regular expression to extract specific part of a URL
I have a vector of URLs and need to extract a certain part of it. I've tried using a regex tester to see if my attempts worked, but they were no good.

The URLs I have are in this format: https://www.baseball-reference.com/teams/MIL/1976.shtml

I ned to extract the three letters after "teams/" (so for the example above, I need "MIL")

Does anyone have any idea how to get the correct regular expression to get this working? Thanks.

答:
Consider using the stringr package to simplify your code when handling strings.

Use a regular expression with positive lookbehind to catch alphanumeric codes following the string "teams\":

```<code>stringr::str_extract(url, "(?<=teams\\/)[A-Z]*")
</code>```

In your case, if the URLs literally all begin with the same string https://www.baseball-reference.com/teams/ then you can avoid regex entirely and use a simple substring to get the three-letter code which follows:

```<code>stringr::str_sub(url, 42, 44)
</code>```

Here are the results:

```<code>> url <- "https://www.baseball-reference.com/teams/MIL/1976.shtml"
>
> stringr::str_extract(url, "(?<=teams\\/)[A-Z]*")
[1] "MIL"
>
> stringr::str_sub(url, 42, 44)
[1] "MIL"
</code>```

Body:
Consider using the stringr package to simplify your code when handling strings.

Use a regular expression with positive lookbehind to catch alphanumeric codes following the string "teams\":

stringr::str_extract(url, "(?<=teams\\/)[A-Z]*")

In your case, if the URLs literally all begin with the same string https://www.baseball-reference.com/teams/ then you can avoid regex entirely and use a simple substring to get the three-letter code which follows:

stringr::str_sub(url, 42, 44)

Here are the results:

> url <- "https://www.baseball-reference.com/teams/MIL/1976.shtml"
>
> stringr::str_extract(url, "(?<=teams\\/)[A-Z]*")
[1] "MIL"
>
> stringr::str_sub(url, 42, 44)
[1] "MIL"


问:
Twilio Java SDK 7.x in a Multi-Threaded environment:
The Twilio latest Java SDK 7.x uses Singleton method 'Twilio.init' for authorisation purpose, which is unsuitable for a multi-users web application.

Any idea to overcome this?

答:
Twilio developer evangelist here.

According to this answer on the Twilio Java GitHub issues you can use the library without setting the account SID and auth token using Twilio.init. Instead, you can create your own TwilioRestClient object and execute the API calls using it.

For example:

```<code>import com.twilio.rest.http.TwilioRestClient;
import com.twilio.rest.resource.api.v2010.account.Call;

TwilioRestClient client = new TwilioRestClient(accountSid, authToken);

Call call = Call.fetch('CAaaaaaaaaaaaaaaaaaaaaaaaaaaa').execute(client);
</code>```

Let me know if that helps at all.

Body:
Twilio developer evangelist here.

According to this answer on the Twilio Java GitHub issues you can use the library without setting the account SID and auth token using Twilio.init. Instead, you can create your own TwilioRestClient object and execute the API calls using it.

For example:

import com.twilio.rest.http.TwilioRestClient;
import com.twilio.rest.resource.api.v2010.account.Call;

TwilioRestClient client = new TwilioRestClient(accountSid, authToken);

Call call = Call.fetch('CAaaaaaaaaaaaaaaaaaaaaaaaaaaa').execute(client);

Let me know if that helps at all.


问:
Discard all changes in Github Desktop (Mac)
How to discard all changes in Github desktop (mac), comparing to the latest commit?

It is possible to click on one file and select "discard changes". But how to discard all changes in files?

答: Right click on any file and you'll find the option to 'Discard All Changes':