问:
log4j - Intercept logging created within a class/method
I have an App which has many ejb Timer methods which are fired at various intervals, in an attempt to log the performance of these scheduled tasks I have written two methods which log the start and end of every task and records some info such as name, running duration and log info each time the timer fires

The intention with log info was to intercept all logging statements raised from within these methods, output to a string and save...I am doing this by creating a new WriterAppender, appending to the Logger for all logging levels, then when the timer completes capture the string output and remove the appender

This works well but it seems to have 2 unwanted effects:

1) It is stopping any logging from the timer class appearing in our normal file appender logs, eg. the log messages are being captured but they now don't appear in our normal logs (which are configured to show everything > INFO

2) Logging statements from different timers which overlap are appearing in each other logs, I guess this is the result of the Logger working on a single thread, not sure if theres a way around this?

I am no expert in log4j so I am hoping someone can point out a simple fix for 1, 2 or both

Code below shows the 2 methods which are called at start and end of every job

```<code>private Writer w = new StringWriter();
private WriterAppender wa;
private Logger logOutput = Logger.getLogger(ScheduledActions.class);

private TimerEvent logStartTimerEvent(ScheduledTask task){

    RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
    TimerEvent event = new TimerEvent(task);

    //Initialise a new log appender to intercept all log4j entries
    w = new StringWriter();
    Layout l = new PatternLayout("%m%n");
    wa = new WriterAppender(l, w);
    wa.setEncoding("UTF-8");
    wa.setThreshold(Level.ALL);
    wa.activateOptions();

    // Add it to logger
    logOutput = Logger.getLogger(ScheduledActions.class);
    logOutput.addAppender(wa);

    //Push this timer event to redis
    redisActions.addToFixedLengthList(RedisItem.TIMER_HISTORY.getKey()+"_"+task.getName(), gson.toJson(event), 100L);

    return event;
}

private void logEndTimerEvent(TimerEvent event){

    try{

        RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
        event.setLogInfo(w.toString());
        event.setEndTime(new Date());
        redisActions.editLastMemberInList(RedisItem.TIMER_HISTORY.getKey()+"_"+event.getTask().getName(), gson.toJson(event));
        w.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        //clean up the temp log appender
        logOutput.removeAppender(wa);
        wa.close();

    }

}
</code>```

答:
I found this old question while trying to do something similar. For now, my solution is creating an independent logger/appender, with a unique loggerId, like:

```<code>var loggerId = operation.getId(); // This is a unique ID
var logger = (org.apache.logging.log4j.core.Logger) LogManager.getLogger(loggerId);
var appender = createAppender();
logger.addAppender(appender);

logger.info("using logger");

appender.stop();
logger.removeAppender(appender);
</code>```

The problem that I have is that I need to pass this logger variable around. I can't use the classic "static logger".

Body:
I have an App which has many ejb Timer methods which are fired at various intervals, in an attempt to log the performance of these scheduled tasks I have written two methods which log the start and end of every task and records some info such as name, running duration and log info each time the timer fires

The intention with log info was to intercept all logging statements raised from within these methods, output to a string and save...I am doing this by creating a new WriterAppender, appending to the Logger for all logging levels, then when the timer completes capture the string output and remove the appender

This works well but it seems to have 2 unwanted effects:

1) It is stopping any logging from the timer class appearing in our normal file appender logs, eg. the log messages are being captured but they now don't appear in our normal logs (which are configured to show everything > INFO

2) Logging statements from different timers which overlap are appearing in each other logs, I guess this is the result of the Logger working on a single thread, not sure if theres a way around this?

I am no expert in log4j so I am hoping someone can point out a simple fix for 1, 2 or both

Code below shows the 2 methods which are called at start and end of every job

private Writer w = new StringWriter();
private WriterAppender wa;
private Logger logOutput = Logger.getLogger(ScheduledActions.class);

private TimerEvent logStartTimerEvent(ScheduledTask task){

    RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
    TimerEvent event = new TimerEvent(task);

    //Initialise a new log appender to intercept all log4j entries
    w = new StringWriter();
    Layout l = new PatternLayout("%m%n");
    wa = new WriterAppender(l, w);
    wa.setEncoding("UTF-8");
    wa.setThreshold(Level.ALL);
    wa.activateOptions();

    // Add it to logger
    logOutput = Logger.getLogger(ScheduledActions.class);
    logOutput.addAppender(wa);

    //Push this timer event to redis
    redisActions.addToFixedLengthList(RedisItem.TIMER_HISTORY.getKey()+"_"+task.getName(), gson.toJson(event), 100L);

    return event;
}

private void logEndTimerEvent(TimerEvent event){

    try{

        RedisActions redisActions = (RedisActions)Component.getInstance("redisActions");
        event.setLogInfo(w.toString());
        event.setEndTime(new Date());
        redisActions.editLastMemberInList(RedisItem.TIMER_HISTORY.getKey()+"_"+event.getTask().getName(), gson.toJson(event));
        w.flush();

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        //clean up the temp log appender
        logOutput.removeAppender(wa);
        wa.close();

    }

}

Body:
I found this old question while trying to do something similar. For now, my solution is creating an independent logger/appender, with a unique loggerId, like:

var loggerId = operation.getId(); // This is a unique ID
var logger = (org.apache.logging.log4j.core.Logger) LogManager.getLogger(loggerId);
var appender = createAppender();
logger.addAppender(appender);

logger.info("using logger");

appender.stop();
logger.removeAppender(appender);

The problem that I have is that I need to pass this logger variable around. I can't use the classic "static logger".


来源: stackexchange

问:
GitHub Actions workflow triggered with files not stated in on.push.paths or on.pull_request.paths
```<code>name: Console
on:
  push:
    paths:
      - "services/console/**"
      - ".github/workflows/console.yaml"
  pull_request:
    paths:
      - "services/console/**"
      - ".github/workflows/console.yaml"
</code>```

