问:
Remove bands below certain threshold in file
```<code>numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
  name = input("\nEnter the name of the band: ")
  votes = input("Enter how many votes that band received: ")
  file.write(name + "," + votes + "," + "\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))

def removebelowthreshold():
   threshold = int(input("Choose the threshold of scores to remove bands which are below"))

removebelowthreshold()
</code>```

The code will take and write a band's name and score to a file.

It should then remove the band's details in the file if their score is below a certain threshold given by the user. Hope you can help.

Thank you in advance

答:
Why should you first write the file, and only then try to filter it? File I/O operations are the more expensive ones in you logic, so you should minimize them. You should ask for the threshold before the other inputs, and then add a condition in you file writing loop:

```<code>threshold = int(input("Choose the threshold of scores to remove bands which are below"))

numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
    name = input("\nEnter the name of the band: ")
    votes = input("Enter how many votes that band received: ")
    if int(votes) >= threshold:
        file.write(name + "," + votes + ",\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))
</code>```

Obviously, there are multiple data type and range checks you would need to do to mke the program robust, but the basic logic is this.

Body:
numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
  name = input("\nEnter the name of the band: ")
  votes = input("Enter how many votes that band received: ")
  file.write(name + "," + votes + "," + "\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))

def removebelowthreshold():
   threshold = int(input("Choose the threshold of scores to remove bands which are below"))

removebelowthreshold()

The code will take and write a band's name and score to a file.

It should then remove the band's details in the file if their score is below a certain threshold given by the user. Hope you can help.

Thank you in advance

Body:
Why should you first write the file, and only then try to filter it? File I/O operations are the more expensive ones in you logic, so you should minimize them. You should ask for the threshold before the other inputs, and then add a condition in you file writing loop:

threshold = int(input("Choose the threshold of scores to remove bands which are below"))

numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
    name = input("\nEnter the name of the band: ")
    votes = input("Enter how many votes that band received: ")
    if int(votes) >= threshold:
        file.write(name + "," + votes + ",\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))

Obviously, there are multiple data type and range checks you would need to do to mke the program robust, but the basic logic is this.


来源: stackexchange

问:
How to set the background color of a swiftui to lightGray?
I am currently trying to set the background color of a text field in SwiftUI to light gray. it is not working

my code is this

TextField("Enter Your Email", text: $username)
    .background(Color.lightGray)
```

Any idea what could be wrong with it ? It works when i just use "gray" But i need the color to be lighter than that. I looked up lightGray in swift , and it says it is a color.

答: Can also use .background(Color(.systemGray6))

ContentLicense: CC BY-SA 4.0

Body:
I am currently trying to set the background color of a text field in SwiftUI to light gray. it is not working

my code is this

TextField("Enter Your Email", text: $username)
    .background(Color.lightGray)

Any idea what could be wrong with it ? It works when i just use "gray" But i need the color to be lighter than that. I looked up lightGray in swift , and it says it is a color.


问:
How to encode array elements in javascript?
How can I encode javascript arrays in url?

eg: The following is my query param

```<code>/query?colors=['red','blue','green',]
</code>```

expected output

```<code>%5B%27red%27%2C%27blue%27%2C%27green%27%2C%5D
</code>```

I've tried encodeURI and encodeURIComponent, but the comma is not getting transformed in to %2C.

UPDATE
I tried this

```<code>let colors = ['red','green']
encodeURIComponent(JSON.stringify(colors))
</code>```

colors=%255B%2522red%2522%252C%2522green%2522%255D.

But when I does so additional characters 25 is getting added. How Can I prevent that?

答:
Try URLSearchParams

let urlSearch = new URLSearchParams()
urlSearch.set("colors",JSON.stringify(['red','blue','green']))
console.log("/query?"+urlSearch.toString())```

Body:
How can I encode javascript arrays in url?

eg: The following is my query param

/query?colors=['red','blue','green',]

expected output

%5B%27red%27%2C%27blue%27%2C%27green%27%2C%5D

I've tried encodeURI and encodeURIComponent, but the comma is not getting transformed in to %2C.

UPDATE
I tried this

let colors = ['red','green']
encodeURIComponent(JSON.stringify(colors))

colors=%255B%2522red%2522%252C%2522green%2522%255D.

But when I does so additional characters 25 is getting added. How Can I prevent that?


问:
Backface-Visibility Not Working Properly in Firefox (Works in Safari)
I'm having a problem with the back face-visibilty property. It works how I want it to in Safari/Chrome, but for some reason it's not working correctly in Firefox.

When the box flips, I get a mirror image of the front face.

答: Add only -moz-backface-visibility: hidden; in the parent. This worked for me.


问:
How to get sum of 2 arrays
I've been trying to make a calculator in JavaScript.

My issue is I don't know how to find the sum of 2 arrays (the first number (33) is saved to an array called num1 ) (the second number (99) is saved to an array called num2 )  example(33+99 = ?)

I wrote the below statement but the total returns in a concatenated format ex(1,3,5,3) which is not my intended solution

```<code>     const calculate = (n1,n2) => {
     let result =""

     if (n1.length > 0 ){
        result =  n1 + n2
     }
        return result
     }

     v.push(calculate(num1, num2))
     document.getElementById("answer").innerHTML = v
</code>```

答:
Use .reduce()

let array1 = [1,2,3,4,5];
let array2 = [1,2,3,4,5];

let result = array1.reduce((a,v) => a + v,0) + array2.reduce((a,v) => a + v,0);

console.log(result);```

Title: How to get sum of 2 arrays

Body:
I've been trying to make a calculator in JavaScript.

My issue is I don't know how to find the sum of 2 arrays (the first number (33) is saved to an array called num1 ) (the second number (99) is saved to an array called num2 )  example(33+99 = ?)

I wrote the below statement but the total returns in a concatenated format ex(1,3,5,3) which is not my intended solution

     const calculate = (n1,n2) => {
     let result =""

     if (n1.length > 0 ){
        result =  n1 + n2
     }
        return result
     }

     v.push(calculate(num1, num2))
     document.getElementById("answer").innerHTML = v


问:
Kibana Bargraph not filtering data properly
I have inserted following dataset in index "testfilter"

```<code>POST /_bulk
{"index":{"_index":"testfilter"}}
{ "jobid": 1, "table_name": "table_A", "Tags": [ { "TagType": "WorkTypeA", "Tag": "ETL" }, { "TagType": "Subject Area", "Tag": "Telecom" } ] }
{"index":{"_index":"testfilter"}}
{ "jobid": 2, "table_name": "table_B", "Tags": [ { "TagType": "WorkTypeB", "Tag": "Engineering" }, { "TagType": "Subject Area", "Tag": "Telecom" } ] }
{"index":{"_index":"testfilter"}}
{ "jobid": 3, "table_name": "table_C", "Tags": [ { "TagType": "WorkTypeC", "Tag": "Development" }, { "TagType": "Subject Area", "Tag": "Telecom" } ] }
</code>```

And the index mapping ( GET testfilter/_mapping )  is as follows

```<code>{
  "testfilter" : {
    "mappings" : {
      "properties" : {
        "Tags" : {
          "properties" : {
            "Tag" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "TagType" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            }
          }
        },
        "jobid" : {
          "type" : "long"
        },
        "table_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}
</code>```

When I create a bar graph visualization in Kibana by choosing X Axis as :

```<code>Aggregation : Terms
Filed : Tags.Tag.keyword
</code>```

The graph gets build correctly. When I filter by choosing Tag : Development, I am getting two bar one filtering "Development" and other that of "Telecom" ( as seen in screenshot)

How do i build the graph that when I filter on any Tag I should get only that Tag data?

答:
This can be due to the fact that you are storing List of strings in field Tags.Tag in this document. If this is the case, then elasticsearch is functioning correctly.

You need to understand how elasticsearch aggregation works. Let's suppose you have inserted below json in elasticsearch

```<code>{
  "Tags": {
    "tag": [
      "abc",
      "def"
    ]
  }
}
</code>```

and in your visualization, you have clicked on term abc.

So elasticsearch on backend will fire a query and try to aggregate on all the terms present in all documents in which "abc" present in field "Tags.Tag.keyword".

So in your case, the document that has term development, might have also a value telecom in it, and so it showing this to you.

Body:
I have inserted following dataset in index "testfilter"

POST /_bulk
{"index":{"_index":"testfilter"}}
{ "jobid": 1, "table_name": "table_A", "Tags": [ { "TagType": "WorkTypeA", "Tag": "ETL" }, { "TagType": "Subject Area", "Tag": "Telecom" } ] }
{"index":{"_index":"testfilter"}}
{ "jobid": 2, "table_name": "table_B", "Tags": [ { "TagType": "WorkTypeB", "Tag": "Engineering" }, { "TagType": "Subject Area", "Tag": "Telecom" } ] }
{"index":{"_index":"testfilter"}}
{ "jobid": 3, "table_name": "table_C", "Tags": [ { "TagType": "WorkTypeC", "Tag": "Development" }, { "TagType": "Subject Area", "Tag": "Telecom" } ] }

And the index mapping ( GET testfilter/_mapping )  is as follows

{
  "testfilter" : {
    "mappings" : {
      "properties" : {
        "Tags" : {
          "properties" : {
            "Tag" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "TagType" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            }
          }
        },
        "jobid" : {
          "type" : "long"
        },
        "table_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }
      }
    }
  }
}

When I create a bar graph visualization in Kibana by choosing X Axis as :

Aggregation : Terms
Filed : Tags.Tag.keyword

The graph gets build correctly. When I filter by choosing Tag : Development, I am getting two bar one filtering "Development" and other that of "Telecom" ( as seen in screenshot)

How do i build the graph that when I filter on any Tag I should get only that Tag data?

Body:
This can be due to the fact that you are storing List of strings in field Tags.Tag in this document. If this is the case, then elasticsearch is functioning correctly.

You need to understand how elasticsearch aggregation works. Let's suppose you have inserted below json in elasticsearch

{
  "Tags": {
    "tag": [
      "abc",
      "def"
    ]
  }
}

and in your visualization, you have clicked on term abc.

So elasticsearch on backend will fire a query and try to aggregate on all the terms present in all documents in which "abc" present in field "Tags.Tag.keyword".

So in your case, the document that has term development, might have also a value telecom in it, and so it showing this to you.


问:
Using only part of a function in R
Is there any way to use only part of a function in R?
For example:

```<code>My.function <- function(x)
{
  m = mean(x)
  q.1 = quantile(x, 1/4)
  q.3 = quantile(x, 3/4)
  rbind(m, q.1, q.3)
}
</code>```

I want to use only q.1 and q.3 and not m for any reason. Is it possible? If it is, then how?

Thanks

答:
Why would you bother?  If you don't want the m in your output, just write

```<code>foo <- My.function(x)[2:3,]
</code>```

Note: if you are dealing with a function which contains three seriously time-consuming subfunctions, then it makes sense to do something similar to "doubled"s answer.  I would recommend full flexibility:

```<code> My.function <- function(x, dolist=c(1,1,1) )
{
result <-vector('list') # to handle any sorts of results
if(dolist[1])   { result[[1]] <- first.function(x) }
if(dolist[2])   {result[[2]] <- second.function(x) }
if(dolist[3])  {result[[3]] <- third.function(x) }
return(result)
}
</code>```

Title: Using only part of a function in R

Body:
Is there any way to use only part of a function in R?
For example:

My.function <- function(x)
{
  m = mean(x)
  q.1 = quantile(x, 1/4)
  q.3 = quantile(x, 3/4)
  rbind(m, q.1, q.3)
}

I want to use only q.1 and q.3 and not m for any reason. Is it possible? If it is, then how?

Thanks

Body:
Why would you bother?  If you don't want the m in your output, just write

foo <- My.function(x)[2:3,]

Note: if you are dealing with a function which contains three seriously time-consuming subfunctions, then it makes sense to do something similar to "doubled"s answer.  I would recommend full flexibility:

 My.function <- function(x, dolist=c(1,1,1) )
{
result <-vector('list') # to handle any sorts of results
if(dolist[1])   { result[[1]] <- first.function(x) }
if(dolist[2])   {result[[2]] <- second.function(x) }
if(dolist[3])  {result[[3]] <- third.function(x) }
return(result)
}


问:
Tips for studying Android
I joined a company recently and they have requested me to develop a few applications for Android. I've never seen it before - though I'm familiar with Java, so the programmatic syntax is familiar to me - and I'd like to know if there is a good site/textbook/whatever where I could learn how to program for Android OS - the simpler the better!

In particular, I'm searching for some way to allow me to use Android to do 2 things - to get a GPS location on a regular basis and to get an application connecting with a remote database. These are my priorities at the moment, but this doesn't mean you can't indicate me a knowledge source that doesn't have these on it. I do need to learn to program on this system, and I'll be thankful for whatever you indicate me. But if you happen to know where I could find these 2 items, please don't be shy and let me know.

Thanks in advance for your replies.

答: Honestly, the best place to start is right on the Android Developers site. Although you might not feel like you need it at first, spending the due time to do some of the simple tutorials to get used to how the UI works and how the Android framework and Activity lifecycle works is extremely important.</p>

ContentLicense: CC BY-SA 3.0

Title: Tips for studying Android


问:
Turbolinks 5 and history popstate event
I'm using Turbolinks in a Rails 6.1 web app.

I understand that Turbolinks uses AJAX to replace the body and uses the history.pushState() to update the URL to match.

I've implemented a dialog/modal system that appends an element to the body and then shows that element using CSS with some event handlers to close the dialog and remove it when the user clicks a close button on the dialog.

The problem is on mobile device browsers, users prefer to the use back button (bottom-left arrow on Android) instead of reaching up to the top of the dialog and clicking the close button.

So I need a way to intercept the normal Turbolinks restoration event and execute some of my own Javascript on the popstate event instead of Turbolinks taking over.

I'm aware the Turbolinks docs state that restoration events can't be canceled, but I was looking for a way I could use native JS to intercept the popstate before Turbolinks ever gets it.

I thought it should be pretty straightforward: when I show a dialog in my Javascript, I execute

```<code>window
      .history
      .pushState({ dialog: { id: "id-of-dialog" } }, null, window.location)
</code>```

and then have an event handler for the popstate that closes the dialog.

```<code>document.addEventListener("popstate", (event) => {
  console.log(event.state)
  if (event.state.dialog) {
    const dialogId = event.state.dialog.id
    const dialogElement = document.getElementyById(dialogId)

    // Note: I do have some animations for closing, so the closing logic is slightly more
    // complex than this, but this shows the gist of what's going on.
    dialogElement.classList.remove("dialog-container-open")
    dialogElement.remove()

    // Does this stop Turbolinks from taking over?
    event.preventDefault()
    event.stopPropagation()
  } else {
    // Do nothing, let Turbolinks handle it
  }
})
</code>```

However, in the popstate event, Turbolinks always has a state on top of the history stack and I can't figure out how or where it's happening, thus I can't stop it.

Essentially, I just want to manually manage the history popstate logic when the back button is pressed to handle my dialogs. But no matter what, Turbolinks always seems to fire and refresh the page when I just want to close a dialog.

Is there a way to implement this?  I've tried hashchange as well, but the history API seemed much more promising, since Turbolinks is built on top of that.

答:
The popstate event is not cancellable, and cannot be intercepted to prevent the default. (I suppose otherwise developers would be able to prevent users from leaving their sites!).

Turbolinks handles all popstate events and has its own mechanisms for doing so. You can push to the history stack in a way that Turbolinks understands by calling:

```<code>Turbolinks
  .controller
  .pushHistoryWithLocationAndRestorationIdentifier(<YOUR_LOCATION>, Turbolinks.uuid())
</code>```

So rather than thinking that you want to handle the popstate event, Turbolinks should now handle that for you, restoring the page as it was before you initialised the dialog. It's worth noting that whilst this is a public method, it's not documented, and therefore maybe removed in future versions.

Title: Turbolinks 5 and history popstate event

Body:
I'm using Turbolinks in a Rails 6.1 web app.

I understand that Turbolinks uses AJAX to replace the body and uses the history.pushState() to update the URL to match.

I've implemented a dialog/modal system that appends an element to the body and then shows that element using CSS with some event handlers to close the dialog and remove it when the user clicks a close button on the dialog.

The problem is on mobile device browsers, users prefer to the use back button (bottom-left arrow on Android) instead of reaching up to the top of the dialog and clicking the close button.

So I need a way to intercept the normal Turbolinks restoration event and execute some of my own Javascript on the popstate event instead of Turbolinks taking over.

I'm aware the Turbolinks docs state that restoration events can't be canceled, but I was looking for a way I could use native JS to intercept the popstate before Turbolinks ever gets it.

I thought it should be pretty straightforward: when I show a dialog in my Javascript, I execute

window
      .history
      .pushState({ dialog: { id: "id-of-dialog" } }, null, window.location)

and then have an event handler for the popstate that closes the dialog.

document.addEventListener("popstate", (event) => {
  console.log(event.state)
  if (event.state.dialog) {
    const dialogId = event.state.dialog.id
    const dialogElement = document.getElementyById(dialogId)

    // Note: I do have some animations for closing, so the closing logic is slightly more
    // complex than this, but this shows the gist of what's going on.
    dialogElement.classList.remove("dialog-container-open")
    dialogElement.remove()

    // Does this stop Turbolinks from taking over?
    event.preventDefault()
    event.stopPropagation()
  } else {
    // Do nothing, let Turbolinks handle it
  }
})

However, in the popstate event, Turbolinks always has a state on top of the history stack and I can't figure out how or where it's happening, thus I can't stop it.

Essentially, I just want to manually manage the history popstate logic when the back button is pressed to handle my dialogs. But no matter what, Turbolinks always seems to fire and refresh the page when I just want to close a dialog.

Is there a way to implement this?  I've tried hashchange as well, but the history API seemed much more promising, since Turbolinks is built on top of that.

Body:
The popstate event is not cancellable, and cannot be intercepted to prevent the default. (I suppose otherwise developers would be able to prevent users from leaving their sites!).

Turbolinks handles all popstate events and has its own mechanisms for doing so. You can push to the history stack in a way that Turbolinks understands by calling:

Turbolinks
  .controller
  .pushHistoryWithLocationAndRestorationIdentifier(<YOUR_LOCATION>, Turbolinks.uuid())

So rather than thinking that you want to handle the popstate event, Turbolinks should now handle that for you, restoring the page as it was before you initialised the dialog. It's worth noting that whilst this is a public method, it's not documented, and therefore maybe removed in future versions.


问:
pyspark: Auto filling in implicit missing values
I have a dataframe

```<code>user day amount
a 2 10
a 1 14
a 4 5
b 1 4
</code>```

You see that, the maximum value of day is 4, and the minimum value is 1. I want to fill 0 for amount column in all missing days of all users, so the above data frame will become.

```<code>user day amount
    a 2 10
    a 1 14
    a 4 5
    a 3 0
    b 1 4
    b 2 0
    b 3 0
    b 4 0
</code>```

How could I do that in PySpark? Many thanks.

答:
Another way to do this is to use sequence, array functions and explode. (spark2.4+)

```<code>from pyspark.sql import functions as F
from pyspark.sql.window import Window

w=Window().partitionBy(F.lit(0))

df.withColumn("boundaries", F.sequence(F.min("day").over(w),F.max("day").over(w),F.lit(1)))\
  .groupBy("user").agg(F.collect_list("day").alias('day'),F.collect_list("amount").alias('amount')\
   ,F.first("boundaries").alias("boundaries")).withColumn("boundaries", F.array_except("boundaries","day"))\
  .withColumn("day",F.flatten(F.array("day","boundaries"))).drop("boundaries")\
  .withColumn("zip", F.explode(F.arrays_zip("day","amount")))\
  .select("user","zip.day", F.when(F.col("zip.amount").isNull(),\
                                   F.lit(0)).otherwise(F.col("zip.amount")).alias("amount")).show()
#+----+---+------+
#|user|day|amount|
#+----+---+------+
#|   a|  2|    10|
#|   a|  1|    14|
#|   a|  4|     5|
#|   a|  3|     0|
#|   b|  1|     4|
#|   b|  2|     0|
#|   b|  3|     0|
#|   b|  4|     0|
#+----+---+------+
</code>```

Body:
I have a dataframe

user day amount
a 2 10
a 1 14
a 4 5
b 1 4

You see that, the maximum value of day is 4, and the minimum value is 1. I want to fill 0 for amount column in all missing days of all users, so the above data frame will become.

user day amount
    a 2 10
    a 1 14
    a 4 5
    a 3 0
    b 1 4
    b 2 0
    b 3 0
    b 4 0

How could I do that in PySpark? Many thanks.

Body:
Another way to do this is to use sequence, array functions and explode. (spark2.4+)

from pyspark.sql import functions as F
from pyspark.sql.window import Window

w=Window().partitionBy(F.lit(0))

df.withColumn("boundaries", F.sequence(F.min("day").over(w),F.max("day").over(w),F.lit(1)))\
  .groupBy("user").agg(F.collect_list("day").alias('day'),F.collect_list("amount").alias('amount')\
   ,F.first("boundaries").alias("boundaries")).withColumn("boundaries", F.array_except("boundaries","day"))\
  .withColumn("day",F.flatten(F.array("day","boundaries"))).drop("boundaries")\
  .withColumn("zip", F.explode(F.arrays_zip("day","amount")))\
  .select("user","zip.day", F.when(F.col("zip.amount").isNull(),\
                                   F.lit(0)).otherwise(F.col("zip.amount")).alias("amount")).show()
#+----+---+------+
#|user|day|amount|
#+----+---+------+
#|   a|  2|    10|
#|   a|  1|    14|
#|   a|  4|     5|
#|   a|  3|     0|
#|   b|  1|     4|
#|   b|  2|     0|
#|   b|  3|     0|
#|   b|  4|     0|
#+----+---+------+


问:
How do I pass a variable used in a function to a variable in another function in C?
I'm making a small and simple game in C as a project for college.
In the game, there's a function in which the player will buy troops of different types for his army. Then, during the execution of the other function, the player will position the troops bought in the game scenario, but the function "needs to know" how many troops and of which type the player bought.

So basically, what I'm asking is how do I pass the value of a variable used in a function to be used in another one.

答: If your code needs to work a lot with common data in different functions, you could put this data in a embedded database  (sqlite for example) that will be part of you executable.</p>


问:
Applying conditions before executing variable nested loop for permutation
I need to get the permutations in the following way: I have N slots, and this slots can be filled with variables reaching from 1 to D. To get all possible permutations I wrote a loop that gives me every different possibility.  The loops look a little bit "strange" due to it being a nested loop that needs to be variable. This loop would take two days to complete (for my condition with N = 8, and D=25), however I only need the permutations where sum of the variables in the slots are equal to "D".

```<code>import numpy as np
from tqdm import tqdm

N = 4 # actualy 8
D = 16  # actually 25

test = np.ones(shape=N)

for k in range(0,pow(D-1,N)):

    if sum(test) == D:
        print("this is a suiting fit!",test)

    # last one gets always changed
    if test[N-1]+1 < D:
        test[N-1] += 1
    else:
        test[N-1] = 1

        for idx in range(2,len(test)+1):

            if test[len(test) -idx] + 1 < D:
                test[len(test) - idx] += 1
                break
            else:
                test[len(test) - idx] = 1
</code>```

Since the above loop might look a little bit confusing I enrolled it into nested loops

```<code>for i in range(0,D-1):
    for j in range(0,D-1):
        for k in range(0,D-1):
            for l in range(0,D-1):
                if k+1+l+1+j+1+i+1 == D:
                    print("this is a suting fit!",k+1,l+1,j+1,i+1)
</code>```

I cannot get my head around how to make it either faster by simplification or by applying the condition before iterating over the permutations, any help is appreciated

答:
you can use permutations and give the length.

```<code>from itertools import permutations
d = 16
n = 4
for item in permutations(range(d), r=n):
    if sum(item) == d:
        print("this is a suiting fit!", item)
</code>```

I think you may not need permutations

```<code>from itertools import product
d = 16
n = 4
for item in product(range(d), repeat=n):
    if sum(item) == d:
        print("this is a suiting fit!", item)
</code>```

Body:
I need to get the permutations in the following way: I have N slots, and this slots can be filled with variables reaching from 1 to D. To get all possible permutations I wrote a loop that gives me every different possibility.  The loops look a little bit "strange" due to it being a nested loop that needs to be variable. This loop would take two days to complete (for my condition with N = 8, and D=25), however I only need the permutations where sum of the variables in the slots are equal to "D".

import numpy as np
from tqdm import tqdm

N = 4 # actualy 8
D = 16  # actually 25

test = np.ones(shape=N)

for k in range(0,pow(D-1,N)):

    if sum(test) == D:
        print("this is a suiting fit!",test)

    # last one gets always changed
    if test[N-1]+1 < D:
        test[N-1] += 1
    else:
        test[N-1] = 1

        for idx in range(2,len(test)+1):

            if test[len(test) -idx] + 1 < D:
                test[len(test) - idx] += 1
                break
            else:
                test[len(test) - idx] = 1

Since the above loop might look a little bit confusing I enrolled it into nested loops

for i in range(0,D-1):
    for j in range(0,D-1):
        for k in range(0,D-1):
            for l in range(0,D-1):
                if k+1+l+1+j+1+i+1 == D:
                    print("this is a suting fit!",k+1,l+1,j+1,i+1)

I cannot get my head around how to make it either faster by simplification or by applying the condition before iterating over the permutations, any help is appreciated

Body:
you can use permutations and give the length.

from itertools import permutations
d = 16
n = 4
for item in permutations(range(d), r=n):
    if sum(item) == d:
        print("this is a suiting fit!", item)

I think you may not need permutations

from itertools import product
d = 16
n = 4
for item in product(range(d), repeat=n):
    if sum(item) == d:
        print("this is a suiting fit!", item)


问:
mongoose async await, unable to capture connection state
I'm trying to capture the connection success state for mongoose/mongodb.
The idea is simply that, when I start the app, if the connection fails, I need an alert recorded.
I can't figure out why, once I connect - or once the connection fails - the function does not return what I tell it to return.

```<code>import { DBURL } from '../parameters/environment';

const mongoose = require('mongoose');
const chalk = require('chalk');

const connected = chalk.bold.cyan;
const error = chalk.bold.yellow;

const connectMe = async () => {
  await mongoose.connect(DBURL, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
      console.log(connected('DB connection successful'));
      return 'Success';
    })
    .catch((reason) => {
      console.log(error('Unable to connect to the mongodb instance. Error: '), reason);
      return 'FAIL';
    });
  return 'Why am I returning this????';
};

module.exports = connectMe;
</code>```

I simply call it and try to display the result.
But regardless of the DB state, the return statement in .then or .catch is ignored
Server.js:

```<code>const connectMe = require('./db-actions/db-connect');

const myResult = connectMe();
myResult.then(x => console.log(x));
</code>```

If mongodb is up, I get this:

DB connection successful
  Why am I returning this????

If mongodb is down, I get this:

Unable to connect to the mongodb instance. Error:  MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:30000
  Why am I returning this????

Console.log works, but the return does not.
Any idea why?

答:
Why it seems return is not working:

You are combining both async/await and .then/.catch, you should choose one of the two. Also, the return keyword is not properly placed within connectMe the function.

The fix:

Since, you are expecting the connectMe function to return a promise so you can attach a .then like this:

```<code>myResult.then(x => console.log(x));
</code>```

You can just go with a .then/.catch in the connectMe function and the return statement should be on mongoose.connect, that's the promise the outside world(i.e outside the function) needs to interact with. Code:

```<code>const connectMe = () => {
  return mongoose.connect(DBURL, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
      console.log(connected('DB connection successful'));
      return 'Success';
    })
    .catch ((reason) =>  {
      console.log(error('Unable to connect to the mongodb instance. Error: '), reason);
      return 'FAIL';
    })
};
</code>```

Body:
I'm trying to capture the connection success state for mongoose/mongodb.
The idea is simply that, when I start the app, if the connection fails, I need an alert recorded.
I can't figure out why, once I connect - or once the connection fails - the function does not return what I tell it to return.

import { DBURL } from '../parameters/environment';

const mongoose = require('mongoose');
const chalk = require('chalk');

const connected = chalk.bold.cyan;
const error = chalk.bold.yellow;

const connectMe = async () => {
  await mongoose.connect(DBURL, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
      console.log(connected('DB connection successful'));
      return 'Success';
    })
    .catch((reason) => {
      console.log(error('Unable to connect to the mongodb instance. Error: '), reason);
      return 'FAIL';
    });
  return 'Why am I returning this????';
};

module.exports = connectMe;

I simply call it and try to display the result.
But regardless of the DB state, the return statement in .then or .catch is ignored
Server.js:

const connectMe = require('./db-actions/db-connect');

const myResult = connectMe();
myResult.then(x => console.log(x));

If mongodb is up, I get this:

DB connection successful
  Why am I returning this????

If mongodb is down, I get this:

Unable to connect to the mongodb instance. Error:  MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:30000
  Why am I returning this????

Console.log works, but the return does not.
Any idea why?

Body:
Why it seems return is not working:

You are combining both async/await and .then/.catch, you should choose one of the two. Also, the return keyword is not properly placed within connectMe the function.

The fix:

Since, you are expecting the connectMe function to return a promise so you can attach a .then like this:

myResult.then(x => console.log(x));

You can just go with a .then/.catch in the connectMe function and the return statement should be on mongoose.connect, that's the promise the outside world(i.e outside the function) needs to interact with. Code:

const connectMe = () => {
  return mongoose.connect(DBURL, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
      console.log(connected('DB connection successful'));
      return 'Success';
    })
    .catch ((reason) =>  {
      console.log(error('Unable to connect to the mongodb instance. Error: '), reason);
      return 'FAIL';
    })
};


问:
How to fix entity not mapped error in HIbernate 5.4.17?
Here is my StudentDaoImpl.java class

```<code>package com.gavs.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.type.StringType;

import com.gavs.beans.Student;
import com.gavs.hibernateutil.HibernateUtil;

public class StudentDaoImpl implements StudentDao {

    @Override
    public List<Student> showRecords(Student s) {

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = sessionFactory.openSession();

        session.beginTransaction();

            String hql="from Student";
        System.out.println(hql);

       List<Student> rl=session.createQuery(hql).list();

        session.getTransaction().commit();
        session.close();
        return rl;
    }}

</code>```

Here is the error page :

```<code>Type Exception Report

Message Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped [from Student]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped [from Student]
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped [from Student]
    org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
    org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:725)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:113)
    com.gavs.dao.StudentDaoImpl.showRecords(StudentDaoImpl.java:41)
    com.gavs.controllers.StudentControl.getStudentDetail(StudentControl.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped [from Student]
    org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
    org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:220)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
    org.hibernate.boot.internal.SessionFactoryBuilderImpl$$Lambda$186/862841004.createQueryPlan(Unknown Source)
    org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162)
    org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:604)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:716)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:113)
    com.gavs.dao.StudentDaoImpl.showRecords(StudentDaoImpl.java:41)
    com.gavs.controllers.StudentControl.getStudentDetail(StudentControl.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped
    org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
    org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
    org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
    org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:333)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3758)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3647)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:732)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:588)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:325)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:273)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:276)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
    org.hibernate.boot.internal.SessionFactoryBuilderImpl$$Lambda$186/862841004.createQueryPlan(Unknown Source)
    org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162)
    org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:604)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:716)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:113)
    com.gavs.dao.StudentDaoImpl.showRecords(StudentDaoImpl.java:41)
    com.gavs.controllers.StudentControl.getStudentDetail(StudentControl.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
</code>```

Here is my HibernateUtil.java class

```<code>package com.gavs.hibernateutil;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

        private static SessionFactory sessionFactory;

        public static SessionFactory getSessionFactory() {

            if (sessionFactory == null) {
                // loads configuration and mappings
                Configuration configuration = new Configuration().configure();
                ServiceRegistry serviceRegistry
                    = new StandardServiceRegistryBuilder()
                        .applySettings(configuration.getProperties()).build();

                // builds a session factory from the service registry
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            }

            return sessionFactory;
        }
    }
</code>```

Here is my  Student.java

```<code>package com.gavs.beans;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="STUDENT_TABLE")
public class Student{

    @Id
    @Column(name="Roll_No")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int roll_no;

    @Column(name="Name")
    private String name;

    @Column(name="Age")
    private int age;

    @Column(name="Address")
    private String address;

    @ManyToOne
    @JoinColumn(name="Dept_Id")
    private Department departments;

    public Student() {
        super();
    }

        public int getRoll_no() {
        return roll_no;
    }

    public void setRoll_no(int roll_no) {
        this.roll_no = roll_no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Department getDepartments() {
        return departments;
    }

    public void setDepartments(Department departments) {
        this.departments = departments;
    }

}

</code>```

Please let me know whether  I have to put the hibernate.cfg.xml file within the configure() method of the above HibernateUtil class. This is a Spring MVC and Hibernate project. In this project, I'm using three entities which has @OneTOMany relations.

Thank You

答:
Just Now I got it. I hadn't mentioned the fully qualified class name. That was the error.

I changed the query as,             String hql="from com.gavs.beans.Student";

Body:
Here is my StudentDaoImpl.java class

package com.gavs.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.type.StringType;

import com.gavs.beans.Student;
import com.gavs.hibernateutil.HibernateUtil;

public class StudentDaoImpl implements StudentDao {

    @Override
    public List<Student> showRecords(Student s) {

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

        Session session = sessionFactory.openSession();

        session.beginTransaction();

            String hql="from Student";
        System.out.println(hql);

       List<Student> rl=session.createQuery(hql).list();

        session.getTransaction().commit();
        session.close();
        return rl;
    }}

Here is the error page :

Type Exception Report

Message Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped [from Student]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped [from Student]
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped [from Student]
    org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:138)
    org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:725)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:113)
    com.gavs.dao.StudentDaoImpl.showRecords(StudentDaoImpl.java:41)
    com.gavs.controllers.StudentControl.getStudentDetail(StudentControl.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped [from Student]
    org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
    org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:220)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
    org.hibernate.boot.internal.SessionFactoryBuilderImpl$$Lambda$186/862841004.createQueryPlan(Unknown Source)
    org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162)
    org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:604)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:716)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:113)
    com.gavs.dao.StudentDaoImpl.showRecords(StudentDaoImpl.java:41)
    com.gavs.controllers.StudentControl.getStudentDetail(StudentControl.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

org.hibernate.hql.internal.ast.QuerySyntaxException: Student is not mapped
    org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:169)
    org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
    org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
    org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:333)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3758)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3647)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:732)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:588)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:325)
    org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:273)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:276)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
    org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
    org.hibernate.boot.internal.SessionFactoryBuilderImpl$$Lambda$186/862841004.createQueryPlan(Unknown Source)
    org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162)
    org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:604)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:716)
    org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:113)
    com.gavs.dao.StudentDaoImpl.showRecords(StudentDaoImpl.java:41)
    com.gavs.controllers.StudentControl.getStudentDetail(StudentControl.java:37)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:483)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.

Here is my HibernateUtil.java class

package com.gavs.hibernateutil;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

        private static SessionFactory sessionFactory;

        public static SessionFactory getSessionFactory() {

            if (sessionFactory == null) {
                // loads configuration and mappings
                Configuration configuration = new Configuration().configure();
                ServiceRegistry serviceRegistry
                    = new StandardServiceRegistryBuilder()
                        .applySettings(configuration.getProperties()).build();

                // builds a session factory from the service registry
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            }

            return sessionFactory;
        }
    }

Here is my  Student.java

package com.gavs.beans;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="STUDENT_TABLE")
public class Student{

    @Id
    @Column(name="Roll_No")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int roll_no;

    @Column(name="Name")
    private String name;

    @Column(name="Age")
    private int age;

    @Column(name="Address")
    private String address;

    @ManyToOne
    @JoinColumn(name="Dept_Id")
    private Department departments;

    public Student() {
        super();
    }

        public int getRoll_no() {
        return roll_no;
    }

    public void setRoll_no(int roll_no) {
        this.roll_no = roll_no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Department getDepartments() {
        return departments;
    }

    public void setDepartments(Department departments) {
        this.departments = departments;
    }

}

Please let me know whether  I have to put the hibernate.cfg.xml file within the configure() method of the above HibernateUtil class. This is a Spring MVC and Hibernate project. In this project, I'm using three entities which has @OneTOMany relations.

Thank You


问:
TO Use Cygwin within Eclipse 3.6
I'm working in J2EE application. We are developing application in java/j2ee. In our project we use cygwin to simulate linux os, run shell script included in application and to deploy. How to use eclipse to embed eclipse and cygwin and deloy in run/debug mode.
Am new to this kind of stuff and confused to how to proceed further. Please suggest me how to proceed with this.

Thanks in advance.

Appreciated for guiding...

We r developing j2ee project in window env. and deploying in linux server.
so to simulate linux in windows we use cygwin.
Now we use eclipse to develop and get into cmd prompt and start cygwin and then run basic shell script to initialize variables and build the project and deploy the EAR in linux server ...
For these two purpose i have to toggle the window and i couldn't debug the code and check for check time data.

Is there any possibility to merge cygwin with eclipse to start the server  or in run in debug mode, so that my developement process would be efficient and easy to code walk through... My enter team is following the first process which may tedious work.

Can any one suggest to work efficient with this project

Thanks in advance

答: Don't use shell scripts for your deployment process. Maven almost certainly has plugins for everything your shell scripts are currently doing, and it runs on Windows and Linux transparently.</p>

Title: TO Use Cygwin within Eclipse 3.6


问:
How to change AM TO PM in Python
I'm trying to change my output to 12/30/1999 11:59:59:PM

here is my code:

```<code>strOutTime = datetime(1999,12,30,11,59,59)
strOutTime = strOutTime.strftime("%m/%d/%Y %I:%M:%S:%p")
</code>```

But I get 12/30/1999 11:59:59:AM.
Any suggestion?

答:
If you use 23 instead of 11, you will get PM. Python is taking 11 as 11th hour of the day.

strOutTime = datetime(1999,12,30,23,59,58)
strOutTime = strOutTime.strftime("%m/%d/%Y %I:%M:%S:%p")
```

Title: How to change AM TO PM in Python

Body:
I'm trying to change my output to 12/30/1999 11:59:59:PM

here is my code:

strOutTime = datetime(1999,12,30,11,59,59)
strOutTime = strOutTime.strftime("%m/%d/%Y %I:%M:%S:%p")

But I get 12/30/1999 11:59:59:AM.
Any suggestion?


问:
is there a way to record videos in kivy?
I am displaying the camera video in Kivy, but I can't find a way to record the video, I tried to use OpenCV Videowriter but because of the updating ( Clock.schedule_interval(self.update, 1.0/33.0)) it is constantly overwriting so the video that it saved is one image, does anybody have an alternative way.</p>

答:
Please look into the below code which may serve your purpose. The main code is taken from the link: https://www.codingforentrepreneurs.com/blog/how-to-record-video-in-opencv-python. I have only adapted for kivy framework (as the question is for kivy solution) and adjusted the frame_per_second to make it consistent with viewing & writing speed.

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.properties import StringProperty, NumericProperty

import cv2
import os

# Standard Video Dimensions Sizes
STD_DIMENSIONS =  {
    "480p": (640, 480),
    "720p": (1280, 720),
    "1080p": (1920, 1080),
    "4k": (3840, 2160),
}

# Video Encoding, might require additional installs
# Types of Codes: http://www.fourcc.org/codecs.php
VIDEO_TYPE = {
    'avi': cv2.VideoWriter_fourcc(*'XVID'),
    #'mp4': cv2.VideoWriter_fourcc(*'H264'),
    'mp4': cv2.VideoWriter_fourcc(*'XVID'),
}

class KivyCamera(BoxLayout):
    filename = StringProperty('video.avi')
    frames_per_second = NumericProperty(30.0)
    video_resolution = StringProperty('720p')