We have the above in the following file: .github/workflows/console.yaml. We have other files in the source code, an example would be in services/example-service/**.

The problem I'm trying to fix or understand is the above workflow is triggered when files in the services/example-service are changed and pushed or is in a pull request. This shouldn't happen because that directory is not stated in the on push paths or on pull_request paths.

Here is the documentation for this: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#example-including-paths

Is there some scenario I've not thought of regarding this or would this be considered a bug?

The only thing I can see that it might be is this: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#git-diff-comparisons

Note: If you push more than 1,000 commits, or if GitHub does not
generate the diff due to a timeout, the workflow will always run.

Our code has thousands of commits, but we do not push thousands of new commits when updating.

答:
The reason was after contacting GitHub support was that pushes use two dot diffs while PRs use three dot diffs.

The two dot diff caused a trigger because we rebased the branch onto master which had changes to the directory stated and then we force pushed. This caused the diff between the new forced pushed branch and the immediate commit before on the branch to includes a hell of a lot of diffs, some of which were in the stated directroy.

ContentLicense: CC BY-SA 4.0

Body:
name: Console
on:
  push:
    paths:
      - "services/console/**"
      - ".github/workflows/console.yaml"
  pull_request:
    paths:
      - "services/console/**"
      - ".github/workflows/console.yaml"

We have the above in the following file: .github/workflows/console.yaml. We have other files in the source code, an example would be in services/example-service/**.

The problem I'm trying to fix or understand is the above workflow is triggered when files in the services/example-service are changed and pushed or is in a pull request. This shouldn't happen because that directory is not stated in the on push paths or on pull_request paths.

Here is the documentation for this: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#example-including-paths

Is there some scenario I've not thought of regarding this or would this be considered a bug?

The only thing I can see that it might be is this: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#git-diff-comparisons

Note: If you push more than 1,000 commits, or if GitHub does not
generate the diff due to a timeout, the workflow will always run.

Our code has thousands of commits, but we do not push thousands of new commits when updating.


问:
React native animation => new Animated.Value() with useState or not?
What is the best way to use Animated.Value () in react-native ?

With useState() or not ?

```<code>const [fadeAnim] = useState(new Animated.Value(0))
</code>```

Or

```<code>const fadeAnim = new Animated.Value(0)
</code>```

React-native doc: https://facebook.github.io/react-native/docs/animations

Thanks

答:
Use useRef() as recommended in https://reactnative.dev/docs/animated and https://reactnative.dev/docs/animations#animated-api.

const [fadeAnim] = useState(() => new Animated.Value(0)); is same but semantically "state" means getter and setter - without setter 'fadeAnim' will be same throughout the component's lifetime so no different than useRef(...).current

Body:
What is the best way to use Animated.Value () in react-native ?

With useState() or not ?

const [fadeAnim] = useState(new Animated.Value(0))

Or

const fadeAnim = new Animated.Value(0)

React-native doc: https://facebook.github.io/react-native/docs/animations

Thanks


问:
[PHP][MySQL]How To SELECT data with two constrain?
I'm new to PHP+MySQL programming

I want to SELCET data using tow constrain at once,

the cons1 is

```<code>Tid=user02 and Fid=user01
</code>```

and cons2 is

```<code>Tid=user01 and Fid=user02
</code>```

the data I want to output is something like:

```<code>$result1 = mysql_query("SELECT * FROM myTable WHERE Tid='user02' AND Fid='user01');
</code>```

+

```<code>$result2 = mysql_query("SELECT * FROM myTable WHERE Tid='user01' AND Fid='user02');
</code>```

= what I want

can it be done in single line?

or can make a result which stored $result1 and $result2

thanks for taking time reading my question

答:
```<code>$result1 = mysql_query("SELECT * FROM chat WHERE Tid='user02' AND Fid='user01' OR Tid='user01' AND Fid='user02'");
</code>```

Some reading : boolean algebra and the mysql doc

ContentLicense: CC BY-SA 3.0

Body:
I'm new to PHP+MySQL programming

I want to SELCET data using tow constrain at once,

the cons1 is

Tid=user02 and Fid=user01

and cons2 is

Tid=user01 and Fid=user02

the data I want to output is something like:

$result1 = mysql_query("SELECT * FROM myTable WHERE Tid='user02' AND Fid='user01');

+

$result2 = mysql_query("SELECT * FROM myTable WHERE Tid='user01' AND Fid='user02');

= what I want

can it be done in single line?

or can make a result which stored $result1 and $result2

thanks for taking time reading my question

Body:
$result1 = mysql_query("SELECT * FROM chat WHERE Tid='user02' AND Fid='user01' OR Tid='user01' AND Fid='user02'");

Some reading : boolean algebra and the mysql doc


问:
Cypher query returning no matches no records in neo4j
I am building a reccomendation search query in cypher
I have produced the following:

```<code>LOAD CSV WITH HEADERS FROM "file:///restaurant_data.csv" AS data
MERGE(n1:Customer{Name:data.Name, Latitude:toFloat(data.Latitude),Longitude:toFloat(data.Longitude)})
MERGE(n2:Orders{OrderId:data.Order_ID,OrderTimestamp:data.Order_ts,FoodName:data.Food_Item})
MERGE(n3:Restaurant{RestaurantName:data.Restaurant, RestLat:toFloat(data.Rest_lat), RestLong:toFloat(data.Rest_long)})
MERGE (n1)-[r1:PLACES_ORDER]->(n2)
MERGE (n2)-[r2:BELONGS_TO]->(n3)
MERGE (n3)-[r3:SERVES]->(n2)
RETURN *;

MATCH(n1:Customer{Name:"Angy"})-[:PLACES_ORDER]->(n2:Orders)<-[:SERVES]-(r:Restaurant)
WITH n2 ORDER BY n2.OrderTimestamp DESC LIMIT 5
WITH collect(distinct n2) as orders
MATCH (r:Restaurant) WHERE ALL(order in orders WHERE EXISTS((r)-[:SERVES]->(order)))
RETURN DISTINCT r.RestaurantName
</code>```

I want to find the last 5 orders of ANGY and give her recommendations of restaurants serving that order. However the above query returns no matches no records
Where am I going wrong? Please help!!! I AM NEW TO NEO4J

答:
```<code>MATCH(:Customer{Name:"Angy"})-[:PLACES_ORDER]->(o:Orders)
WITH o ORDER BY o.OrderTimestamp DESC LIMIT 5
WITH [o.FoodName] as foods
MATCH (r:Restaurant)-[:SERVES]->(n:Orders)
WHERE (n.FoodName in foods)
RETURN distinct r.RestaurantName,foods
</code>```

Finnally this worked for me.

Body:
I am building a reccomendation search query in cypher
I have produced the following:

LOAD CSV WITH HEADERS FROM "file:///restaurant_data.csv" AS data
MERGE(n1:Customer{Name:data.Name, Latitude:toFloat(data.Latitude),Longitude:toFloat(data.Longitude)})
MERGE(n2:Orders{OrderId:data.Order_ID,OrderTimestamp:data.Order_ts,FoodName:data.Food_Item})
MERGE(n3:Restaurant{RestaurantName:data.Restaurant, RestLat:toFloat(data.Rest_lat), RestLong:toFloat(data.Rest_long)})
MERGE (n1)-[r1:PLACES_ORDER]->(n2)
MERGE (n2)-[r2:BELONGS_TO]->(n3)
MERGE (n3)-[r3:SERVES]->(n2)
RETURN *;

MATCH(n1:Customer{Name:"Angy"})-[:PLACES_ORDER]->(n2:Orders)<-[:SERVES]-(r:Restaurant)
WITH n2 ORDER BY n2.OrderTimestamp DESC LIMIT 5
WITH collect(distinct n2) as orders
MATCH (r:Restaurant) WHERE ALL(order in orders WHERE EXISTS((r)-[:SERVES]->(order)))
RETURN DISTINCT r.RestaurantName

I want to find the last 5 orders of ANGY and give her recommendations of restaurants serving that order. However the above query returns no matches no records
Where am I going wrong? Please help!!! I AM NEW TO NEO4J

Body:
MATCH(:Customer{Name:"Angy"})-[:PLACES_ORDER]->(o:Orders)
WITH o ORDER BY o.OrderTimestamp DESC LIMIT 5
WITH [o.FoodName] as foods
MATCH (r:Restaurant)-[:SERVES]->(n:Orders)
WHERE (n.FoodName in foods)
RETURN distinct r.RestaurantName,foods

Finnally this worked for me.


问:
"dotnet ef migrations add" replaces \r\n with \n when calling on mac/linux
I've got a repeatable issue with creating new migrations with dotnet ef cli tool. I work on a project with developers mainly using windows and I with no major problems work on MacOS and Linux.
We have fluent entity configuration with some data seeding using .HasData() method

```<code> builder.HasData(new SomeType
        {
            NameEn = @"multi
                        line string"
        });
</code>```

when migration is then created on Windows it produces migration files with "\r\n" for every encounter of new line, but then when any migration is created on mac/linux system it catches it as a change and produces migrationBuilder.UpdateData entries with "\r\n" being replaced with just "\n". And on the windows with next migration it is again caught and converted back to "\r\n".

It makes no difference for successful applying of the migration to the DB, but it successfully obfuscates the git diff result and makes it harder to review. Unnecessary updates I don't need to mention...

Does anybody encountered such an issue? Any solutions to it? I could not find any reported issue on this and it seems to me that it's not so rare that people on the team work on different systems.

I use "Entity Framework Core .NET Command-line Tools 6.0.0"

Thanks in advance for any help

答:
Ran in to this recently as well, not sure why it's not a breaking change listed in the documentation. To the best we can tell, EF Core is now adding the line endings to multi-line strings in seed data based on the native file system at the time of the migration. As you've found, this creates the ping pong situation with multi-environment teams since git normalizes the line endings in your working directory.

When upgrading to EF Core 6, you'll most likely get a lot of changes to the snapshot on your first migration no matter what, as the migration will include the strings with their line endings. But you can avoid the continued back and forth, as well as the actual UpdateData call within a migration, with:

A .gitattributes file to force the file your seed data strings are in to respect a CRLF, or LF setting, no matter the environment. Read more here.

You can use git ls-files --eol left column results to determine the line endings of your files as they're already checked in, so you know which to pick to make it the easiest.

If you're bringing in data from a file, or otherwise reading it somehow, manually put specific line endings in the string as part of that read. You can also use the .gitattributes method here on the data files so the line endings are consistent.

Body:
I've got a repeatable issue with creating new migrations with dotnet ef cli tool. I work on a project with developers mainly using windows and I with no major problems work on MacOS and Linux.
We have fluent entity configuration with some data seeding using .HasData() method

 builder.HasData(new SomeType
        {
            NameEn = @"multi
                        line string"
        });

when migration is then created on Windows it produces migration files with "\r\n" for every encounter of new line, but then when any migration is created on mac/linux system it catches it as a change and produces migrationBuilder.UpdateData entries with "\r\n" being replaced with just "\n". And on the windows with next migration it is again caught and converted back to "\r\n".

It makes no difference for successful applying of the migration to the DB, but it successfully obfuscates the git diff result and makes it harder to review. Unnecessary updates I don't need to mention...

Does anybody encountered such an issue? Any solutions to it? I could not find any reported issue on this and it seems to me that it's not so rare that people on the team work on different systems.

I use "Entity Framework Core .NET Command-line Tools 6.0.0"

Thanks in advance for any help


问:
VBA webResponse Response.data getting error when changing type from "Dictionary" to "collection"
Here is the problem : I have the following code

```<code>Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse

Dim responseData As Scripting.Dictionary

Request.UserAgent = VBA.Environ("USERNAME")
Request.AddHeader "AuthToken", m_token
Request.AddHeader "APIKey", m_key
Request.Method = WebMethod.HttpPost

Dim Auth As New HttpBasicAuthenticator
Auth.Setup "username", "Password"
Set Client.Authenticator = Auth

Dim Body As New Dictionary
If condition1 Then
        Body.Add "status", "open"
Else
        Body.Add "status", "closed"
End If

Client.BaseUrl = server_api & "Tasks/" & m_id

Set Request.Body = Body
Set Response = Client.Execute(Request)

If (Response.StatusCode = Ok) Then
        Debug.Print TypeName(Response.Data) 'returns Dictionary
        Set responseData = Response.Data '.Item(1)
        Debug.Print "ID: " & responseData("id")
        Debug.Print "message: " & responseData("message")
End If
</code>```

The request is executed with success, the program has no errors, and the Response.data has the typename Dictionary, but message is :

'statut' doesn't exist in table

So I tried to fix this by changing the "status" name to the required "tableColunm" which have int32 as type in the database.

The changes applied are in the following code with results on comments:

```<code>    If condition1 Then
        Body.Add "tableColunm", 1 'I tried also with "1"
    Else
        Body.Add "tableColunm", 2 ' I tried also with "2"
    End If        Client.BaseUrl = server_api & "Tasks/" & m_id

    Set Request.Body = Body
    Set Response = Client.Execute(Request)

    If (Response.StatusCode = Ok) Then
        Debug.Print TypeName(Response.Data) 'returns Collection
        Set responseData = Response.Data '.Item(1) ' error here, and the program crashed
        Debug.Print "ID: " & responseData("id")
        Debug.Print "message: " & responseData("message")
    End If
</code>```

Now the typename of Response.data is collection, and I think this is the reason why the program crashes

Any help ? Thanks

答:
Finally, after adding this

```<code>For Each elt In Response.Data
    Debug.Print TypeName(elt)
Next
</code>```

The loop is executed only one time, outputting Dictionary. That's mean that in the second case, the dictionary is encapsulated on a collection

So I worked with elt and this solves my problem

Body:
Here is the problem : I have the following code

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse

Dim responseData As Scripting.Dictionary

Request.UserAgent = VBA.Environ("USERNAME")
Request.AddHeader "AuthToken", m_token
Request.AddHeader "APIKey", m_key
Request.Method = WebMethod.HttpPost

Dim Auth As New HttpBasicAuthenticator
Auth.Setup "username", "Password"
Set Client.Authenticator = Auth

Dim Body As New Dictionary
If condition1 Then
        Body.Add "status", "open"
Else
        Body.Add "status", "closed"
End If

Client.BaseUrl = server_api & "Tasks/" & m_id

Set Request.Body = Body
Set Response = Client.Execute(Request)

If (Response.StatusCode = Ok) Then
        Debug.Print TypeName(Response.Data) 'returns Dictionary
        Set responseData = Response.Data '.Item(1)
        Debug.Print "ID: " & responseData("id")
        Debug.Print "message: " & responseData("message")
End If

The request is executed with success, the program has no errors, and the Response.data has the typename Dictionary, but message is :

'statut' doesn't exist in table

So I tried to fix this by changing the "status" name to the required "tableColunm" which have int32 as type in the database.

The changes applied are in the following code with results on comments:

    If condition1 Then
        Body.Add "tableColunm", 1 'I tried also with "1"
    Else
        Body.Add "tableColunm", 2 ' I tried also with "2"
    End If        Client.BaseUrl = server_api & "Tasks/" & m_id

    Set Request.Body = Body
    Set Response = Client.Execute(Request)

    If (Response.StatusCode = Ok) Then
        Debug.Print TypeName(Response.Data) 'returns Collection
        Set responseData = Response.Data '.Item(1) ' error here, and the program crashed
        Debug.Print "ID: " & responseData("id")
        Debug.Print "message: " & responseData("message")
    End If

Now the typename of Response.data is collection, and I think this is the reason why the program crashes

Any help ? Thanks

Body:
Finally, after adding this

For Each elt In Response.Data
    Debug.Print TypeName(elt)
Next

The loop is executed only one time, outputting Dictionary. That's mean that in the second case, the dictionary is encapsulated on a collection

So I worked with elt and this solves my problem


问:
Keyup prevent default not working angular6
I want to stop entering any number after validating a custom regular expression , the issue is condition got true but event.preventDefault is not preventing the input , The reg ex is to input value in percentage between 1-100 with decimals

```<code>/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/
</code>```

this is my input

```<code><input  type='text' (keyup)="preventPercentage($event)"  [(ngModel)]="value">
</code>```

ts

```<code>preventPercentage(event){
  var p = event.target.value
  var s= p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/)  != null
  if(!s && p){
    event.preventDefault();
  }
}
</code>```

user can still enter any value even  the condition is true
input anything between 100 above it still working and event is not preventing values

```<code>  <input  type='text' (keydown)="preventPercentage($event)"  [(ngModel)]="value">
</code>```

I used key down but it allows to enter 123 i.e three digit numbers
and I cannot then remove that number using backspace what exactly I am doing wrong can anyone suggest a sol any help will be appreciated

答:
This is because it's necessary to use keydown event, not keyup.

It considers that the keyboard action is already done and you cannot cancel it.

Body:
I want to stop entering any number after validating a custom regular expression , the issue is condition got true but event.preventDefault is not preventing the input , The reg ex is to input value in percentage between 1-100 with decimals

/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/

this is my input

<input  type='text' (keyup)="preventPercentage($event)"  [(ngModel)]="value">

ts

preventPercentage(event){
  var p = event.target.value
  var s= p.match(/^(100(\.0{1,2})?|[1-9]?\d(\.\d{1,2})?)$/)  != null
  if(!s && p){
    event.preventDefault();
  }
}

user can still enter any value even  the condition is true
input anything between 100 above it still working and event is not preventing values

  <input  type='text' (keydown)="preventPercentage($event)"  [(ngModel)]="value">

I used key down but it allows to enter 123 i.e three digit numbers
and I cannot then remove that number using backspace what exactly I am doing wrong can anyone suggest a sol any help will be appreciated


问:
Updating table in Access from Excel VBA
I have two tables in an Excel file which I need to import to Access and I have found a way that works perfectly for that, the problem is that it only works the first time (to import the table when this one does not exist in Access) but when I make changes to the Excel file and try this method again, it does not update the records and basically does nothing.

Both the table in Excel and in Access are called "Messungen" and "Grundinformation", respectively. This is the implemented code for the module called ExcelImport:

```<code>Public Sub ImportExcelSpreadsheet(fileName As String, tableName As String)

    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Messungen", _
     fileName, True, "Messung!"

    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Grundinformation", _
     fileName, True, "Grundinformation!"

    Exit Sub

End Sub
</code>```

I have made also the following objects. The first one to browse and select the file from a folder:

```<code>Private Sub btnBrowse_Click()
    Dim diag As Office.FileDialog
    Dim item As Variant

    Set diag = Application.FileDialog(msoFileDialogFilePicker)
    diag.AllowMultiSelect = False
    diag.Title = "Bitte die Excel Datei 'DB_Access_Daten' wählen "
    diag.Filters.Clear
    diag.Filters.Add "Excel Spreadsheets", "*.xls, *.xlsx, *.xlsm"

    If diag.Show Then

        For Each item In diag.SelectedItems
            Me.ExcelDatei = item

        Next
    End If

End Sub
</code>```

And this one to import the table using a button:

```<code>Private Sub btnImportTabelle_Click()
    Dim FSO As New FileSystemObject

    If Nz(Me.ExcelDatei, "") = "" Then
        MsgBox "Bitte eine Datei auswählen"
        Exit Sub
        End If

    If FSO.FileExists(Nz(Me.ExcelDatei, "")) Then
        ExcelImport.ImportExcelSpreadsheet Me.ExcelDatei, FSO.GetFileName(Me.ExcelDatei)

    Else
        MsgBox "File not found"

    End If

End Sub
</code>```

As mentioned before, this unfortunately is not working to update the values, just to import the table for the first time. I have thought of just linking the Database to the table in Excel but had some trouble with that since the excel file is in a shared network and my disk drive letter varies from the ones from my colleagues. I do not know then if maybe something is wrong with the code and how could I fix it.

Thank you for any help in advance!

答:
You should link the spreadsheets. Then run an update/append query as shown here:

Update and Append Records with One Query

Title: Updating table in Access from Excel VBA

Body:
I have two tables in an Excel file which I need to import to Access and I have found a way that works perfectly for that, the problem is that it only works the first time (to import the table when this one does not exist in Access) but when I make changes to the Excel file and try this method again, it does not update the records and basically does nothing.

Both the table in Excel and in Access are called "Messungen" and "Grundinformation", respectively. This is the implemented code for the module called ExcelImport:

Public Sub ImportExcelSpreadsheet(fileName As String, tableName As String)

    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Messungen", _
     fileName, True, "Messung!"

    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Grundinformation", _
     fileName, True, "Grundinformation!"

    Exit Sub

End Sub

I have made also the following objects. The first one to browse and select the file from a folder:

Private Sub btnBrowse_Click()
    Dim diag As Office.FileDialog
    Dim item As Variant

    Set diag = Application.FileDialog(msoFileDialogFilePicker)
    diag.AllowMultiSelect = False
    diag.Title = "Bitte die Excel Datei 'DB_Access_Daten' wählen "
    diag.Filters.Clear
    diag.Filters.Add "Excel Spreadsheets", "*.xls, *.xlsx, *.xlsm"

    If diag.Show Then

        For Each item In diag.SelectedItems
            Me.ExcelDatei = item

        Next
    End If

End Sub

And this one to import the table using a button:

Private Sub btnImportTabelle_Click()
    Dim FSO As New FileSystemObject

    If Nz(Me.ExcelDatei, "") = "" Then
        MsgBox "Bitte eine Datei auswählen"
        Exit Sub
        End If

    If FSO.FileExists(Nz(Me.ExcelDatei, "")) Then
        ExcelImport.ImportExcelSpreadsheet Me.ExcelDatei, FSO.GetFileName(Me.ExcelDatei)

    Else
        MsgBox "File not found"

    End If

End Sub

As mentioned before, this unfortunately is not working to update the values, just to import the table for the first time. I have thought of just linking the Database to the table in Excel but had some trouble with that since the excel file is in a shared network and my disk drive letter varies from the ones from my colleagues. I do not know then if maybe something is wrong with the code and how could I fix it.

Thank you for any help in advance!


问:
Trying to remove rows with zeros in Pandas, getting KeyError
I am pretty new to Python and Pandas in general, apologies for the noob question.

I am trying to sort out the values that I read from a csv file by removing the items with less than 0.01 in them. Unfortunately, I've been either getting KeyErrors all day, or the error is "TypeError: '>=' not supported between instances of 'str' and 'float'" and I'm at my wits end.

My code looks like this:

```<code>def get_aws_account_usage_charges(df):
    df_gb = df[['item_type', 'item_currency', 'item_description', 'item_price', 'item_quantity', 'charge_amount', 'item_amount']].groupby(['item_type', 'item_currency', 'item_description', 'item_price'], dropna=False).sum().reset_index()
    format_aud = lambda conv: '%.2f' % (conv['item_amount'])
    format_usd = lambda conv: '%.2f' % (conv['charge_amount'])
    df_gb['charges_aud'] = df_gb.apply(format_aud, axis=1)
    df_gb['charges_usd'] = df_gb.apply(format_usd, axis=1)

    print(df_gb['charges_aud'])

    return df_gb.sort_values(by='charge_amount', ascending=False)
</code>```

The return looks like this:

```<code>0      1.11
1     17.00
2      0.70
3      0.59
4      0.00
5      0.05
6      2.45
7      6.00
8      0.00
9      0.00
10     0.00
11     3.60
12     0.13
13     0.00
14     0.01
15     0.10
16     0.04
17     0.00
18     0.00
19     0.01
20     0.01
21     0.10
22     0.01
Name: charges_aud, dtype: object
</code>```

Any idea how I could remove the zeroes before I do my return, so when I do print(df_gb['charges_aud']), it'd look like this?

```<code>0      1.11
1     17.00
2      0.70
3      0.59
4      0.05
5      2.45
6      6.00
7      3.60
8      0.13
9      0.01
10     0.10
11     0.04
12     0.01
13     0.01
14     0.10
15     0.01
</code>```

答:
```<code>...
df_gb = df[['item_type', 'item_currency', 'item_description', 'item_price', 'item_quantity', 'charge_amount', 'item_amount']].groupby(['item_type', 'item_currency', 'item_description', 'item_price'], dropna=False).sum().reset_index()

df_gb = df_gb[df_gb.item_amount > 0]

format_aud = lambda conv: '%.2f' % (conv['item_amount'])
format_usd = lambda conv: '%.2f' % (conv['charge_amount'])
...
</code>```

Body:
I am pretty new to Python and Pandas in general, apologies for the noob question.

I am trying to sort out the values that I read from a csv file by removing the items with less than 0.01 in them. Unfortunately, I've been either getting KeyErrors all day, or the error is "TypeError: '>=' not supported between instances of 'str' and 'float'" and I'm at my wits end.

My code looks like this:

def get_aws_account_usage_charges(df):
    df_gb = df[['item_type', 'item_currency', 'item_description', 'item_price', 'item_quantity', 'charge_amount', 'item_amount']].groupby(['item_type', 'item_currency', 'item_description', 'item_price'], dropna=False).sum().reset_index()
    format_aud = lambda conv: '%.2f' % (conv['item_amount'])
    format_usd = lambda conv: '%.2f' % (conv['charge_amount'])
    df_gb['charges_aud'] = df_gb.apply(format_aud, axis=1)
    df_gb['charges_usd'] = df_gb.apply(format_usd, axis=1)

    print(df_gb['charges_aud'])

    return df_gb.sort_values(by='charge_amount', ascending=False)

The return looks like this:

0      1.11
1     17.00
2      0.70
3      0.59
4      0.00
5      0.05
6      2.45
7      6.00
8      0.00
9      0.00
10     0.00
11     3.60
12     0.13
13     0.00
14     0.01
15     0.10
16     0.04
17     0.00
18     0.00
19     0.01
20     0.01
21     0.10
22     0.01
Name: charges_aud, dtype: object

Any idea how I could remove the zeroes before I do my return, so when I do print(df_gb['charges_aud']), it'd look like this?

0      1.11
1     17.00
2      0.70
3      0.59
4      0.05
5      2.45
6      6.00
7      3.60
8      0.13
9      0.01
10     0.10
11     0.04
12     0.01
13     0.01
14     0.10
15     0.01


问:
Create Views Within ConstraintLayout programatically
I want to create a simple layout with 3 rows of the TextView elements. The first and the last row contain just one text view each and the middle row contains two adjacent text views.
Link to the Image

Here is the xml for generating the views

```<code>    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"

        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"

        app:layout_constraintBottom_toTopOf="@+id/textView4"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/textView4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />
</code>```

I am trying to re-create the same view programatically with the following code:

```<code>        val layout = findViewById<ConstraintLayout>(R.id.main)
        val cs = ConstraintSet()
        cs.clone(layout)

        val textViews: MutableList<TextView> = ArrayList<TextView>()
        for (i  in 1..4) {
            val t = TextView(this)
            t.id = View.generateViewId()
            t.text = "Text" + i.toString()
            layout.addView(t)
            textViews.add(t)
        }

        //Just make suffixes similar to the layout xml
        val t1 = textViews[0]
        val t2 = textViews[1]
        val t3 = textViews[2]
        val t4 = textViews[3]

//    app:layout_constraintBottom_toTopOf="@+id/textView2"
//    app:layout_constraintEnd_toEndOf="parent"
//    app:layout_constraintStart_toStartOf="parent"
//    app:layout_constraintTop_toTopOf="parent" />
        cs.connect(t1.id, ConstraintSet.BOTTOM, t2.id, ConstraintSet.TOP)
        cs.connect(t1.id, ConstraintSet.END, layout.id, ConstraintSet.END)
        cs.connect(t1.id, ConstraintSet.START, layout.id, ConstraintSet.START)
        cs.connect(t1.id, ConstraintSet.TOP, layout.id, ConstraintSet.TOP)

//    app:layout_constraintBottom_toTopOf="@+id/textView4"
//    app:layout_constraintEnd_toStartOf="@+id/textView3"
//    app:layout_constraintStart_toStartOf="parent"
//    app:layout_constraintTop_toBottomOf="@+id/textView" />
        cs.connect(t2.id, ConstraintSet.BOTTOM, t4.id, ConstraintSet.TOP)
        cs.connect(t2.id, ConstraintSet.END, t3.id, ConstraintSet.START)
        cs.connect(t2.id, ConstraintSet.START, layout.id, ConstraintSet.START)
        cs.connect(t2.id, ConstraintSet.TOP, t1.id, ConstraintSet.BOTTOM)

//    app:layout_constraintBottom_toTopOf="@+id/textView4"
//    app:layout_constraintEnd_toEndOf="parent"
//    app:layout_constraintStart_toEndOf="@+id/textView2"
//    app:layout_constraintTop_toBottomOf="@+id/textView" />
        cs.connect(t3.id, ConstraintSet.BOTTOM, t4.id, ConstraintSet.TOP)
        cs.connect(t3.id, ConstraintSet.END, layout.id, ConstraintSet.END)
        cs.connect(t3.id, ConstraintSet.START, t2.id, ConstraintSet.END)
        cs.connect(t3.id, ConstraintSet.TOP, t1.id, ConstraintSet.BOTTOM)

//    app:layout_constraintBottom_toBottomOf="parent"
//    app:layout_constraintEnd_toEndOf="parent"
//    app:layout_constraintStart_toStartOf="parent"
//    app:layout_constraintTop_toBottomOf="@+id/textView2" />
        cs.connect(t4.id, ConstraintSet.BOTTOM, layout.id, ConstraintSet.BOTTOM)
        cs.connect(t4.id, ConstraintSet.END, layout.id, ConstraintSet.END)
        cs.connect(t4.id, ConstraintSet.START, layout.id, ConstraintSet.START)
        cs.connect(t4.id, ConstraintSet.TOP, t2.id, ConstraintSet.BOTTOM)
</code>```

However this doesn't seem to work and all the text views are placed at the top-left corner of the display.

Could you please tell me how to make this piece of code work.

答: It is not enough just to clone the constraints and make the changes. The changes have to be applied to the ConstraintLayout using ConstraintSet#applyTo().

Body:
I want to create a simple layout with 3 rows of the TextView elements. The first and the last row contain just one text view each and the middle row contains two adjacent text views.
Link to the Image

Here is the xml for generating the views

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"

        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"

        app:layout_constraintBottom_toTopOf="@+id/textView4"
        app:layout_constraintEnd_toStartOf="@+id/textView3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/textView4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

I am trying to re-create the same view programatically with the following code:

        val layout = findViewById<ConstraintLayout>(R.id.main)
        val cs = ConstraintSet()
        cs.clone(layout)

        val textViews: MutableList<TextView> = ArrayList<TextView>()
        for (i  in 1..4) {
            val t = TextView(this)
            t.id = View.generateViewId()
            t.text = "Text" + i.toString()
            layout.addView(t)
            textViews.add(t)
        }

        //Just make suffixes similar to the layout xml
        val t1 = textViews[0]
        val t2 = textViews[1]
        val t3 = textViews[2]
        val t4 = textViews[3]

//    app:layout_constraintBottom_toTopOf="@+id/textView2"
//    app:layout_constraintEnd_toEndOf="parent"
//    app:layout_constraintStart_toStartOf="parent"
//    app:layout_constraintTop_toTopOf="parent" />
        cs.connect(t1.id, ConstraintSet.BOTTOM, t2.id, ConstraintSet.TOP)
        cs.connect(t1.id, ConstraintSet.END, layout.id, ConstraintSet.END)
        cs.connect(t1.id, ConstraintSet.START, layout.id, ConstraintSet.START)
        cs.connect(t1.id, ConstraintSet.TOP, layout.id, ConstraintSet.TOP)

//    app:layout_constraintBottom_toTopOf="@+id/textView4"
//    app:layout_constraintEnd_toStartOf="@+id/textView3"
//    app:layout_constraintStart_toStartOf="parent"
//    app:layout_constraintTop_toBottomOf="@+id/textView" />
        cs.connect(t2.id, ConstraintSet.BOTTOM, t4.id, ConstraintSet.TOP)
        cs.connect(t2.id, ConstraintSet.END, t3.id, ConstraintSet.START)
        cs.connect(t2.id, ConstraintSet.START, layout.id, ConstraintSet.START)
        cs.connect(t2.id, ConstraintSet.TOP, t1.id, ConstraintSet.BOTTOM)

//    app:layout_constraintBottom_toTopOf="@+id/textView4"
//    app:layout_constraintEnd_toEndOf="parent"
//    app:layout_constraintStart_toEndOf="@+id/textView2"
//    app:layout_constraintTop_toBottomOf="@+id/textView" />
        cs.connect(t3.id, ConstraintSet.BOTTOM, t4.id, ConstraintSet.TOP)
        cs.connect(t3.id, ConstraintSet.END, layout.id, ConstraintSet.END)
        cs.connect(t3.id, ConstraintSet.START, t2.id, ConstraintSet.END)
        cs.connect(t3.id, ConstraintSet.TOP, t1.id, ConstraintSet.BOTTOM)

//    app:layout_constraintBottom_toBottomOf="parent"
//    app:layout_constraintEnd_toEndOf="parent"
//    app:layout_constraintStart_toStartOf="parent"
//    app:layout_constraintTop_toBottomOf="@+id/textView2" />
        cs.connect(t4.id, ConstraintSet.BOTTOM, layout.id, ConstraintSet.BOTTOM)
        cs.connect(t4.id, ConstraintSet.END, layout.id, ConstraintSet.END)
        cs.connect(t4.id, ConstraintSet.START, layout.id, ConstraintSet.START)
        cs.connect(t4.id, ConstraintSet.TOP, t2.id, ConstraintSet.BOTTOM)

However this doesn't seem to work and all the text views are placed at the top-left corner of the display.

Could you please tell me how to make this piece of code work.


问:
Ruby - Constants DL and Fiddle is not defined
When I go to execute the rake db:create showing error Constants DL and Fiddle is not defined

I am using ruby 2.2.3. I think I have a problem with my rjb

rake aborted!

Constants DL and Fiddle is not defined.
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:62:in load'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:62:ininit'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:72:in block in <class:Railtie>'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:36:incall'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:36:in execute_hook'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:45:inblock in run_load_hooks'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:44:in each'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:44:inrun_load_hooks'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application/finisher.rb:62:in block in <module:Finisher>'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:30:ininstance_exec'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:30:in run'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:55:inblock in run_initializers'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:54:in run_initializers'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:352:ininitialize!'
/home/nibo/rails_workplace/ekylibre/config/environment.rb:5:in <top (required)>'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/skylight-1.3.1/lib/skylight/probes.rb:81:inrequire'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/skylight-1.3.1/lib/skylight/probes.rb:81:in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/polyglot-0.3.5/lib/polyglot.rb:65:inrequire'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:in block in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:240:inload_dependency'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:328:inrequire_environment!'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:457:in block in run_tasks_blocks'
/home/nibo/rails_workplace/ekylibre/lib/tasks/db/tenanting.rake:19:inblock in '
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rake-12.1.0/exe/rake:27:in <top (required)>'
/home/nibo/.rvm/gems/ruby-2.2.5/bin/ruby_executable_hooks:15:ineval'
/home/nibo/.rvm/gems/ruby-2.2.5/bin/ruby_executable_hooks:15:in '
LoadError: cannot load such file -- dl
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:62:inload'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:62:in init'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:72:inblock in '
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:36:in call'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:36:inexecute_hook'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:45:in block in run_load_hooks'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:44:ineach'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:44:in run_load_hooks'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application/finisher.rb:62:inblock in '
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:30:in instance_exec'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:30:inrun'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:55:in block in run_initializers'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:54:inrun_initializers'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:352:in initialize!'
/home/nibo/rails_workplace/ekylibre/config/environment.rb:5:in'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/skylight-1.3.1/lib/skylight/probes.rb:81:in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/skylight-1.3.1/lib/skylight/probes.rb:81:inrequire'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/polyglot-0.3.5/lib/polyglot.rb:65:in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:inblock in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:240:in load_dependency'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:inrequire'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:328:in require_environment!'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:457:inblock in run_tasks_blocks'
/home/nibo/rails_workplace/ekylibre/lib/tasks/db/tenanting.rake:19:in block in <top (required)>'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rake-12.1.0/exe/rake:27:in'
/home/nibo/.rvm/gems/ruby-2.2.5/bin/ruby_executable_hooks:15:in eval'
/home/nibo/.rvm/gems/ruby-2.2.5/bin/ruby_executable_hooks:15:in'
Fiddle::DLError: /usr/local/java/9-internal/jre/lib/amd64/server/libjvm.so: cannot open shared object file: No such file or directory
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:62:in load'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:62:ininit'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rjb-loader-0.0.2/lib/rjb-loader.rb:72:in block in <class:Railtie>'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:36:incall'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:36:in execute_hook'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:45:inblock in run_load_hooks'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:44:in each'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/lazy_load_hooks.rb:44:inrun_load_hooks'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application/finisher.rb:62:in block in <module:Finisher>'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:30:ininstance_exec'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:30:in run'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:55:inblock in run_initializers'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/initializable.rb:54:in run_initializers'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:352:ininitialize!'
/home/nibo/rails_workplace/ekylibre/config/environment.rb:5:in <top (required)>'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/skylight-1.3.1/lib/skylight/probes.rb:81:inrequire'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/skylight-1.3.1/lib/skylight/probes.rb:81:in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/polyglot-0.3.5/lib/polyglot.rb:65:inrequire'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:in block in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:240:inload_dependency'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.10/lib/active_support/dependencies.rb:274:in require'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:328:inrequire_environment!'
/home/nibo/.rvm/gems/ruby-2.2.5/gems/railties-4.2.10/lib/rails/application.rb:457:in block in run_tasks_blocks'
/home/nibo/rails_workplace/ekylibre/lib/tasks/db/tenanting.rake:19:inblock in '
/home/nibo/.rvm/gems/ruby-2.2.5/gems/rake-12.1.0/exe/rake:27:in <top (required)>'
/home/nibo/.rvm/gems/ruby-2.2.5/bin/ruby_executable_hooks:15:ineval'
/home/nibo/.rvm/gems/ruby-2.2.5/bin/ruby_executable_hooks:15:in `'

答:
I get this problem occasionally when updating Java, and it seems the cause is that the RJB folks haven't kept up with the new JDK layout.  In particular, RJB is relying on finding libjvm.so somewhere in $JAVA_HOME/jre but that's not been the case since Java 9 came out.

The only workaround I've found is to create a symbolic link to replicate the path that Ruby is expecting to find in the Java home directory.

This does the trick on my Linux machine (when run as root):

```<code>cd $JAVA_HOME
mkdir -p jre/lib/amd64
ln -s $JAVA_HOME/lib/server/ jre/lib/amd64/server
</code>```

Body:
I get this problem occasionally when updating Java, and it seems the cause is that the RJB folks haven't kept up with the new JDK layout.  In particular, RJB is relying on finding libjvm.so somewhere in $JAVA_HOME/jre but that's not been the case since Java 9 came out.

The only workaround I've found is to create a symbolic link to replicate the path that Ruby is expecting to find in the Java home directory.

This does the trick on my Linux machine (when run as root):

cd $JAVA_HOME
mkdir -p jre/lib/amd64
ln -s $JAVA_HOME/lib/server/ jre/lib/amd64/server


问:
Java aes encryption string to hex
I am using node forge package to encrypt and decrypt on my server , now I am  trying to encrypt data from my client app on android and want to send data back to my server in hex format but the below code is not working

```<code>val KEY_AES= "************"
val IV_AES= "************"
fun encrypat(value: String): String? {
    try {
        val key: ByteArray = KEY_AES.toByteArray()
        val ivs: ByteArray = IV_AES.toByteArray()
        val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
        val secretKeySpec = SecretKeySpec(key, "AES")
        val paramSpec: AlgorithmParameterSpec = IvParameterSpec(ivs)
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, paramSpec)
        return Hex.encodeHexString(cipher.doFinal(value.toByteArray(charset("UTF-8"))),true)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}
</code>```

error :java.lang.NoSuchMethodError: No static method encodeHexString([BZ)Ljava/lang/String; in class Lorg/apache/commons/codec/binary/Hex; or its super classes (declaration of 'org.apache.commons.codec.binary.Hex' appears in /system/framework/org.apache.http.legacy.jar)

答:
You are using the legacy version of apache.http.
But you should be able to get the same results with the available char[] encodeHex(byte[] data) method.

Title: Java aes encryption string to hex

Body:
I am using node forge package to encrypt and decrypt on my server , now I am  trying to encrypt data from my client app on android and want to send data back to my server in hex format but the below code is not working

val KEY_AES= "************"
val IV_AES= "************"
fun encrypat(value: String): String? {
    try {
        val key: ByteArray = KEY_AES.toByteArray()
        val ivs: ByteArray = IV_AES.toByteArray()
        val cipher = Cipher.getInstance("AES/CBC/PKCS7Padding")
        val secretKeySpec = SecretKeySpec(key, "AES")
        val paramSpec: AlgorithmParameterSpec = IvParameterSpec(ivs)
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, paramSpec)
        return Hex.encodeHexString(cipher.doFinal(value.toByteArray(charset("UTF-8"))),true)
    } catch (e: Exception) {
        e.printStackTrace()
    }
    return null
}

error :java.lang.NoSuchMethodError: No static method encodeHexString([BZ)Ljava/lang/String; in class Lorg/apache/commons/codec/binary/Hex; or its super classes (declaration of 'org.apache.commons.codec.binary.Hex' appears in /system/framework/org.apache.http.legacy.jar)


问:
Generate graph from a list of connected components

Setup

Let's assume the following undirected graph:

import networkx as nx

G = nx.from_edgelist([(0, 3), (0, 1), (2, 5), (0, 3)])
G.add_nodes_from(range(7))
```
<p><img src="https://i.stack.imgur.com/ZNfy5.png" alt="graph" /></p>
<p>or even adding the (1, 3) edge (it doesn't matter here):</p>
<p><img src="https://i.stack.imgur.com/ZFqk3.png" alt="enter image description here" /></p>
<p>The connected components are:</p>
<pre class="lang-py prettyprint-override"><code>list(nx.connected_components(G))
# [{0, 1, 3}, {2, 5}, {4}, {6}]
</code>```

Question

Is it possible to generate the graph G from the list of connected components directly with networkx? Or using a simple method?

The only solution I found so far is to generate the successive edges or all combinations of nodes per group and feed it to nx.from_edgelist, then to add the single nodes with add_nodes_from:

from itertools import pairwise, chain

l = [{0, 1, 3}, {2, 5}, {4}, {6}]

G = nx.from_edgelist(chain.from_iterable(pairwise(e) for e in l))
G.add_nodes_from(set.union(*l))
```
<p>or for all edges:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import combinations, chain

l = [{0, 1, 3}, {2, 5}, {4}, {6}]

G = nx.from_edgelist(chain.from_iterable(combinations(e, 2) for e in l))
G.add_nodes_from(set.union(*l))
</code>```

答:
An alternative to itertools.pairwise is networkx.path_graph.

An alternative to itertools.combinations is networkx.complete_graph.

These two networkx functions return a new graph, not a list of edges, so you can combine them with networkx.compose_all.

Note also union_all and disjoint_union_all as alternatives to compose_all.

import networkx as nx

l = [{0, 1, 3}, {2, 5}, {4}, {6}]

G = nx.compose_all(map(nx.path_graph, l))

H = nx.compose_all(map(nx.complete_graph, l))

print(G.nodes, G.edges)
# [0, 1, 3, 2, 5, 4, 6] [(0, 1), (1, 3), (2, 5)]

print(H.nodes, H.edges)
# [0, 1, 3, 2, 5, 4, 6] [(0, 1), (0, 3), (1, 3), (2, 5)]
```

I haven't actually run benchmarks, but I suspect creating several graphs and composing them might be slower than creating lists of edges and chaining them to create only one graph.

Body:
Setup

Let's assume the following undirected graph:

import networkx as nx

G = nx.from_edgelist([(0, 3), (0, 1), (2, 5), (0, 3)])
G.add_nodes_from(range(7))

or even adding the (1, 3) edge (it doesn't matter here):

The connected components are:

list(nx.connected_components(G))
# [{0, 1, 3}, {2, 5}, {4}, {6}]

Question

Is it possible to generate the graph G from the list of connected components directly with networkx? Or using a simple method?

The only solution I found so far is to generate the successive edges or all combinations of nodes per group and feed it to nx.from_edgelist, then to add the single nodes with add_nodes_from:

from itertools import pairwise, chain

l = [{0, 1, 3}, {2, 5}, {4}, {6}]

G = nx.from_edgelist(chain.from_iterable(pairwise(e) for e in l))
G.add_nodes_from(set.union(*l))

or for all edges:

from itertools import combinations, chain

l = [{0, 1, 3}, {2, 5}, {4}, {6}]

G = nx.from_edgelist(chain.from_iterable(combinations(e, 2) for e in l))
G.add_nodes_from(set.union(*l))

Body:
An alternative to itertools.pairwise is networkx.path_graph.

An alternative to itertools.combinations is networkx.complete_graph.

These two networkx functions return a new graph, not a list of edges, so you can combine them with networkx.compose_all.

Note also union_all and disjoint_union_all as alternatives to compose_all.

import networkx as nx

l = [{0, 1, 3}, {2, 5}, {4}, {6}]

G = nx.compose_all(map(nx.path_graph, l))

H = nx.compose_all(map(nx.complete_graph, l))

print(G.nodes, G.edges)
# [0, 1, 3, 2, 5, 4, 6] [(0, 1), (1, 3), (2, 5)]

print(H.nodes, H.edges)
# [0, 1, 3, 2, 5, 4, 6] [(0, 1), (0, 3), (1, 3), (2, 5)]

I haven't actually run benchmarks, but I suspect creating several graphs and composing them might be slower than creating lists of edges and chaining them to create only one graph.


问:
Spring Boot Application stuck at INFO [main] org.apache.catalina.startup.Catalina.start Server startup in [] milliseconds
I am trying to deploy a Spring Boot application in my local Tomcat server. (It has a very old Spring dependency so it needed to be ran as WAR in Tomcat)

I have excluded spring-boot-starter-tomcat from the pom.xml, and made the neccessary changes inside main class (extended SpringBootServletInitializer etc).
The Applications runs perfectly when i run it from IntellIJ as a Spring Boot App, but when i deploy it in my local environment (packaging war) it does not run at all.

It simply says that Server Startup at ... like the following image:

Any ideas what might be wrong ? (It doesnt even throw an error at all)

答: Your web-app has no error. Check your business logic processing in source code.</p>


问:
How to invoke external command from within Kotlin code?
I want to invoke an external command from Kotlin code.

In C/Perl, I would use the system() function.

In Python, I would use the subprocess module.

In Go, I would use os/exec, and etc.

But how do I do this in Kotlin?

答:
this worked for me, windows 10</p>
```<code>ProcessBuilder("cmd /C git status".split(" "))
        .redirectOutput(ProcessBuilder.Redirect.INHERIT)
        .start()
        .waitFor()
</code>```

Body:
this worked for me, windows 10

ProcessBuilder("cmd /C git status".split(" "))
        .redirectOutput(ProcessBuilder.Redirect.INHERIT)
        .start()
        .waitFor()


问:
How to make dictionary entry a pandas dataframe by specifying columns?
I have a dictionary like this:

```<code>mydict ={'9788845278518': [['/book/show/24235201-numero-zero', 'Italian'], ['/book/show/10522.Il_nome_della_rosa', 'Italian']]}
</code>```

And I would like to make it a dataframe like this:

```<code>ISBN, LINK, LANG
9788845278518, /book/show/24235201-numero-zero, Italian
9788845278518, /book/show/10522.Il_nome_della_rosa, Italian
</code>```

So I tried by doing:

```<code>df = pd.DataFrame.from_dict(mydict)
</code>```

And I wanted to use df.explode and then doing transpose, but it didn't really work because my column is not named. Also, there must be a simpler way to do it...

答:
Flatten the dictionary using list comprehension then create a new dataframe

```<code>df = pd.DataFrame(
    [(k, *l) for k, v in mydict.items() for l in v],
    columns=['ISBN', "LINK", 'LANG']
)
</code>```

```<code>print(df)
            ISBN                                 LINK     LANG
0  9788845278518      /book/show/24235201-numero-zero  Italian
1  9788845278518  /book/show/10522.Il_nome_della_rosa  Italian
</code>```

Body:
I have a dictionary like this:

mydict ={'9788845278518': [['/book/show/24235201-numero-zero', 'Italian'], ['/book/show/10522.Il_nome_della_rosa', 'Italian']]}

And I would like to make it a dataframe like this:

ISBN, LINK, LANG
9788845278518, /book/show/24235201-numero-zero, Italian
9788845278518, /book/show/10522.Il_nome_della_rosa, Italian

So I tried by doing:

df = pd.DataFrame.from_dict(mydict)

And I wanted to use df.explode and then doing transpose, but it didn't really work because my column is not named. Also, there must be a simpler way to do it...

Body:
Flatten the dictionary using list comprehension then create a new dataframe

df = pd.DataFrame(
    [(k, *l) for k, v in mydict.items() for l in v],
    columns=['ISBN', "LINK", 'LANG']
)

print(df)
            ISBN                                 LINK     LANG
0  9788845278518      /book/show/24235201-numero-zero  Italian
1  9788845278518  /book/show/10522.Il_nome_della_rosa  Italian


问:
Spring 3 MVC Handle multiple form submit with a single Controller
Spring 3 MVC Handle multiple form submit with a Controller.

I am developing JSP page with multiple forms. 1) Search Customer, 2) Search Product, 3) Print Something etc. I've a different form bind object tied to each form and my controller code looks similar to below

```<code>  @Controller
  @RequestMapping(value="/search.do")
  public class SearchController {

    @RequestMapping(method = RequestMethod.GET)
    public String pageLoad(ModelMap modelMap) {
      modelMap.addAttribute("productSearch", new ProductSearchCriteria());
        modelMap.addAttribute("customerSearch", new CustomerSearchCriteria());
        modelMap.addAttribute("print", new PrintForm());
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView searchProducts(@ModelAttribute("productSearch") ProductSearchCriteria productSearchCriteria,
            BindingResult result, SessionStatus status) {
            //Do Product search
            return modelAndView;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView searchCustomers(@ModelAttribute("customerSearch") CustomerSearchCriteria customerSearchCriteria,
            BindingResult result, SessionStatus status) {
            //Do Customer search
            return modelAndView;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView printSomething(@ModelAttribute("print") PrintForm printForm,
            BindingResult result, SessionStatus status) {
            //Print something
            return modelAndView;
    }
  }
</code>```

Above certainly doesn't work as I assumed it would. I get exception saying 'Request method 'POST' not supported'. If I have only one POST method inside above controller say searchProducts it works well. But it won't with more than one methods with POST. I also tried adding hidden parameter in JSP and changing method signatures similar to below only to get the same exception again.

```<code>  @RequestMapping(method = RequestMethod.POST, params="pageAction=searchProduct")
    public ModelAndView searchProducts(@ModelAttribute("productSearch") ProductSearchCriteria productSearchCriteria,
            BindingResult result, SessionStatus status) {
            //Do Product search
            return modelAndView;
   }
</code>```

Can anyone please suggest correct way to achieve above? Also any reference to source material or further reading will be greatly appreciated. Thanks.

EDIT #1: The above approach with params="pageAction=searchProduct" works perfectly as far as you get your hidden parameter right in JSP (see comment below). In addition to that, answers by @Bozho and @Biju Kunjummen is also very helpful and a good (possibly better?) alternative to tackle multiple form submit.

答:
I've had the same problem: two forms (register and contact) on the same page with two submit buttons.
Each form has its own validation by Spring.

I've managed to do this in one Controller:

```<code>@RequestMapping(value = "/contactOrRegister.do", method = RequestMethod.GET)
public void contactOrRegisterFormGet(@ModelAttribute("contactForm") ContactForm contactForm, @ModelAttribute("registerForm") RegisterForm registerForm) {
    //-----prepare forms for displaying here----
}

@RequestMapping(value = "/contact.do", method = RequestMethod.POST)
public String contactFormPost(@ModelAttribute("contactForm") ContactForm contactForm, BindingResult result, final Model model) {
    contactValidator.validate(contactForm, result);
    if (result.hasErrors()) {
        model.addAttribute("registerForm", new RegisterForm());
        return "contactOrRegister";
    }
    //--- validation is passed, do submit for contact form here ---
}

@RequestMapping(value = "/register.do", method = RequestMethod.POST)
public String registerFormPost(@ModelAttribute("registerForm") RegisterForm registerForm, BindingResult result, final Model model) {
    registerValidator.validate(registerForm, result);
    if (result.hasErrors()) {
        model.addAttribute("contactForm", new ContactForm());
        return "contactOrRegister";
    }
    //--- validation is passed, do submit for register form here ---
}
</code>```

I need to create a new form (contact or register) and put it in model when validation is failed because "contactOrRegister" view needs both forms to display. So when "contact" form was submitted and has errors the "register" form content will be erased. This way fits for me.

The contactOrRegister.jsp contains both forms with different action:

```<code> <form:form action="/register.do" modelAttribute="registerForm" method="POST">
    <!-- register form here -->
 </form:form>

 <form:form action="/contact.do" modelAttribute="contactForm" method="POST">
    <!-- contact form here -->
 </form:form>
</code>```

Body:
Spring 3 MVC Handle multiple form submit with a Controller.

I am developing JSP page with multiple forms. 1) Search Customer, 2) Search Product, 3) Print Something etc. I've a different form bind object tied to each form and my controller code looks similar to below

  @Controller
  @RequestMapping(value="/search.do")
  public class SearchController {

    @RequestMapping(method = RequestMethod.GET)
    public String pageLoad(ModelMap modelMap) {
      modelMap.addAttribute("productSearch", new ProductSearchCriteria());
        modelMap.addAttribute("customerSearch", new CustomerSearchCriteria());
        modelMap.addAttribute("print", new PrintForm());
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView searchProducts(@ModelAttribute("productSearch") ProductSearchCriteria productSearchCriteria,
            BindingResult result, SessionStatus status) {
            //Do Product search
            return modelAndView;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView searchCustomers(@ModelAttribute("customerSearch") CustomerSearchCriteria customerSearchCriteria,
            BindingResult result, SessionStatus status) {
            //Do Customer search
            return modelAndView;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView printSomething(@ModelAttribute("print") PrintForm printForm,
            BindingResult result, SessionStatus status) {
            //Print something
            return modelAndView;
    }
  }

Above certainly doesn't work as I assumed it would. I get exception saying 'Request method 'POST' not supported'. If I have only one POST method inside above controller say searchProducts it works well. But it won't with more than one methods with POST. I also tried adding hidden parameter in JSP and changing method signatures similar to below only to get the same exception again.

  @RequestMapping(method = RequestMethod.POST, params="pageAction=searchProduct")
    public ModelAndView searchProducts(@ModelAttribute("productSearch") ProductSearchCriteria productSearchCriteria,
            BindingResult result, SessionStatus status) {
            //Do Product search
            return modelAndView;
   }

Can anyone please suggest correct way to achieve above? Also any reference to source material or further reading will be greatly appreciated. Thanks.

EDIT #1: The above approach with params="pageAction=searchProduct" works perfectly as far as you get your hidden parameter right in JSP (see comment below). In addition to that, answers by @Bozho and @Biju Kunjummen is also very helpful and a good (possibly better?) alternative to tackle multiple form submit.

Body:
I've had the same problem: two forms (register and contact) on the same page with two submit buttons.
Each form has its own validation by Spring.

I've managed to do this in one Controller:

@RequestMapping(value = "/contactOrRegister.do", method = RequestMethod.GET)
public void contactOrRegisterFormGet(@ModelAttribute("contactForm") ContactForm contactForm, @ModelAttribute("registerForm") RegisterForm registerForm) {
    //-----prepare forms for displaying here----
}

@RequestMapping(value = "/contact.do", method = RequestMethod.POST)
public String contactFormPost(@ModelAttribute("contactForm") ContactForm contactForm, BindingResult result, final Model model) {
    contactValidator.validate(contactForm, result);
    if (result.hasErrors()) {
        model.addAttribute("registerForm", new RegisterForm());
        return "contactOrRegister";
    }
    //--- validation is passed, do submit for contact form here ---
}

@RequestMapping(value = "/register.do", method = RequestMethod.POST)
public String registerFormPost(@ModelAttribute("registerForm") RegisterForm registerForm, BindingResult result, final Model model) {
    registerValidator.validate(registerForm, result);
    if (result.hasErrors()) {
        model.addAttribute("contactForm", new ContactForm());
        return "contactOrRegister";
    }
    //--- validation is passed, do submit for register form here ---
}

I need to create a new form (contact or register) and put it in model when validation is failed because "contactOrRegister" view needs both forms to display. So when "contact" form was submitted and has errors the "register" form content will be erased. This way fits for me.

The contactOrRegister.jsp contains both forms with different action:

 <form:form action="/register.do" modelAttribute="registerForm" method="POST">
    <!-- register form here -->
 </form:form>

 <form:form action="/contact.do" modelAttribute="contactForm" method="POST">
    <!-- contact form here -->
 </form:form>


问:
How do I calculate tables size in Oracle
Being used to (and potentially spoiled by) MSSQL, I'm wondering how I can get at tables size in Oracle 10g.
I have googled it so I'm now aware that I may not have as easy an option as sp_spaceused. Still the potential answers I got are most of the time outdated or don't work. Probably because I'm no DBA on the schema I'm working with.

Would anyone have solutions and or recommendations?

答:
```<code>select segment_name as tablename, sum(bytes/ (1024 * 1024 * 1024)) as tablesize_in_GB
From dba_segments /* if looking at tables not owned by you else use user_segments */
where segment_name = 'TABLE_WHOSE_SIZE_I_WANT_TO_KNOW'
and   OWNER = 'WHO OWNS THAT TABLE' /* if user_segments is used delete this line */
group by segment_name ;
</code>```

OwnerDisplayName: Rollo Tomazzi


问:
Pandas dataframe: Check if regex contained in a column matches a string in another column in the same row
Input data is a Pandas dataframe:

```<code>df = pd.DataFrame()
df['strings'] = ['apple','house','hat','train','tan','note']
df['patterns'] = ['\\ba','\\ba','\\ba','n\\b','n\\b','n\\b']
df['group'] = ['1','1','1','2','2','2']

df

    strings patterns    group
0   apple   \ba         1
1   house   \ba         1
2   hat     \ba         1
3   train   n\b         2
4   tan     n\b         2
5   note    n\b         2

</code>```

The patterns column contains regex. \b is a regex pattern that matches on word boundaries. That means \ba would match with 'apple' because a is at the beginning of the word, while it would not match 'hat' because this a is in the middle of the word.

I want to use the regex in the patterns column to check if it matches with the strings column in the same row.

Desired result:

```<code>    strings patterns    group
0   apple   \ba         1
3   train   n\b         2
4   tan     n\b         2
</code>```

I got it to work below using re.search and a for loop that loops line by line. But this is very inefficient. I have millions of rows and this loop takes 5-10 minutes to run.

```<code>import re
for i in range(len(df)):
  pattern = df.at[i,"patterns"]
  test_string = df.at[i,"strings"]
  if re.search(pattern, test_string):
    df.at[i,'match'] = True
  else:
    df.at[i,'match'] = False

df.loc[df.match]
</code>```

Is there a way to do something like re.search(df['patterns'], df['strings'])?

This question appears to be similar: Python Pandas: Check if string in one column is contained in string of another column in the same row

However, the question and answers in the above link are not using regex to match, and I need to use regex to specify word boundaries.

答:
You can't use a pandas builtin method directly. You will need to apply a re.search per row:

```<code>import re