    def __init__(self, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self.img1=Image()
        self.add_widget(self.img1)
        self.capture = cv2.VideoCapture(0)
        self.out = cv2.VideoWriter(self.filename, self.get_video_type(self.filename), self.frames_per_second, self.get_dims(self.capture, self.video_resolution))
        Clock.schedule_interval(self.update, 1 / self.frames_per_second)

    def update(self, *args):
        ret, frame = self.capture.read()
        self.out.write(frame)
        buf = cv2.flip(frame, 0).tostring()
        texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr")
        texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
        self.img1.texture = texture

    # Set resolution for the video capture
    # Function adapted from https://kirr.co/0l6qmh
    def change_resolution(self, cap, width, height):
        self.capture.set(3, width)
        self.capture.set(4, height)

    # grab resolution dimensions and set video capture to it.
    def get_dims(self, cap, video_resolution='1080p'):
        width, height = STD_DIMENSIONS["480p"]
        if self.video_resolution in STD_DIMENSIONS:
            width, height = STD_DIMENSIONS[self.video_resolution]
        ## change the current caputre device
        ## to the resulting resolution
        self.change_resolution(cap, width, height)
        return width, height

    def get_video_type(self, filename):
        filename, ext = os.path.splitext(filename)
        if ext in VIDEO_TYPE:
          return  VIDEO_TYPE[ext]
        return VIDEO_TYPE['avi']

class CamApp(App):
    def build(self):
        return KivyCamera()

if __name__ == '__main__':
    CamApp().run()
</code>```

Body:
Please look into the below code which may serve your purpose. The main code is taken from the link: https://www.codingforentrepreneurs.com/blog/how-to-record-video-in-opencv-python. I have only adapted for kivy framework (as the question is for kivy solution) and adjusted the frame_per_second to make it consistent with viewing & writing speed.

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
from kivy.properties import StringProperty, NumericProperty

import cv2
import os

# Standard Video Dimensions Sizes
STD_DIMENSIONS =  {
    "480p": (640, 480),
    "720p": (1280, 720),
    "1080p": (1920, 1080),
    "4k": (3840, 2160),
}

# Video Encoding, might require additional installs
# Types of Codes: http://www.fourcc.org/codecs.php
VIDEO_TYPE = {
    'avi': cv2.VideoWriter_fourcc(*'XVID'),
    #'mp4': cv2.VideoWriter_fourcc(*'H264'),
    'mp4': cv2.VideoWriter_fourcc(*'XVID'),
}

class KivyCamera(BoxLayout):
    filename = StringProperty('video.avi')
    frames_per_second = NumericProperty(30.0)
    video_resolution = StringProperty('720p')

    def __init__(self, **kwargs):
        super(KivyCamera, self).__init__(**kwargs)
        self.img1=Image()
        self.add_widget(self.img1)
        self.capture = cv2.VideoCapture(0)
        self.out = cv2.VideoWriter(self.filename, self.get_video_type(self.filename), self.frames_per_second, self.get_dims(self.capture, self.video_resolution))
        Clock.schedule_interval(self.update, 1 / self.frames_per_second)

    def update(self, *args):
        ret, frame = self.capture.read()
        self.out.write(frame)
        buf = cv2.flip(frame, 0).tostring()
        texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt="bgr")
        texture.blit_buffer(buf, colorfmt="bgr", bufferfmt="ubyte")
        self.img1.texture = texture

    # Set resolution for the video capture
    # Function adapted from https://kirr.co/0l6qmh
    def change_resolution(self, cap, width, height):
        self.capture.set(3, width)
        self.capture.set(4, height)

    # grab resolution dimensions and set video capture to it.
    def get_dims(self, cap, video_resolution='1080p'):
        width, height = STD_DIMENSIONS["480p"]
        if self.video_resolution in STD_DIMENSIONS:
            width, height = STD_DIMENSIONS[self.video_resolution]
        ## change the current caputre device
        ## to the resulting resolution
        self.change_resolution(cap, width, height)
        return width, height

    def get_video_type(self, filename):
        filename, ext = os.path.splitext(filename)
        if ext in VIDEO_TYPE:
          return  VIDEO_TYPE[ext]
        return VIDEO_TYPE['avi']

class CamApp(App):
    def build(self):
        return KivyCamera()

if __name__ == '__main__':
    CamApp().run()


问:
Postgresql Error: error: password authentication failed for user “postgres” in Adonis.js
I have a Ubuntu 18.04 LTS vps in where I've installed and configured postgresql.
I can log in to the postgresql via command line. But I can not be able to establish a connection into my project.

But right after deployment of an Adonis project, It shoes me error message of below
error: error: password authentication failed for user "postgres"

Full Error is below:

```<code>error: error: password authentication failed for user "postgres"
0|server  |     at Connection.parseE (project_directory/node_modules/pg/lib/connection.js:614:13)
0|server  |     at Connection.parseMessage (project_directory/node_modules/pg/lib/connection.js:413:19)
0|server  |     at Socket.<anonymous> (project_directory/node_modules/pg/lib/connection.js:129:22)
0|server  |     at Socket.emit (events.js:315:20)
0|server  |     at addChunk (_stream_readable.js:295:12)
0|server  |     at readableAddChunk (_stream_readable.js:271:9)
0|server  |     at Socket.Readable.push (_stream_readable.js:212:10)
0|server  |     at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
0|server  | From previous event:
0|server  |     at Client_PG.acquireRawConnection (project_directory/node_modules/knex/lib/dialects/postgres/index.js:147:12)
0|server  |     at create (project_directory/node_modules/knex/lib/client.js:280:23)
0|server  |     at project_directory/node_modules/tarn/lib/Pool.js:315:34
0|server  |     at Object.tryPromise (project_directory/node_modules/tarn/lib/utils.js:53:24)
0|server  |     at project_directory/node_modules/tarn/lib/Pool.js:315:17
0|server  |     at new Promise (<anonymous>)
0|server  |     at callbackOrPromise (project_directory/node_modules/tarn/lib/Pool.js:306:12)
0|server  |     at Pool._create (project_directory/node_modules/tarn/lib/Pool.js:236:9)
0|server  |     at Pool._doCreate (project_directory/node_modules/tarn/lib/Pool.js:208:36)
0|server  |     at Pool._tryAcquireOrCreate (project_directory/node_modules/tarn/lib/Pool.js:159:18)
0|server  |     at Pool.acquire (project_directory/node_modules/tarn/lib/Pool.js:85:14)
0|server  |     at project_directory/node_modules/knex/lib/client.js:335:26
0|server  | From previous event:
0|server  |     at Client_PG.acquireConnection (project_directory/node_modules/knex/lib/client.js:334:34)
0|server  |     at Runner.ensureConnection (project_directory/node_modules/knex/lib/runner.js:228:24)
0|server  |     at Runner.run (project_directory/node_modules/knex/lib/runner.js:34:42)
0|server  |     at Builder.Target.then (project_directory/node_modules/knex/lib/interface.js:20:43) {
0|server  |   length: 104,
0|server  |   severity: 'FATAL',
0|server  |   code: '28P01',
0|server  |   detail: undefined,
0|server  |   hint: undefined,
0|server  |   position: undefined,
0|server  |   internalPosition: undefined,
0|server  |   internalQuery: undefined,
0|server  |   where: undefined,
0|server  |   schema: undefined,
0|server  |   table: undefined,
0|server  |   column: undefined,
0|server  |   dataType: undefined,
0|server  |   constraint: undefined,
0|server  |   file: 'auth.c',
0|server  |   line: '333',
0|server  |   routine: 'auth_failed'
0|server  | }
</code>```

Though I did some research and as per these instructions I updated the pg_hba.conf file. Here it is below:

```<code># Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            peer
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5
</code>```

Here is my project environemnt(.env) file

```<code>HOST=127.0.0.1
PORT=8989
NODE_ENV=development

APP_NAME=
APP_URL=http://${HOST}:${PORT}
CACHE_VIEWS=false
APP_KEY=my_app_key

DB_CONNECTION=pg
DB_HOST=127.0.0.1
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=my_db_pass
DB_DATABASE=my_db_name

... other credential goes here ....
</code>```

Note: my_db_pass is my postgres username's password. I can successfully get logged in using this password in command-line.

Can anyone help me figuring out about what went wrong ?

答:
go in config/database.js

find PostgreSQL configuration and replace password value like this

```<code>password: "direct set your password",
</code>```

and try I have same issue in Cpanel hosting and I try this method it's work

Body:
I have a Ubuntu 18.04 LTS vps in where I've installed and configured postgresql.
I can log in to the postgresql via command line. But I can not be able to establish a connection into my project.

But right after deployment of an Adonis project, It shoes me error message of below
error: error: password authentication failed for user "postgres"

Full Error is below:

error: error: password authentication failed for user "postgres"
0|server  |     at Connection.parseE (project_directory/node_modules/pg/lib/connection.js:614:13)
0|server  |     at Connection.parseMessage (project_directory/node_modules/pg/lib/connection.js:413:19)
0|server  |     at Socket.<anonymous> (project_directory/node_modules/pg/lib/connection.js:129:22)
0|server  |     at Socket.emit (events.js:315:20)
0|server  |     at addChunk (_stream_readable.js:295:12)
0|server  |     at readableAddChunk (_stream_readable.js:271:9)
0|server  |     at Socket.Readable.push (_stream_readable.js:212:10)
0|server  |     at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
0|server  | From previous event:
0|server  |     at Client_PG.acquireRawConnection (project_directory/node_modules/knex/lib/dialects/postgres/index.js:147:12)
0|server  |     at create (project_directory/node_modules/knex/lib/client.js:280:23)
0|server  |     at project_directory/node_modules/tarn/lib/Pool.js:315:34
0|server  |     at Object.tryPromise (project_directory/node_modules/tarn/lib/utils.js:53:24)
0|server  |     at project_directory/node_modules/tarn/lib/Pool.js:315:17
0|server  |     at new Promise (<anonymous>)
0|server  |     at callbackOrPromise (project_directory/node_modules/tarn/lib/Pool.js:306:12)
0|server  |     at Pool._create (project_directory/node_modules/tarn/lib/Pool.js:236:9)
0|server  |     at Pool._doCreate (project_directory/node_modules/tarn/lib/Pool.js:208:36)
0|server  |     at Pool._tryAcquireOrCreate (project_directory/node_modules/tarn/lib/Pool.js:159:18)
0|server  |     at Pool.acquire (project_directory/node_modules/tarn/lib/Pool.js:85:14)
0|server  |     at project_directory/node_modules/knex/lib/client.js:335:26
0|server  | From previous event:
0|server  |     at Client_PG.acquireConnection (project_directory/node_modules/knex/lib/client.js:334:34)
0|server  |     at Runner.ensureConnection (project_directory/node_modules/knex/lib/runner.js:228:24)
0|server  |     at Runner.run (project_directory/node_modules/knex/lib/runner.js:34:42)
0|server  |     at Builder.Target.then (project_directory/node_modules/knex/lib/interface.js:20:43) {
0|server  |   length: 104,
0|server  |   severity: 'FATAL',
0|server  |   code: '28P01',
0|server  |   detail: undefined,
0|server  |   hint: undefined,
0|server  |   position: undefined,
0|server  |   internalPosition: undefined,
0|server  |   internalQuery: undefined,
0|server  |   where: undefined,
0|server  |   schema: undefined,
0|server  |   table: undefined,
0|server  |   column: undefined,
0|server  |   dataType: undefined,
0|server  |   constraint: undefined,
0|server  |   file: 'auth.c',
0|server  |   line: '333',
0|server  |   routine: 'auth_failed'
0|server  | }

Though I did some research and as per these instructions I updated the pg_hba.conf file. Here it is below:

# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            peer
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
local   replication     all                                     peer
host    replication     all             127.0.0.1/32            md5
host    replication     all             ::1/128                 md5

Here is my project environemnt(.env) file

HOST=127.0.0.1
PORT=8989
NODE_ENV=development

APP_NAME=
APP_URL=http://${HOST}:${PORT}
CACHE_VIEWS=false
APP_KEY=my_app_key

DB_CONNECTION=pg
DB_HOST=127.0.0.1
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=my_db_pass
DB_DATABASE=my_db_name

... other credential goes here ....

Note: my_db_pass is my postgres username's password. I can successfully get logged in using this password in command-line.

Can anyone help me figuring out about what went wrong ?

Body:
go in config/database.js

find PostgreSQL configuration and replace password value like this

password: "direct set your password",

and try I have same issue in Cpanel hosting and I try this method it's work


问:
Python: C engine does not support regex separators
Attempting to upload a bunch of csv's to a database. The csvs are not necesarily always separated by a comma so I used a regular expression to ensure the correct delimiters are used. I then added the

```<code>error_bad_lines=False
</code>```

in order to handle CParserError: Error tokenizing data. C error: Expected 3 fields in line 127, saw 4
which resulted in me getting this error

```<code>ValueError: Falling back to the 'python' engine because the 'c' engine does not support regex separators, but this causes 'error_bad_lines' to be ignored as it is not supported by the 'python' engine.
</code>```

for the following code

Is there a workaround?

```<code>import psycopg2
import pandas as pd
import sqlalchemy as sa
csvList = []
tableList = []
filenames = find_csv_filenames(directory)
for name in filenames:
    lhs, rhs = str(name).split(".", 1)
    print name
    dataRaw = pd.read_csv(name,sep=";|,",chunksize=5000000, error_bad_lines=False)
    for chunk in dataRaw:
        chunk.to_sql(name = str(lhs),if_exists='append',con=con)
</code>```

答:
As per pandas parameter in this link  Pandas-link
if the separator is more than one character you need to add engine parameter as 'python'.

try this,

```<code>dataRaw = pd.read_csv(name,sep=";|,",engine ='python',chunksize=5000000,
error_bad_lines=False)
</code>```

Body:
Attempting to upload a bunch of csv's to a database. The csvs are not necesarily always separated by a comma so I used a regular expression to ensure the correct delimiters are used. I then added the

error_bad_lines=False

in order to handle CParserError: Error tokenizing data. C error: Expected 3 fields in line 127, saw 4
which resulted in me getting this error

ValueError: Falling back to the 'python' engine because the 'c' engine does not support regex separators, but this causes 'error_bad_lines' to be ignored as it is not supported by the 'python' engine.

for the following code

Is there a workaround?

import psycopg2
import pandas as pd
import sqlalchemy as sa
csvList = []
tableList = []
filenames = find_csv_filenames(directory)
for name in filenames:
    lhs, rhs = str(name).split(".", 1)
    print name
    dataRaw = pd.read_csv(name,sep=";|,",chunksize=5000000, error_bad_lines=False)
    for chunk in dataRaw:
        chunk.to_sql(name = str(lhs),if_exists='append',con=con)

Body:
As per pandas parameter in this link  Pandas-link
if the separator is more than one character you need to add engine parameter as 'python'.

try this,

dataRaw = pd.read_csv(name,sep=";|,",engine ='python',chunksize=5000000,
error_bad_lines=False)


问:
How to make a table with automatic column widths without using HTML table?
I have a big table I'm trying to add some hover effects to and finding that CSS tables are relatively inflexible, so I'd like to try to implement some other way (see background below).

I'm thinking CSS grid might work. How can I make a CSS table using CSS grid? I need the columns widths to adjust automatically (and of course be synced between rows), as they do with a regular CSS table, and (I think) I need each row to be a parent element to its cells, as in tables.

I read here that the level 2 specifications of CSS grid incorporate a subgrid, but I've been unable to find an example of using subgrid to duplicate basic table functionality. It seems most browsers don't yet implement subgrid, so display: contents might be an alternative.

Background in case you need it: I'm trying to implement a sort of action-bar hover-overlay, as in Gmail: when you hover the cursor over a row/email, an overlay appears on the right side of the row with various actions you can perform on the row/email, such as Move to folder, Delete. Gmail displays the table rows as flex boxes to make this possible, but that means the column widths have to be set "by hand." In my case I have a massive table of various data and setting column widths by hand isn't feasible.

UPDATE: what does it look like? It's an ordinary table with rows and columns. You have certainly seen such things before. I'm asking a general question and the particulars of the table are irrelevant.

Here is a screen shot from Gmail, fwiw:

答:
You can use the last cell of each row to hold the action icons. Then display them on tr:hover

  * {
  box-sizing: border-box;
}

body {
  font-family: 'Segoe UI'
}

table {
  width: 100%;
  border-collapse: collapse;
}

table td,
table th {
  padding: .5em 1em;
  text-align: left;
}

table th {
  border-bottom: 1px solid #999;
}

table tr td:last-child {
  position: relative;
  white-space: nowrap;
}

.row-action {
  position: absolute;
  display: none;
  right: 1em;
  top: 50%;
  transform: translateY(-50%);
  background-color: #f4f4f4;
  padding: 0.25em 0.5em;
}

tr:hover .row-action {
  display: block;
}

i:not(:last-child) {
  margin-right: 1em;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://use.fontawesome.com/releases/v5.12.0/css/all.css" rel="stylesheet" />
<table class="table">
  <thead>
    <tr>
      <th>
        Name
      </th>
      <th>
        Address
      </th>
      <th>
        Contact
      </th>
      <th>
        Name
      </th>
      <th>
        Address
      </th>
      <th>
        Contact
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        Name
      </td>
      <td>
        Address
      </td>
      <td>
        Contact
      </td>
      <td>
        Name
      </td>
      <td>
        Address
      </td>
      <td>
        Contact
        <span class="row-action">
              <i class="fas fa-reply"></i>
        <i class="fas fa-reply-all"></i>
        <i class="fas fa-comment-dots"></i>
        </span>
      </td>
    </tr>

    <tr>
      <td>
        Name
      </td>
      <td>
        Address
      </td>
      <td>
        Contact
      </td>
      <td>
        Name
      </td>
      <td>
        Address
      </td>
      <td>
        Contact
        <span class="row-action">
        <i class="fas fa-reply"></i>
        <i class="fas fa-reply-all"></i>
        <i class="fas fa-comment-dots"></i>
        </span>
      </td>
    </tr>
  </tbody>
</table></code>```

Body:
You can use the last cell of each row to hold the action icons. Then display them on tr:hover

  * {
  box-sizing: border-box;
}

body {
  font-family: 'Segoe UI'
}

table {
  width: 100%;
  border-collapse: collapse;
}

table td,
table th {
  padding: .5em 1em;
  text-align: left;
}

table th {
  border-bottom: 1px solid #999;
}

table tr td:last-child {
  position: relative;
  white-space: nowrap;
}

.row-action {
  position: absolute;
  display: none;
  right: 1em;
  top: 50%;
  transform: translateY(-50%);
  background-color: #f4f4f4;
  padding: 0.25em 0.5em;
}

tr:hover .row-action {
  display: block;
}

i:not(:last-child) {
  margin-right: 1em;

<link href="https://use.fontawesome.com/releases/v5.12.0/css/all.css" rel="stylesheet" />
<table class="table">
  <thead>
    <tr>
      <th>
        Name
      </th>
      <th>
        Address
      </th>
      <th>
        Contact
      </th>
      <th>
        Name
      </th>
      <th>
        Address
      </th>
      <th>
        Contact
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        Name
      </td>
      <td>
        Address
      </td>
      <td>
        Contact
      </td>
      <td>
        Name
      </td>
      <td>
        Address
      </td>
      <td>
        Contact
        <span class="row-action">
              <i class="fas fa-reply"></i>
        <i class="fas fa-reply-all"></i>
        <i class="fas fa-comment-dots"></i>
        </span>
      </td>
    </tr>

    <tr>
      <td>
        Name
      </td>
      <td>
        Address
      </td>
      <td>
        Contact
      </td>
      <td>
        Name
      </td>
      <td>
        Address
      </td>
      <td>
        Contact
        <span class="row-action">
        <i class="fas fa-reply"></i>
        <i class="fas fa-reply-all"></i>
        <i class="fas fa-comment-dots"></i>
        </span>
      </td>
    </tr>
  </tbody>
</table>


问:
is there a way to implement redo and undo on imageView
I have used a slider to take input and apply effects on the Image View with help of Color Adjust</p>

```<code>public void adjustBrightness() {
        colorAdjust.setBrightness(brightnessSlider.getValue());
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }

    public void adjustSaturation() {
        colorAdjust.setSaturation(saturationSlider.getValue());
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }

    public void adjustContrast() {
        colorAdjust.setContrast(contrastSlider.getValue());
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }

    public void adjustHue() {
        colorAdjust.setHue(hueSlider.getValue());
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }
</code>```

答:
There is no simple built in mechanism to do what you want as far as I know.  In order to undo and redo the applied color adjustments, you will need to save a copy of the color adjustment to something like an ArrayDeque.  To undo and redo you move the adjustments between the undo and redo double ended queues and apply the adjustments.

A simple save function would save the current adjustment to the undo deque:

private Deque<ColorAdjustment> undos = new ArrayDeque<>();
private Deque<ColorAdjustment> redos = new ArrayDeque<>();

public void saveColorAdjustment(ColorAdjust save) {
    ColorAdjust copy = new ColorAdjust(save.getHue(), save.getSaturation(), save.getBrightness(), save.getContrast());
    undos.addLast(copy)
    // clear any redos since we added a new undo
    redos.clear()
}
```

<p>Then in each of your adjust functions, call save after changing colorAdjust so that the most recent change will be available for redo:</p>

<pre class="lang-java prettyprint-override"><code>    public void adjustHue() {
        colorAdjust.setHue(hueSlider.getValue());
        saveColorAdjustment(colorAdjust);
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }
</code>```

Then undo and redo will move adjustments between the deques and set the color adjustment as needed.

public void undoColorAdjustment() {
    if (undos.size() > 0) {
        // move last undo (which is current applied adjustment) to redo
        redos.addFirst(undos.removeLast())
        // apply last color effect
        imageView.setEffect(undos.getLast());
        addDrawOperation(imageView.getImage());
    }
}

public void redoColorAdjustment() {
    if (redos.size() > 0 ) {
        // move first redo to undos
        undos.addLast(redos.removeFirst());
        // apply last color effect
        imageView.setEffect(undos.getLast());
        addDrawOperation(imageView.getImage());
    }
}
```

That should give you the basic idea.  Of course you will need to handle the case when undos is empty to apply no colorAdjustments or remove effects from the image view.

This is just one way to do it.  Swing provides an UndoManager where you create a class for each action (e.g. UndoColorAdjustment()) that you want to apply and it handles managing the undo and redo lists. You could possibly use that UndoManager or create your own.  Otherwise, what I have here is a simple straight forward way to go.

Body:
I have used a slider to take input and apply effects on the Image View with help of Color Adjust

public void adjustBrightness() {
        colorAdjust.setBrightness(brightnessSlider.getValue());
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }

    public void adjustSaturation() {
        colorAdjust.setSaturation(saturationSlider.getValue());
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }

    public void adjustContrast() {
        colorAdjust.setContrast(contrastSlider.getValue());
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }

    public void adjustHue() {
        colorAdjust.setHue(hueSlider.getValue());
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }

Body:
There is no simple built in mechanism to do what you want as far as I know.  In order to undo and redo the applied color adjustments, you will need to save a copy of the color adjustment to something like an ArrayDeque.  To undo and redo you move the adjustments between the undo and redo double ended queues and apply the adjustments.

A simple save function would save the current adjustment to the undo deque:

private Deque<ColorAdjustment> undos = new ArrayDeque<>();
private Deque<ColorAdjustment> redos = new ArrayDeque<>();

public void saveColorAdjustment(ColorAdjust save) {
    ColorAdjust copy = new ColorAdjust(save.getHue(), save.getSaturation(), save.getBrightness(), save.getContrast());
    undos.addLast(copy)
    // clear any redos since we added a new undo
    redos.clear()
}

Then in each of your adjust functions, call save after changing colorAdjust so that the most recent change will be available for redo:

    public void adjustHue() {
        colorAdjust.setHue(hueSlider.getValue());
        saveColorAdjustment(colorAdjust);
        imageView.setEffect(colorAdjust);
        addDrawOperation(imageView.getImage());
    }

Then undo and redo will move adjustments between the deques and set the color adjustment as needed.

public void undoColorAdjustment() {
    if (undos.size() > 0) {
        // move last undo (which is current applied adjustment) to redo
        redos.addFirst(undos.removeLast())
        // apply last color effect
        imageView.setEffect(undos.getLast());
        addDrawOperation(imageView.getImage());
    }
}

public void redoColorAdjustment() {
    if (redos.size() > 0 ) {
        // move first redo to undos
        undos.addLast(redos.removeFirst());
        // apply last color effect
        imageView.setEffect(undos.getLast());
        addDrawOperation(imageView.getImage());
    }
}

That should give you the basic idea.  Of course you will need to handle the case when undos is empty to apply no colorAdjustments or remove effects from the image view.

This is just one way to do it.  Swing provides an UndoManager where you create a class for each action (e.g. UndoColorAdjustment()) that you want to apply and it handles managing the undo and redo lists. You could possibly use that UndoManager or create your own.  Otherwise, what I have here is a simple straight forward way to go.