mask = df.apply(lambda r: bool(re.search(r['patterns'], r['strings'])), axis=1)
df2 = df[mask]
</code>```

or using a (faster) list comprehension:

```<code>mask = [bool(re.search(p,s)) for p,s in zip(df['patterns'], df['strings'])]
</code>```

output:

```<code>  strings patterns group
0   apple      \ba     1
3   train      n\b     2
4     tan      n\b     2
</code>```

Body:
Input data is a Pandas dataframe:

df = pd.DataFrame()
df['strings'] = ['apple','house','hat','train','tan','note']
df['patterns'] = ['\\ba','\\ba','\\ba','n\\b','n\\b','n\\b']
df['group'] = ['1','1','1','2','2','2']

df

    strings patterns    group
0   apple   \ba         1
1   house   \ba         1
2   hat     \ba         1
3   train   n\b         2
4   tan     n\b         2
5   note    n\b         2

The patterns column contains regex. \b is a regex pattern that matches on word boundaries. That means \ba would match with 'apple' because a is at the beginning of the word, while it would not match 'hat' because this a is in the middle of the word.

I want to use the regex in the patterns column to check if it matches with the strings column in the same row.

Desired result:

    strings patterns    group
0   apple   \ba         1
3   train   n\b         2
4   tan     n\b         2

I got it to work below using re.search and a for loop that loops line by line. But this is very inefficient. I have millions of rows and this loop takes 5-10 minutes to run.

import re
for i in range(len(df)):
  pattern = df.at[i,"patterns"]
  test_string = df.at[i,"strings"]
  if re.search(pattern, test_string):
    df.at[i,'match'] = True
  else:
    df.at[i,'match'] = False

df.loc[df.match]

Is there a way to do something like re.search(df['patterns'], df['strings'])?

This question appears to be similar: Python Pandas: Check if string in one column is contained in string of another column in the same row

However, the question and answers in the above link are not using regex to match, and I need to use regex to specify word boundaries.

Body:
You can't use a pandas builtin method directly. You will need to apply a re.search per row:

import re

mask = df.apply(lambda r: bool(re.search(r['patterns'], r['strings'])), axis=1)
df2 = df[mask]

or using a (faster) list comprehension:

mask = [bool(re.search(p,s)) for p,s in zip(df['patterns'], df['strings'])]

output:

  strings patterns group
0   apple      \ba     1
3   train      n\b     2
4     tan      n\b     2


问:
How to connecte to sql sever NET6 visual studio 2022 asp.net mvc project
i try to modify my local db connection (which works fine) in the appsettings.json :

```<code> "ApplicationDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=CateringMilano;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

with the sql server connection :

```<code> "ApplicationDbContextConnection": "Data Source=SQL5101.site4now.net;Initial Catalog=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

but when i run the project i got a strange error:

local host does  not exists..

and also

```<code>An unhandled exception occurred while processing the request.
</code>```

SqlException: Failed to generate SSPI context.
Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

and also i cannot see the sql server db in visual studio sql explorer..

What do i need to connect my website to my sql sever db?  what am i missing to do?

Thanks

答:
since you are using userid and password for your new server, replace

```<code>Trusted_Connection=True;
</code>```

with

```<code>Integrated Security=False;
</code>```

Body:
i try to modify my local db connection (which works fine) in the appsettings.json :

 "ApplicationDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=CateringMilano;Trusted_Connection=True;MultipleActiveResultSets=true"

with the sql server connection :

 "ApplicationDbContextConnection": "Data Source=SQL5101.site4now.net;Initial Catalog=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"

but when i run the project i got a strange error:

local host does  not exists..

and also

An unhandled exception occurred while processing the request.

SqlException: Failed to generate SSPI context.
Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

and also i cannot see the sql server db in visual studio sql explorer..

What do i need to connect my website to my sql sever db?  what am i missing to do?

Thanks

Body:
since you are using userid and password for your new server, replace

Trusted_Connection=True;

with

Integrated Security=False;


问:
SQL nesting BEGIN END Blocks gives SQL Error (102)
I'm getting the following error for this simple piece of SQL code. Any ideas why? Any BEGIN ... END block causes this error to occur

/* SQL Error (156): Incorrect syntax near the keyword 'END'. */

```<code>DECLARE @PROCESSEDCOUNT INT = 0
WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
    IF 1=1
    BEGIN
        -- Stuff happens here
    END
END
</code>```

This is running on SQL Server - MSSQL15

答:
You need more than a comment in a begin/end block.

Try the following

```<code>IF 1=1
    BEGIN
      SELECT @PROCESSEDCOUNT
    END
</code>```

Body:
I'm getting the following error for this simple piece of SQL code. Any ideas why? Any BEGIN ... END block causes this error to occur

/* SQL Error (156): Incorrect syntax near the keyword 'END'. */

DECLARE @PROCESSEDCOUNT INT = 0
WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
    IF 1=1
    BEGIN
        -- Stuff happens here
    END
END

This is running on SQL Server - MSSQL15

Body:
You need more than a comment in a begin/end block.

Try the following

IF 1=1
    BEGIN
      SELECT @PROCESSEDCOUNT
    END