问:
How to solve issue of "cannot cast object" for Microsoft SQL in spring boot?
I am trying to call a stored procedure for my application using Microsoft SQL. However, when I run the stored procedure to pass back the contents of the object it fails. I have the objects as AVSApplication and in that class it has a list of variables and methods. I tried using an Iterable and a List but both produce the same error. I am not sure where I went wrong. I looked at other similar StackOverflow questions but I didn't get much from it.

Error:

```<code>java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to com.Mapping.AVSApplication
    at com.Mapping.Employeecontroller.getAll(Employeecontroller.java:33) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~
</code>```

Java Entity Code:

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

import javax.persistence.*;

@Entity
@NamedStoredProcedureQueries(value= {
        @NamedStoredProcedureQuery(name= "procedure-one", procedureName= "GetAllAppWithStatus")
})

public class AVSApplication implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private String appcode;

    private String acronym;

    private String appname;

    private String sys_id;

    private String mapstatus;

    private String sdg;

    private String status;

    private String statuscode;

    //Constructor
    public AVSApplication(String appcode, String acronym, String appname, String sys_id, String mapstatus,
            String sdg, String status, String statuscode) {
        super();
        this.appcode = appcode;
        this.acronym = acronym;
        this.appname = appname;
        this.sys_id = sys_id;
        this.mapstatus = mapstatus;
        this.sdg = sdg;
        this.status = status;
        this.statuscode = statuscode;
    }

    //Getters

    public String getAppcode() {
        return appcode;
    }

    public String getAcronym() {
        return acronym;
    }

    public String getAppname() {
        return appname;
    }

    public String getSys_id() {
        return sys_id;
    }

    public String getMapstatus() {
        return mapstatus;
    }

    public String getSdg() {
        return sdg;
    }

    public String getStatus() {
        return status;
    }

    public String getStatuscode() {
        return statuscode;
    }

    //Setters

    public void setAppcode(String appcode) {
        this.appcode = appcode;
    }

    public void setAcronym(String acronym) {
        this.acronym = acronym;
    }

    public void setAppname(String appname) {
        this.appname = appname;
    }

    public void setSys_id(String sys_id) {
        this.sys_id = sys_id;
    }

    public void setMapstatus(String mapstatus) {
        this.mapstatus = mapstatus;
    }

    public void setSdg(String sdg) {
        this.sdg = sdg;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setStatuscode(String statuscode) {
        this.statuscode = statuscode;
    }

}

</code>```

DAO:

```<code>
@Repository
public class Employeedao {
    @Autowired
    private EntityManager em;

    /**
     * Method to fetch all employees from the db.
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<AVSApplication> getAllEmployees() {
        return em.createNamedStoredProcedureQuery("procedure-one").getResultList();
    }

}
</code>```

Controller:

```<code>
@RestController
public class Employeecontroller {

   @Autowired
   Employeedao edao;

   /**
    * Method to fetch all employees from the db.
    * @return
    */
   @RequestMapping(value= "/getall")
   public void getAll() {
      System.out.println("All objects: " + edao.getAllEmployees());

      System.out.println("Get the first item in list: " + edao.getAllEmployees().get(0).getAppcode());

   }

}

</code>```

答:
In given code there is nothing that would map rows returned by stored procedure AVSApplication instances:

```<code>@NamedStoredProcedureQueries(value= {
        @NamedStoredProcedureQuery(name= "procedure-one", procedureName= "GetAllAppWithStatus")
})
</code>```

If stored procedure matches nicely to entity, then definining result class can be enough:

```<code>@NamedStoredProcedureQueries(value= {
    @NamedStoredProcedureQuery(
        name= "procedure-one",
        procedureName= "GetAllAppWithStatus",
        resultClasses = {AVSApplication.class}
})
</code>```

If there is some discrepancies, one must define SqlResultSetMapping and refer to it from resultsetMappings.

Body:
I am trying to call a stored procedure for my application using Microsoft SQL. However, when I run the stored procedure to pass back the contents of the object it fails. I have the objects as AVSApplication and in that class it has a list of variables and methods. I tried using an Iterable and a List but both produce the same error. I am not sure where I went wrong. I looked at other similar StackOverflow questions but I didn't get much from it.

Error:

java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to com.Mapping.AVSApplication
    at com.Mapping.Employeecontroller.getAll(Employeecontroller.java:33) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~

Java Entity Code:

import java.util.*;

import javax.persistence.*;

@Entity
@NamedStoredProcedureQueries(value= {
        @NamedStoredProcedureQuery(name= "procedure-one", procedureName= "GetAllAppWithStatus")
})

public class AVSApplication implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private String appcode;

    private String acronym;

    private String appname;

    private String sys_id;

    private String mapstatus;

    private String sdg;

    private String status;

    private String statuscode;

    //Constructor
    public AVSApplication(String appcode, String acronym, String appname, String sys_id, String mapstatus,
            String sdg, String status, String statuscode) {
        super();
        this.appcode = appcode;
        this.acronym = acronym;
        this.appname = appname;
        this.sys_id = sys_id;
        this.mapstatus = mapstatus;
        this.sdg = sdg;
        this.status = status;
        this.statuscode = statuscode;
    }

    //Getters

    public String getAppcode() {
        return appcode;
    }

    public String getAcronym() {
        return acronym;
    }

    public String getAppname() {
        return appname;
    }

    public String getSys_id() {
        return sys_id;
    }

    public String getMapstatus() {
        return mapstatus;
    }

    public String getSdg() {
        return sdg;
    }

    public String getStatus() {
        return status;
    }

    public String getStatuscode() {
        return statuscode;
    }

    //Setters

    public void setAppcode(String appcode) {
        this.appcode = appcode;
    }

    public void setAcronym(String acronym) {
        this.acronym = acronym;
    }

    public void setAppname(String appname) {
        this.appname = appname;
    }

    public void setSys_id(String sys_id) {
        this.sys_id = sys_id;
    }

    public void setMapstatus(String mapstatus) {
        this.mapstatus = mapstatus;
    }

    public void setSdg(String sdg) {
        this.sdg = sdg;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setStatuscode(String statuscode) {
        this.statuscode = statuscode;
    }

}

DAO:

@Repository
public class Employeedao {
    @Autowired
    private EntityManager em;

    /**
     * Method to fetch all employees from the db.
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<AVSApplication> getAllEmployees() {
        return em.createNamedStoredProcedureQuery("procedure-one").getResultList();
    }

}

Controller:

@RestController
public class Employeecontroller {

   @Autowired
   Employeedao edao;

   /**
    * Method to fetch all employees from the db.
    * @return
    */
   @RequestMapping(value= "/getall")
   public void getAll() {
      System.out.println("All objects: " + edao.getAllEmployees());

      System.out.println("Get the first item in list: " + edao.getAllEmployees().get(0).getAppcode());

   }

}

Body:
In given code there is nothing that would map rows returned by stored procedure AVSApplication instances:

@NamedStoredProcedureQueries(value= {
        @NamedStoredProcedureQuery(name= "procedure-one", procedureName= "GetAllAppWithStatus")
})

If stored procedure matches nicely to entity, then definining result class can be enough:

@NamedStoredProcedureQueries(value= {
    @NamedStoredProcedureQuery(
        name= "procedure-one",
        procedureName= "GetAllAppWithStatus",
        resultClasses = {AVSApplication.class}
})

If there is some discrepancies, one must define SqlResultSetMapping and refer to it from resultsetMappings.


来源: stackexchange

问:
How can I count only 'Yes' entities in my column of a dataframe?
In Input[96] I tried many things but couldnot do anything, always getting both 'yes, and 'no values'

Input:

```<code>y = (z_copy['fruity']) .value_counts()
print(y)
</code>```

Output:

```<code>No     45
Yes    38
Name: fruity, dtype: int64
</code>```

答:
EDIT: Because value_counts() returns Series so you can use ['Yes']

```<code>print( z_copy['fruity'].value_counts()['Yes'] )
</code>```

.

```<code>import pandas as pd

z_copy = pd.DataFrame({'fruity': ['Yes', 'No', 'Yes', 'No', 'No']})

print( z_copy['fruity'].value_counts()['Yes'] )
</code>```

OLD VERSION: You can get selected rows and use len()

```<code>import pandas as pd

z_copy = pd.DataFrame({'fruity': ['Yes', 'No', 'Yes', 'No', 'No']})

filter = (z_copy['fruity'] == 'Yes')
selected = z_copy[filter]

print( len( selected ) )

#print( len( z_copy[df['fruity'] == 'Yes'] ) )
</code>```

Eventually you can use sum() because True/False is converted to 1/0

```<code>filter = (z_copy['fruity'] == 'Yes')

print( sum( filter ) )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Input[96] I tried many things but couldnot do anything, always getting both 'yes, and 'no values'

Input:

y = (z_copy['fruity']) .value_counts()
print(y)

Output:

No     45
Yes    38
Name: fruity, dtype: int64

Body:
EDIT: Because value_counts() returns Series so you can use ['Yes']

print( z_copy['fruity'].value_counts()['Yes'] )

.

import pandas as pd

z_copy = pd.DataFrame({'fruity': ['Yes', 'No', 'Yes', 'No', 'No']})

print( z_copy['fruity'].value_counts()['Yes'] )

OLD VERSION: You can get selected rows and use len()

import pandas as pd

z_copy = pd.DataFrame({'fruity': ['Yes', 'No', 'Yes', 'No', 'No']})

filter = (z_copy['fruity'] == 'Yes')
selected = z_copy[filter]

print( len( selected ) )

#print( len( z_copy[df['fruity'] == 'Yes'] ) )

Eventually you can use sum() because True/False is converted to 1/0

filter = (z_copy['fruity'] == 'Yes')

print( sum( filter ) )


问:
Finding the radius of a circle that circumscribes a polygon
I am trying to find the best way of obtaining: the length of the longest line from the center of a polygon to its edge.

In the code below, I download the polygon data of the 75254 zip code located in Texas, USA. I then determine the location of its center with sf::st_centroid() and I plot the geometries using the tmap package.

```<code># Useful packages

library(dplyr)
library(sf)
library(tigris)
library(tmap)

# Download polygon data

geo <- tigris::zctas(cb = TRUE, starts_with = "75254")
geo <- st_as_sf(geo)

# Determine the location of the polygon's center

geo_center <- st_centroid(geo)

# Plot geometries

tm_shape(geo) +
  tm_polygons() +
  tm_shape(geo_center) +
  tm_dots(size = 0.1, col = "red")
</code>```

Once again, is there an efficient way to determine the length of the line going from the center of the polygon all the way to the farthest point on the polygon's edge? In other words, how can I find the radius of the circle that perfectly circumscribes the  polygon given that both the circle and the polygon have the same center?

Thank you very much for your help.

答:
One point here, although I mentioned, st_bbox wouldn't work as the centroid of the bbox and the one of your shape are not the same, since the centroid is weighted. See here one approach based on the further distance to the points of the border, but you woud need to project your shape (currently is unprojected):

```<code>library(dplyr)
library(sf)
library(tigris)
library(tmap)

# Download polygon data
geo <- tigris::zctas(cb = TRUE, starts_with = "75254")
geo <- st_as_sf(geo)

st_crs(geo)
#> Coordinate Reference System:
#>   EPSG: 4269
#>   proj4string: "+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs"

#Need to project
geo=st_transform(geo,3857)

# Determine the location of the polygon's center

geo_center <- st_centroid(geo)
#> Warning in st_centroid.sf(geo): st_centroid assumes attributes are constant over
#> geometries of x

plot(st_geometry(geo))
plot(st_geometry(geo_center), col="blue", add=TRUE)

#Cast to points
geopoints=st_cast(geo,"POINT")
#> Warning in st_cast.sf(geo, "POINT"): repeating attributes for all sub-geometries
#> for which they may not be constant

r=max(st_distance(geo_center,geopoints))
r
#> 3684.917 [m]
buffer=st_buffer(geo_center,dist=r)
plot(st_geometry(buffer), add=TRUE, border="green")
</code>```

Body:
I am trying to find the best way of obtaining: the length of the longest line from the center of a polygon to its edge.

In the code below, I download the polygon data of the 75254 zip code located in Texas, USA. I then determine the location of its center with sf::st_centroid() and I plot the geometries using the tmap package.

# Useful packages

library(dplyr)
library(sf)
library(tigris)
library(tmap)

# Download polygon data

geo <- tigris::zctas(cb = TRUE, starts_with = "75254")
geo <- st_as_sf(geo)

# Determine the location of the polygon's center

geo_center <- st_centroid(geo)

# Plot geometries

tm_shape(geo) +
  tm_polygons() +
  tm_shape(geo_center) +
  tm_dots(size = 0.1, col = "red")

Once again, is there an efficient way to determine the length of the line going from the center of the polygon all the way to the farthest point on the polygon's edge? In other words, how can I find the radius of the circle that perfectly circumscribes the  polygon given that both the circle and the polygon have the same center?

Thank you very much for your help.

Body:
One point here, although I mentioned, st_bbox wouldn't work as the centroid of the bbox and the one of your shape are not the same, since the centroid is weighted. See here one approach based on the further distance to the points of the border, but you woud need to project your shape (currently is unprojected):

library(dplyr)
library(sf)
library(tigris)
library(tmap)

# Download polygon data
geo <- tigris::zctas(cb = TRUE, starts_with = "75254")
geo <- st_as_sf(geo)

st_crs(geo)
#> Coordinate Reference System:
#>   EPSG: 4269
#>   proj4string: "+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs"

#Need to project
geo=st_transform(geo,3857)

# Determine the location of the polygon's center

geo_center <- st_centroid(geo)
#> Warning in st_centroid.sf(geo): st_centroid assumes attributes are constant over
#> geometries of x

plot(st_geometry(geo))
plot(st_geometry(geo_center), col="blue", add=TRUE)

#Cast to points
geopoints=st_cast(geo,"POINT")
#> Warning in st_cast.sf(geo, "POINT"): repeating attributes for all sub-geometries
#> for which they may not be constant

r=max(st_distance(geo_center,geopoints))
r
#> 3684.917 [m]
buffer=st_buffer(geo_center,dist=r)
plot(st_geometry(buffer), add=TRUE, border="green")


问:
how to have a lock on a mysql database and dequeue the waiting jobs
i was wondering if anyone knew how to lock a database, and then dequeue the waiting jobs. so i have a hashtable in a database, and im storing data in the database where multiple users are sending requests to edit that data at the same time, but the data needs to be persistent across all users and that only one user can acesss/edit it at a time.

thanks a bunch = )

答:
Can you elaborate on "but the data needs to be persistent across all users"?

I think that InnoDb which is transactional will keep things in a way that's consistent to all of your users. It's ACID compliant.

ContentLicense: CC BY-SA 3.0


问:
Why pdf_text from pdftools reads only the first page of each pdf element in my list of pdfs?
I would like to create a dataframe with all the text and title of ech pdf of my pdfs list. I made one for loop but when I open the resulting dataframe I see that not all the text from each pdf have been processed into text, but only the last page.

Here the code:

```<code>#folder
folder <- paste0(getwd(), "/data/pdfs/")

#QC
qc <- sample(1:length(pdf_list), size = 1, replace = F)

#Create a vector of all the files in the folder selected
file_vector <- list.files(all.files = T, path = folder, recursive = T)

#Apply a filter to the file vector of files
pdf_list <- file_vector[grepl(".pdf", file_vector)]

#make the data frame
corpus_raw <- data.frame("title" = c(),"text" = c())

#list of pdf files comprehensive of path
files <- paste0(folder,pdf_list)

#cycle for the text fetching:
for (i in 1:length(pdf_list)){
    #print i so that I know the loop is working right
    print(i)
    #take the text
    text_from_pdf <- pdf_text(pdf = files[i])
    temp_store_data <- data.frame("title" = gsub(pattern = "\\d\\/", replacement = "",
                                               x = pdf_list[i], ignore.case = T),
                                  "text" = text_from_pdf, stringsAsFactors = F)
    # quality control
    if (i == qc[1]){
      print(temp_store_data[i,2])
      write(temp_store_data[i,2], "data/quality_control.txt")
    }
    colnames(temp_store_data) <- c("title", "text")
    corpus_raw <- rbind(corpus_raw, temp_store_data)
}
</code>```

Can you help me with this?
Thank you!

答:
pdf_text creates a vector with one string per page, not a single text string. You are only writing the ith page of your list to the qc text file.

You could try this when reading in the pdf:

text_from_pdf <- paste(pdf_text(pdf = files[i]), collapse = "\n")
```

This should work providing you do not have whole novels as pdfs to store.

Body:
I would like to create a dataframe with all the text and title of ech pdf of my pdfs list. I made one for loop but when I open the resulting dataframe I see that not all the text from each pdf have been processed into text, but only the last page.

Here the code:

#folder
folder <- paste0(getwd(), "/data/pdfs/")

#QC
qc <- sample(1:length(pdf_list), size = 1, replace = F)

#Create a vector of all the files in the folder selected
file_vector <- list.files(all.files = T, path = folder, recursive = T)

#Apply a filter to the file vector of files
pdf_list <- file_vector[grepl(".pdf", file_vector)]

#make the data frame
corpus_raw <- data.frame("title" = c(),"text" = c())

#list of pdf files comprehensive of path
files <- paste0(folder,pdf_list)

#cycle for the text fetching:
for (i in 1:length(pdf_list)){
    #print i so that I know the loop is working right
    print(i)
    #take the text
    text_from_pdf <- pdf_text(pdf = files[i])
    temp_store_data <- data.frame("title" = gsub(pattern = "\\d\\/", replacement = "",
                                               x = pdf_list[i], ignore.case = T),
                                  "text" = text_from_pdf, stringsAsFactors = F)
    # quality control
    if (i == qc[1]){
      print(temp_store_data[i,2])
      write(temp_store_data[i,2], "data/quality_control.txt")
    }
    colnames(temp_store_data) <- c("title", "text")
    corpus_raw <- rbind(corpus_raw, temp_store_data)
}

Can you help me with this?
Thank you!

Body:
pdf_text creates a vector with one string per page, not a single text string. You are only writing the ith page of your list to the qc text file.

You could try this when reading in the pdf:

text_from_pdf <- paste(pdf_text(pdf = files[i]), collapse = "\n")

This should work providing you do not have whole novels as pdfs to store.


问:
How can I convert columns of a pandas DataFrame into a list of lists?
I have a pandas DataFrame with multiple columns.

```<code>2u    2s    4r     4n     4m   7h   7v
0     1     1      0      0     0    1
0     1     0      1      0     0    1
1     0     0      1      0     1    0
1     0     0      0      1     1    0
1     0     1      0      0     1    0
0     1     1      0      0     0    1
</code>```

What I want to do is to convert this pandas.DataFrame into a list like following

```<code>X = [
     [0, 0, 1, 1, 1, 0],
     [1, 1, 0, 0, 0, 1],
     [1, 0, 0, 0, 1, 1],
     [0, 1, 1, 0, 0, 0],
     [0, 0, 0, 1, 0, 0],
     [0, 0, 1, 1, 1, 0],
     [1, 1, 0, 0, 0, 1]
    ]
</code>```

2u    2s    4r     4n     4m   7h   7v   are column headings. It will change in different situations, so don't bother about it.

答:
To change Dataframe into list use tolist() function to convert
Let use say i have Dataframe df

to change into list you can simply use tolist() function

```<code>df.values.tolist()
</code>```

You can also change a particular column in to list by using

```<code>df['column name'].values.tolist()
</code>```

Body:
I have a pandas DataFrame with multiple columns.

2u    2s    4r     4n     4m   7h   7v
0     1     1      0      0     0    1
0     1     0      1      0     0    1
1     0     0      1      0     1    0
1     0     0      0      1     1    0
1     0     1      0      0     1    0
0     1     1      0      0     0    1

What I want to do is to convert this pandas.DataFrame into a list like following

X = [
     [0, 0, 1, 1, 1, 0],
     [1, 1, 0, 0, 0, 1],
     [1, 0, 0, 0, 1, 1],
     [0, 1, 1, 0, 0, 0],
     [0, 0, 0, 1, 0, 0],
     [0, 0, 1, 1, 1, 0],
     [1, 1, 0, 0, 0, 1]
    ]

2u    2s    4r     4n     4m   7h   7v   are column headings. It will change in different situations, so don't bother about it.

Body:
To change Dataframe into list use tolist() function to convert
Let use say i have Dataframe df

to change into list you can simply use tolist() function

df.values.tolist()

You can also change a particular column in to list by using

df['column name'].values.tolist()


问:
Check if a string contains the keywords of a file c#
I'm trying to check if a string contains a keyword present in a text file but nothing was done

If you need more information ask me

For exemple i have a keywords.txt like this :

```<code>example1
example2
example3
</code>```

and i want to see if one of these keyword are in a json string like this :

```<code>{
     "title":"new doc 4",
     "rotate":0,
     "sort_key":"new doc 4",
     "tag_ids":"",
     "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
     "co_token":"",
     "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
     "t":"1474932063",
     "c":"2",
     "updated":"1474932063"
}
</code>```

You can see what i have try below
So I'm hoping you can help me solve this problem thanks

```<code>if (json.Contains(File.ReadAllText(@"keywords.txt")))
{
    //My if logic
}
else
{
    //My else logic
}
</code>```

答:
If you want check any word in file contains in string then, first you need to store all lines from file into an Array, then you need to string contains any of string from array or not.

Enumerable.Any method

Determines whether any element of a sequence exists or satisfies a
  condition.

To do that try below,

```<code>var examples = File.ReadAllLines(@"keywords.txt");

if(examples.Any(x => json.Contains(x))
{
  //Your business logic
}
else
{
  //Your business logic
}
</code>```

If you want to check exact match then you can try with RegEx IsMatch() function

like,

```<code>using System.Text;
using System.Text.RegularExpressions;
...
var examples = File.ReadAllLines(@"keywords.txt");

//If you want to ignore case then, pass third parameter to IsMatch() "RegexOptions.IgnoreCase"
if(examples.Any(x => Regex.IsMatch(json, $@"\b{x}\b"))
{
  // here "\b" stands for boundary
  //Your business logic
}
else
{
  //Your business logic
}
</code>```

Body:
I'm trying to check if a string contains a keyword present in a text file but nothing was done

If you need more information ask me

For exemple i have a keywords.txt like this :

example1
example2
example3

and i want to see if one of these keyword are in a json string like this :

{
     "title":"new doc 4",
     "rotate":0,
     "sort_key":"new doc 4",
     "tag_ids":"",
     "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
     "co_token":"",
     "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
     "t":"1474932063",
     "c":"2",
     "updated":"1474932063"
}

You can see what i have try below
So I'm hoping you can help me solve this problem thanks

if (json.Contains(File.ReadAllText(@"keywords.txt")))
{
    //My if logic
}
else
{
    //My else logic
}

Body:
If you want check any word in file contains in string then, first you need to store all lines from file into an Array, then you need to string contains any of string from array or not.

Enumerable.Any method

Determines whether any element of a sequence exists or satisfies a
  condition.

To do that try below,

var examples = File.ReadAllLines(@"keywords.txt");

if(examples.Any(x => json.Contains(x))
{
  //Your business logic
}
else
{
  //Your business logic
}

If you want to check exact match then you can try with RegEx IsMatch() function

like,

using System.Text;
using System.Text.RegularExpressions;
...
var examples = File.ReadAllLines(@"keywords.txt");

//If you want to ignore case then, pass third parameter to IsMatch() "RegexOptions.IgnoreCase"
if(examples.Any(x => Regex.IsMatch(json, $@"\b{x}\b"))
{
  // here "\b" stands for boundary
  //Your business logic
}
else
{
  //Your business logic
}


问:
how to use a plugin inside a groovy plugin
I am trying to migrate tasks from build.gradle to a plugin that do it.
In my build.gradle I do this:

```<code>plugins {
    //id 'java'
    id 'war'

    //https://plugins.gradle.org/plugin/org.gretty
    id 'org.gretty' version '3.0.1'

    id "com.github.dkorotych.gradle-maven-exec" version "2.2.1"

}
apply plugin: 'maven'

....
....

prepareFrontEnd (type: MavenExec, dependsOn: build) {
    goals 'vaadin:prepare-frontend'
}

task buildFrontEnd (type: MavenExec, dependsOn: prepareFrontEnd) {
    goals 'vaadin:build-frontend'
}
</code>```

Now I am moving this stuff to a plugins:

```<code>package com.github.mdre.hgvaadinplugin

import org.gradle.api.Plugin;
import org.gradle.api.Project;
//import com.github.dkorotych.gradle.maven.exec.MavenExec;

class HGVaadinPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        println "Hybrid Gradle Vaaadin plugin."
        project.plugins.apply('com.github.dkorotych.gradle-maven-exec')
        // project.getPluginManager().apply('gradle-maven-exec-plugin')

        project.task('prepareFrontEnd', type: MavenExec){
            dependsOn build
            doLast {
                goal 'vaadin:prepare-frontend'
            }
        }
    }
}
</code>```

If I try to import the class MavenExec I get this error:

```<code>> Task :compileGroovy FAILED
startup failed:
/home/mdre/Proyectos/HGVaadinPlugin/src/main/groovy/com/github/mdre/hgvaadinplugin/HGVaadinPlugin.groovy: 5: unable to resolve class com.github.dkorotych.gradle.maven.exec.MavenExec
 @ line 5, column 1.
   import com.github.dkorotych.gradle.maven.exec.MavenExec;
   ^
</code>```

and if I comment the import line, I get this error in the project that use the plugin:

What went wrong:
A problem occurred evaluating root project 'VaadinFlowLab'.

Failed to apply plugin [id 'com.github.mdre.hgvaadinplugin']
  No such property: MavenExec for class: com.github.mdre.hgvaadinplugin.HGVaadinPlugin

How could I do this?

Thanks.

答:
Well, I fix it!

I forget to include the dependency class in the final jar. So all of I need was to add this to the build.config:

```<code>configurations {
    // configuration that holds jars to include in the jar
    extraLibs
}

dependencies {
    ....
    ....
    //necesario para crear un fatJar
    extraLibs "gradle.plugin.com.github.dkorotych.gradle.maven.exec:gradle-maven-exec-plugin:2.2.1"
    configurations.compile.extendsFrom(configurations.extraLibs)
}

jar {
    from {
        configurations.extraLibs.collect { it.isDirectory() ? it : zipTree(it) }
    }
}
</code>```

and now it is working!!

Body:
I am trying to migrate tasks from build.gradle to a plugin that do it.
In my build.gradle I do this:

plugins {
    //id 'java'
    id 'war'

    //https://plugins.gradle.org/plugin/org.gretty
    id 'org.gretty' version '3.0.1'

    id "com.github.dkorotych.gradle-maven-exec" version "2.2.1"

}
apply plugin: 'maven'

....
....

prepareFrontEnd (type: MavenExec, dependsOn: build) {
    goals 'vaadin:prepare-frontend'
}

task buildFrontEnd (type: MavenExec, dependsOn: prepareFrontEnd) {
    goals 'vaadin:build-frontend'
}

Now I am moving this stuff to a plugins:

package com.github.mdre.hgvaadinplugin

import org.gradle.api.Plugin;
import org.gradle.api.Project;
//import com.github.dkorotych.gradle.maven.exec.MavenExec;

class HGVaadinPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        println "Hybrid Gradle Vaaadin plugin."
        project.plugins.apply('com.github.dkorotych.gradle-maven-exec')
        // project.getPluginManager().apply('gradle-maven-exec-plugin')

        project.task('prepareFrontEnd', type: MavenExec){
            dependsOn build
            doLast {
                goal 'vaadin:prepare-frontend'
            }
        }
    }
}

If I try to import the class MavenExec I get this error:

> Task :compileGroovy FAILED
startup failed:
/home/mdre/Proyectos/HGVaadinPlugin/src/main/groovy/com/github/mdre/hgvaadinplugin/HGVaadinPlugin.groovy: 5: unable to resolve class com.github.dkorotych.gradle.maven.exec.MavenExec
 @ line 5, column 1.
   import com.github.dkorotych.gradle.maven.exec.MavenExec;
   ^

and if I comment the import line, I get this error in the project that use the plugin:

What went wrong:
A problem occurred evaluating root project 'VaadinFlowLab'.

Failed to apply plugin [id 'com.github.mdre.hgvaadinplugin']
  No such property: MavenExec for class: com.github.mdre.hgvaadinplugin.HGVaadinPlugin

How could I do this?

Thanks.

Body:
Well, I fix it!

I forget to include the dependency class in the final jar. So all of I need was to add this to the build.config:

configurations {
    // configuration that holds jars to include in the jar
    extraLibs
}

dependencies {
    ....
    ....
    //necesario para crear un fatJar
    extraLibs "gradle.plugin.com.github.dkorotych.gradle.maven.exec:gradle-maven-exec-plugin:2.2.1"
    configurations.compile.extendsFrom(configurations.extraLibs)
}

jar {
    from {
        configurations.extraLibs.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

and now it is working!!


问:
Integrating Frontend (Vue.js, React and Angular) with Kafka as part of event driven architecture microservices
This is an architecture related question. I am exploring a new architecture/paradigm (real-time event driven) where the Frontend (could be vue.js, angular or react) calls multiple rest services that integrates with distributed streaming platform such as kafka.

I struggle to put this together. Reason below.

For simple operations on the Front end, which does not involve a state change, HTTP GET API calls would suffice - no need for Kafka.

For operations with state change, such as updating something, HTTP POST calls are required -- this is where Kafka might come in handy.

However, I also know of folks who have used websockets to resolve this.

How then can I leverage Kafka fully in relation to making the Frontend and the Backend a truly Event Driven Architecture?

答:
You would need a three tier app.

Kafka is your backend tier for data storage.

Some API layer exists to perform RPC. Kafka Streams Interactive queries could be used to create key-value store KTables for get-by-id type queries.

Your API layer also can run an active Kafka consumer thread which pushes messages into a websocket or as SSE messages.

Your web application will open and subscribe to the websocket and use JS to update the DOM.

User input on the site can send POST or GET back to the API.

The API layer will poll or push to (other) Kafka topics


答:
A simple method uses row_number():

```<code>select t.*
from (select t.*,
             row_number() over (partition by id
                                order by (case action when 'Checked' then 1 else 2 end) desc,
                                         timestamp desc
                               ) as seqnum
      from t
     ) t
where seqnum = 1;
</code>```

Title: Redshift get rows with highest priority and timestamp

Body:
I have a table in redshift with records as follows

+====+======+=========+============+
| Id | Book | Action  | Timestamp  |
+====+======+=========+============+
| 1  | ABC  | ADDED   | 1111111111 |
+----+------+---------+------------+
| 1  | ABC  | REMOVED | 2222222222 |
+----+------+---------+------------+
| 1  | ABC  | CHECKED | 3333333333 |
+----+------+---------+------------+
| 2  | XYZ  | ADDED   | 4444444444 |
+----+------+---------+------------+
| 2  | XYZ  | CHECKED | 5555555555 |
+----+------+---------+------------+
| 5  | DEF  | CHECKED | 6666666666 |
+----+------+---------+------------+
| 5  | DEF  | CHECKED | 7777777777 |
+====+======+=========+============+

What I want is to get single record for each book. In case of duplicates, prioritize by Action with CHECKED having the lowest rank, rest all actions will have same priority and then pick the most recent record.

Expected Output

+====+======+=========+============+
| Id | Book | Action  | Timestamp  |
+====+======+=========+============+
| 1  | ABC  | REMOVED | 2222222222 |
+----+------+---------+------------+
| 2  | XYZ  | ADDED   | 4444444444 |
+----+------+---------+------------+
| 5  | DEF  | CHECKED | 7777777777 |
+====+======+=========+============+

Body:
A simple method uses row_number():

select t.*
from (select t.*,
             row_number() over (partition by id
                                order by (case action when 'Checked' then 1 else 2 end) desc,
                                         timestamp desc
                               ) as seqnum
      from t
     ) t
where seqnum = 1;


问:
Using vuetify to determine different layouts for different screen sizes
I have a vue.js application and I'm using vuetify. I have a table that looks like this:

When I shrink the width of the viewport, it ends up looking like this:

I don't like this view. I'd prefer to have the dropdown be shoved under the row description and have the checkboxes stay aligned with the ones on the other rows, like this:

The problem is that the order of items in each row goes as follows: description, dropdown (if applicable to row), checkbox 1, checbox 2, checkbox 3. The only way I can see the dropdown falling below the description is if it's put at the end of the row. But can that be done with CSS below certain screen widths?

Here is my code:

```<code><v-card class="mb-3 px-3">
      <v-card-title class="px-0">
          <div class="headline">Items</div>
      </v-card-title>
      <v-container fluid pa-0>
      <v-layout row wrap py-3>
          <v-flex xs9 sm6 md9>
              <v-label>Item</v-label>
          </v-flex>
          <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 1</v-label></v-flex>
          <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 2</v-label></v-flex>
          <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 3</v-label></v-flex>
      </v-layout>
      <v-divider></v-divider>
      </v-container>
      <v-form>
        <v-card v-for="(item, index) in items" :key="index" :id="'index-' + index" flat>
            <v-container fluid pa-0>
                <v-layout row wrap align-center style="min-height: 80px;">
                    <v-flex xs12 sm6 :class="item.hasDropdown ? 'md5' : 'md9'"><p class="pt-3 pb-3 font-weight-medium">{{item.description}}</p></v-flex>
                    <v-flex md4 v-if="item.hasDropdown">
                      <v-select :items="dropdownOptions" v-model="dropdownSelection" outline label="dropdown" class="d-inline-block"></v-select>
                    </v-flex>
                    <v-flex xs4 sm2 md1><label class="hidden-sm-and-up">Col 1:</label><v-checkbox v-model="item.col1" class="checkbox"></v-checkbox></v-flex>
                    <v-flex xs4 sm2 md1><label class="hidden-sm-and-up">Col 2:</label><v-checkbox v-model="item.col2" class="checkbox"></v-checkbox></v-flex>
                    <v-flex xs4 sm2 md1><label class="hidden-sm-and-up">Col 3:</label><v-checkbox v-model="item.col3" class="checkbox"></v-checkbox></v-flex>
                </v-layout>
            </v-container>
            <v-divider v-if="index < items.length - 1"></v-divider>
        </v-card>
      </v-form>
    </v-card>
</code>```

You'll note that I'm using vuetify's flex classes such as sm2, md1, sm2, etc. These are great for adjusting the number of columns on different screen sizes, but is there something similar in vuetify for determining different layouts based on different screen sizes?

答:
You can utilize the order classes for this purpose. Just add order-lg/order-md etc according to your need. Here in your example i'm using order-md. Customize according to your needs. Here's how I have done it:

Instead of v-flex, you have to use v-col

for grid use md=9 style instead of md9

your page must have v-app at root level, otherwise this will not work.

.........................

```<code><v-card class="mb-3 px-3">
  <v-card-title class="px-0">
      <div class="headline">Items</div>
  </v-card-title>
  <v-container fluid pa-0>
    <v-layout row wrap py-3>
      <v-flex xs9 sm6 md9>
          <v-label>Item</v-label>
      </v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 1</v-label></v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 2</v-label></v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 3</v-label></v-flex>
  </v-layout>
  <v-divider></v-divider>
  </v-container>
  <v-form>
    <v-card v-for="(item, index) in items" :key="index" :id="'index-' + index" flat>
        <v-container fluid pa-0>
            <v-layout row wrap align-center style="min-height: 80px;">
                <v-col xs=12 sm=6 :md="item.hasDropdown ? '5' : '9'"><p class="pt-3 pb-3 font-weight-medium">{{item.description}}</p></v-col>
                <v-col xs=4 sm=2 md=1 order-md="2"><label class="hidden-sm-and-up">Col 1:</label><v-checkbox v-model="item.col1" class="checkbox"></v-checkbox></v-col>
                <v-col xs=4 sm=2 md=1 order-md="2"><label class="hidden-sm-and-up">Col 2:</label><v-checkbox v-model="item.col2" class="checkbox"></v-checkbox></v-col>
                <v-col xs=4 sm=2 md=1 order-md="2"><label class="hidden-sm-and-up">Col 3:</label><v-checkbox v-model="item.col3" class="checkbox"></v-checkbox></v-col>
                <v-col md=4 v-if="item.hasDropdown" order-md="1">
                  <v-select :items="dropdownOptions" v-model="dropdownSelection" outline label="dropdown" class="d-inline-block"></v-select>
                </v-col>
            </v-layout>
        </v-container>
        <v-divider v-if="index < items.length - 1"></v-divider>
    </v-card>
  </v-form>
</v-card>
</code>```

SOLUTION 2
Solution 1 is more like vuetifyish way to do the ordering. For plain css way:

```<code><v-card class="mb-3 px-3">
  <v-card-title class="px-0">
      <div class="headline">Items</div>
  </v-card-title>
  <v-container fluid pa-0>
  <v-layout row wrap py-3>
      <v-flex xs9 sm6 md9>
          <v-label>Item</v-label>
      </v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 1</v-label></v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 2</v-label></v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 3</v-label></v-flex>
  </v-layout>
  <v-divider></v-divider>
  </v-container>
  <v-form>
    <v-card v-for="(item, index) in items" :key="index" :id="'index-' + index" flat>
        <v-container fluid pa-0>
            <v-layout row wrap align-center style="min-height: 80px;">
                <v-flex xs12 sm6 :class="item.hasDropdown ? 'md5' : 'md9'"><p class="pt-3 pb-3 font-weight-medium">{{item.description}}</p></v-flex>
                <v-flex md4 v-if="item.hasDropdown" class="v-select">
                  <v-select :items="dropdownOptions" v-model="dropdownSelection" outline label="dropdown" class="d-inline-block"></v-select>
                </v-flex>
                <v-flex xs4 sm2 md1 class="v-chkbox"><label class="hidden-sm-and-up">Col 1:</label><v-checkbox v-model="item.col1" class="checkbox"></v-checkbox></v-flex>
                <v-flex xs4 sm2 md1 class="v-chkbox"><label class="hidden-sm-and-up">Col 2:</label><v-checkbox v-model="item.col2" class="checkbox"></v-checkbox></v-flex>
                <v-flex xs4 sm2 md1 class="v-chkbox"><label class="hidden-sm-and-up">Col 3:</label><v-checkbox v-model="item.col3" class="checkbox"></v-checkbox></v-flex>
            </v-layout>
        </v-container>
        <v-divider v-if="index < items.length - 1"></v-divider>
    </v-card>
  </v-form>
</v-card>
</code>```

And Here's the CSS:

```<code>.v-chkbox {
  order: 1;
}
.v-select {
  order: 2;
}
</code>```

*Don't forget the media query which I didn't add.

** To know more about css ordering check the MDN and CSS Tricks link.

Cheers :)

Body:
I have a vue.js application and I'm using vuetify. I have a table that looks like this:

When I shrink the width of the viewport, it ends up looking like this:

I don't like this view. I'd prefer to have the dropdown be shoved under the row description and have the checkboxes stay aligned with the ones on the other rows, like this:

The problem is that the order of items in each row goes as follows: description, dropdown (if applicable to row), checkbox 1, checbox 2, checkbox 3. The only way I can see the dropdown falling below the description is if it's put at the end of the row. But can that be done with CSS below certain screen widths?

Here is my code:

<v-card class="mb-3 px-3">
      <v-card-title class="px-0">

Items

      </v-card-title>
      <v-container fluid pa-0>
      <v-layout row wrap py-3>
          <v-flex xs9 sm6 md9>
              <v-label>Item</v-label>
          </v-flex>
          <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 1</v-label></v-flex>
          <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 2</v-label></v-flex>
          <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 3</v-label></v-flex>
      </v-layout>
      <v-divider></v-divider>
      </v-container>
      <v-form>
        <v-card v-for="(item, index) in items" :key="index" :id="'index-' + index" flat>
            <v-container fluid pa-0>
                <v-layout row wrap align-center style="min-height: 80px;">
                    <v-flex xs12 sm6 :class="item.hasDropdown ? 'md5' : 'md9'">
{{item.description}}
</v-flex>
                    <v-flex md4 v-if="item.hasDropdown">
                      <v-select :items="dropdownOptions" v-model="dropdownSelection" outline label="dropdown" class="d-inline-block"></v-select>
                    </v-flex>
                    <v-flex xs4 sm2 md1>Col 1:<v-checkbox v-model="item.col1" class="checkbox"></v-checkbox></v-flex>
                    <v-flex xs4 sm2 md1>Col 2:<v-checkbox v-model="item.col2" class="checkbox"></v-checkbox></v-flex>
                    <v-flex xs4 sm2 md1>Col 3:<v-checkbox v-model="item.col3" class="checkbox"></v-checkbox></v-flex>
                </v-layout>
            </v-container>
            <v-divider v-if="index < items.length - 1"></v-divider>
        </v-card>
      </v-form>
    </v-card>

You'll note that I'm using vuetify's flex classes such as sm2, md1, sm2, etc. These are great for adjusting the number of columns on different screen sizes, but is there something similar in vuetify for determining different layouts based on different screen sizes?

Body:
You can utilize the order classes for this purpose. Just add order-lg/order-md etc according to your need. Here in your example i'm using order-md. Customize according to your needs. Here's how I have done it:

Instead of v-flex, you have to use v-col

for grid use md=9 style instead of md9

your page must have v-app at root level, otherwise this will not work.

.........................

<v-card class="mb-3 px-3">
  <v-card-title class="px-0">
      <div class="headline">Items</div>
  </v-card-title>
  <v-container fluid pa-0>
    <v-layout row wrap py-3>
      <v-flex xs9 sm6 md9>
          <v-label>Item</v-label>
      </v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 1</v-label></v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 2</v-label></v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 3</v-label></v-flex>
  </v-layout>
  <v-divider></v-divider>
  </v-container>
  <v-form>
    <v-card v-for="(item, index) in items" :key="index" :id="'index-' + index" flat>
        <v-container fluid pa-0>
            <v-layout row wrap align-center style="min-height: 80px;">
                <v-col xs=12 sm=6 :md="item.hasDropdown ? '5' : '9'"><p class="pt-3 pb-3 font-weight-medium">{{item.description}}</p></v-col>
                <v-col xs=4 sm=2 md=1 order-md="2"><label class="hidden-sm-and-up">Col 1:</label><v-checkbox v-model="item.col1" class="checkbox"></v-checkbox></v-col>
                <v-col xs=4 sm=2 md=1 order-md="2"><label class="hidden-sm-and-up">Col 2:</label><v-checkbox v-model="item.col2" class="checkbox"></v-checkbox></v-col>
                <v-col xs=4 sm=2 md=1 order-md="2"><label class="hidden-sm-and-up">Col 3:</label><v-checkbox v-model="item.col3" class="checkbox"></v-checkbox></v-col>
                <v-col md=4 v-if="item.hasDropdown" order-md="1">
                  <v-select :items="dropdownOptions" v-model="dropdownSelection" outline label="dropdown" class="d-inline-block"></v-select>
                </v-col>
            </v-layout>
        </v-container>
        <v-divider v-if="index < items.length - 1"></v-divider>
    </v-card>
  </v-form>
</v-card>

SOLUTION 2
Solution 1 is more like vuetifyish way to do the ordering. For plain css way:

<v-card class="mb-3 px-3">
  <v-card-title class="px-0">
      <div class="headline">Items</div>
  </v-card-title>
  <v-container fluid pa-0>
  <v-layout row wrap py-3>
      <v-flex xs9 sm6 md9>
          <v-label>Item</v-label>
      </v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 1</v-label></v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 2</v-label></v-flex>
      <v-flex sm2 md1 class="text-xs-center hidden-xs-only"><v-label>Col 3</v-label></v-flex>
  </v-layout>
  <v-divider></v-divider>
  </v-container>
  <v-form>
    <v-card v-for="(item, index) in items" :key="index" :id="'index-' + index" flat>
        <v-container fluid pa-0>
            <v-layout row wrap align-center style="min-height: 80px;">
                <v-flex xs12 sm6 :class="item.hasDropdown ? 'md5' : 'md9'"><p class="pt-3 pb-3 font-weight-medium">{{item.description}}</p></v-flex>
                <v-flex md4 v-if="item.hasDropdown" class="v-select">
                  <v-select :items="dropdownOptions" v-model="dropdownSelection" outline label="dropdown" class="d-inline-block"></v-select>
                </v-flex>
                <v-flex xs4 sm2 md1 class="v-chkbox"><label class="hidden-sm-and-up">Col 1:</label><v-checkbox v-model="item.col1" class="checkbox"></v-checkbox></v-flex>
                <v-flex xs4 sm2 md1 class="v-chkbox"><label class="hidden-sm-and-up">Col 2:</label><v-checkbox v-model="item.col2" class="checkbox"></v-checkbox></v-flex>
                <v-flex xs4 sm2 md1 class="v-chkbox"><label class="hidden-sm-and-up">Col 3:</label><v-checkbox v-model="item.col3" class="checkbox"></v-checkbox></v-flex>
            </v-layout>
        </v-container>
        <v-divider v-if="index < items.length - 1"></v-divider>
    </v-card>
  </v-form>
</v-card>

And Here's the CSS:

.v-chkbox {
  order: 1;
}
.v-select {
  order: 2;
}

*Don't forget the media query which I didn't add.

** To know more about css ordering check the MDN and CSS Tricks link.

Cheers :)


问:
how to extract a column from a matrix in python without using any package
I want to find a sum of a column in a matrix without using any package.

```<code>a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
</code>```

If I want to extract a row I can write a[i] for ith row, but how to extract a particular column?

答:
You can access any element : </p>

```<code>def sumColumn(m, column):
    sum = 0
    for row in range(len(m)):
        sum += m[row][column]
    return sum

column = 1
print("The sum for column number", column, "is", sumColumn(matrix, column))
</code>```

Body:
I want to find a sum of a column in a matrix without using any package.

a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

If I want to extract a row I can write a[i] for ith row, but how to extract a particular column?

Body:
You can access any element :

def sumColumn(m, column):
    sum = 0
    for row in range(len(m)):
        sum += m[row][column]
    return sum

column = 1
print("The sum for column number", column, "is", sumColumn(matrix, column))


问:
Trying to Convert from decimal to binary and it is not working C#
```<code>{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Input decimal number to convert");
            int num = int.Parse(Console.ReadLine());
            int count = 0;
            int[] binary = { };
            while (num != 0)
            {
                int answer = num % 2;
                binary[count] = answer;
                count++;
                num /= 2;
                Console.WriteLine(num);
            }
            for (int i = binary.Length; i < binary.Length && i >= 0; i++)
            {
                Console.WriteLine(binary[i]);
            }
            Console.ReadLine();
        }
    }
}
</code>```

答:
"Not working" is not a programmer term. When asking questions on Stackoverflow, you should provide far more detail as to what exactly is going wrong.

Looks like there are a number of different issues with your code. Hard to know where to start. Here's how I would write my own C# code to convert an integer to a binary string:

```<code>StringBuilder builder = new StringBuilder();

if (num == 0)
{
    builder.Append('0');
}
else
{
    while (num != 0)
    {
        builder.Insert(0, (char)('0' + (num & 1)));
        num >>= 1;
    }
}

Console.WriteLine(builder.ToString());
</code>```

Body:
"Not working" is not a programmer term. When asking questions on Stackoverflow, you should provide far more detail as to what exactly is going wrong.

Looks like there are a number of different issues with your code. Hard to know where to start. Here's how I would write my own C# code to convert an integer to a binary string:

StringBuilder builder = new StringBuilder();

if (num == 0)
{
    builder.Append('0');
}
else
{
    while (num != 0)
    {
        builder.Insert(0, (char)('0' + (num & 1)));
        num >>= 1;
    }
}

Console.WriteLine(builder.ToString());


问:
Function Subtracts 1 when converting to base 2 on many numbers?
In my code, I have command line arguments, and they are being passed correctly. I am converting a base 2-10 number into base 10 using coefficient base exponent form. it works on many numbers, but many others don't work. It is noticeable with you convert base 10 numbers, 3 digits, to base 10.

This is my function:

```<code>int decimal(int inbase, int dig, int argc, char *argv[])
{

    int total = 0, place = dig - 1;

    for(int i = 0; i < dig; i++)
    {
        total = total + (argv[2][place] - '0')*pow(inbase, i);
        cout<<"Argv: "<<argv[2][place] - '0'<<endl;
        cout<<"Power: "<<pow(inbase, i)<<endl;
        cout<<"Total After: "<<total<<endl;
        place--;
    }

    return total;
}
</code>```

Argv[2] is being passed as a character sting, an example input at compiling this program is:
./a.exe 10 100 10
Expected output in base 10:
100
What I get:
99

答:
C++ does not have pow for integers: https://en.cppreference.com/w/cpp/numeric/math/pow

You are probably losing data somewhere in the midst of all the floating point / integer conversions.

Also, how about simply:

```<code>int total = 0;
for (int i = 0; i < len; ++i) {
    total = total * base + arr[i];
}
</code>```

or, with the variables you have:

```<code>int total = 0;
for (int i = 0; i < dig; ++i) {
    total = total * inbase + int(argv[2][i] - '0');
}
</code>```

Body:
In my code, I have command line arguments, and they are being passed correctly. I am converting a base 2-10 number into base 10 using coefficient base exponent form. it works on many numbers, but many others don't work. It is noticeable with you convert base 10 numbers, 3 digits, to base 10.

This is my function:

int decimal(int inbase, int dig, int argc, char *argv[])
{

    int total = 0, place = dig - 1;

    for(int i = 0; i < dig; i++)
    {
        total = total + (argv[2][place] - '0')*pow(inbase, i);
        cout<<"Argv: "<<argv[2][place] - '0'<<endl;
        cout<<"Power: "<<pow(inbase, i)<<endl;
        cout<<"Total After: "<<total<<endl;
        place--;
    }

    return total;
}

Argv[2] is being passed as a character sting, an example input at compiling this program is:
./a.exe 10 100 10
Expected output in base 10:
100
What I get:
99

Body:
C++ does not have pow for integers: https://en.cppreference.com/w/cpp/numeric/math/pow

You are probably losing data somewhere in the midst of all the floating point / integer conversions.

Also, how about simply:

int total = 0;
for (int i = 0; i < len; ++i) {
    total = total * base + arr[i];
}

or, with the variables you have:

int total = 0;
for (int i = 0; i < dig; ++i) {
    total = total * inbase + int(argv[2][i] - '0');
}


问:
MySQL find and update based on results from 2 tables
First off, please note that this is not answered in the question here:
MySQL update table based on another tables value
or indeed any other Stack question or answer that I could find!

I converted a forum on a website and now just need to repair the internal URL links on a few hundred of the posts.

Posts are found in the column post_content within the table xyz_posts

```<code>ID     post_content

1467  This is great https://example.com/index.php?topic=1234 I really like it
1468  Hello world
1469  Take a look https://example.com/index.php?topic=5678.0
</code>```

You can see the URLs are mostly buried in the post text.
Note that the example above can sometimes be written with topic=1234.0 at the end, although it is actually stored in the database as a value of 1234. I don't want to rewrite the url and accidentally keep the .0

Here's an example of how I need that table to look:

```<code>ID     post_content

1467  This is great https://example.com/finished-page/ I really like it
1468  Hello world
1469  Take a look https://example.com/another-page/
</code>```

So, the table xyz_converter maps the old topic number to the new post ID like this:

```<code>meta_key             meta_value     value_id

_bbp_old_topic_id    1234           15675
_bbp_old_reply_id    1234           17439

</code>```

Caveat here, the number 1234 also exists in this table for forum replies which we don't want, but the meta_key and value_id are different for those as shown. This SQL query works to get to the right one:

```<code>SELECT * FROM `xyz_converter` WHERE meta_key LIKE '_bbp_old_topic_id' AND `meta_value` LIKE '1234'
</code>```

Also in table xyz_posts we map the value_id mentioned above to the post's URL suffix like this:

```<code>ID        post_name

15675     finished-page
15676     another-page
</code>```

How do I construct a SQL query that will detect the meta_value in one table and then replace it with the correct final URL as mentioned?

PROCESS SUMMARY

Detect the URL in xyz_posts post_content

Extract the topic number from the URL (eg 1234). If it's 1234.0 then take just 1234

Convert it to a post number in found in xyz_converter value_id (eg 15675) ensuring it is found alongside _bbp_old_topic_id

Take the suffix of the URL in xyz_posts post_name (eg 'finished-page')

Rewrite the original URL to include the suffix (not forgetting the trailing slashes).

I'm using MySQL 5.7.29 and PHPMyAdmin.
I'm fairly new to SQL queries and a Regex noob, but willing to learn more!

答:
A solution that uses only MySQL commands and works in MySQL 5.7 could be like this.

If .0 is present only in the urls you could use a query like this to remove all occurences of .0 from post_content in xyz_posts.

```<code>UPDATE `xyz_posts` SET post_content=REPLACE(post_content,'.0 ',' ') WHERE post_content LIKE '%topic=%.0 %';
</code>```

Then you can use

```<code>CREATE TABLE temp_tbl
SELECT CONCAT('index.php?topic=',c.meta_value) as `find_value` ,p.post_name as `replace_value`
FROM `xyz_converter` c
INNER JOIN `xyz_posts` p ON c.value_id=p.id AND `meta_key`='_bbp_old_topic_id'
ORDER BY meta_value DESC;

UPDATE `xyz_posts` p
INNER JOIN  `temp_tbl` t ON p.post_content LIKE CONCAT('%',t.find_value,'%')
SET p.`post_content`=REPLACE(p.`post_content`,t.find_value,t.replace_value);
</code>```

The first command will create a temporary table where the first column will be the value that you want to find and replace like index.php?topic=1234 and the second column will be the value you want to be replace with like finished-page

The second command will replace posts_content in xyz_posts taking the first column from temp_tbl and replacing it with the second column.

Below an sql fiddle where you can see the solution in action

http://sqlfiddle.com/#!9/7bce8c

Of course you should first create a copy of your database and try these commands to ensure everything works fine before trying it in your production database.

Body:
First off, please note that this is not answered in the question here:
MySQL update table based on another tables value
or indeed any other Stack question or answer that I could find!

I converted a forum on a website and now just need to repair the internal URL links on a few hundred of the posts.

Posts are found in the column post_content within the table xyz_posts

ID     post_content

1467  This is great https://example.com/index.php?topic=1234 I really like it
1468  Hello world
1469  Take a look https://example.com/index.php?topic=5678.0

You can see the URLs are mostly buried in the post text.
Note that the example above can sometimes be written with topic=1234.0 at the end, although it is actually stored in the database as a value of 1234. I don't want to rewrite the url and accidentally keep the .0

Here's an example of how I need that table to look:

ID     post_content

1467  This is great https://example.com/finished-page/ I really like it
1468  Hello world
1469  Take a look https://example.com/another-page/

So, the table xyz_converter maps the old topic number to the new post ID like this:

meta_key             meta_value     value_id

_bbp_old_topic_id    1234           15675
_bbp_old_reply_id    1234           17439

Caveat here, the number 1234 also exists in this table for forum replies which we don't want, but the meta_key and value_id are different for those as shown. This SQL query works to get to the right one:

SELECT * FROM `xyz_converter` WHERE meta_key LIKE '_bbp_old_topic_id' AND `meta_value` LIKE '1234'

Also in table xyz_posts we map the value_id mentioned above to the post's URL suffix like this:

ID        post_name

15675     finished-page
15676     another-page

How do I construct a SQL query that will detect the meta_value in one table and then replace it with the correct final URL as mentioned?

PROCESS SUMMARY

Detect the URL in xyz_posts post_content

Extract the topic number from the URL (eg 1234). If it's 1234.0 then take just 1234

Convert it to a post number in found in xyz_converter value_id (eg 15675) ensuring it is found alongside _bbp_old_topic_id

Take the suffix of the URL in xyz_posts post_name (eg 'finished-page')

Rewrite the original URL to include the suffix (not forgetting the trailing slashes).

I'm using MySQL 5.7.29 and PHPMyAdmin.
I'm fairly new to SQL queries and a Regex noob, but willing to learn more!

Body:
A solution that uses only MySQL commands and works in MySQL 5.7 could be like this.

If .0 is present only in the urls you could use a query like this to remove all occurences of .0 from post_content in xyz_posts.

UPDATE `xyz_posts` SET post_content=REPLACE(post_content,'.0 ',' ') WHERE post_content LIKE '%topic=%.0 %';

Then you can use

CREATE TABLE temp_tbl
SELECT CONCAT('index.php?topic=',c.meta_value) as `find_value` ,p.post_name as `replace_value`
FROM `xyz_converter` c
INNER JOIN `xyz_posts` p ON c.value_id=p.id AND `meta_key`='_bbp_old_topic_id'
ORDER BY meta_value DESC;

UPDATE `xyz_posts` p
INNER JOIN  `temp_tbl` t ON p.post_content LIKE CONCAT('%',t.find_value,'%')
SET p.`post_content`=REPLACE(p.`post_content`,t.find_value,t.replace_value);

The first command will create a temporary table where the first column will be the value that you want to find and replace like index.php?topic=1234 and the second column will be the value you want to be replace with like finished-page

The second command will replace posts_content in xyz_posts taking the first column from temp_tbl and replacing it with the second column.

Below an sql fiddle where you can see the solution in action

http://sqlfiddle.com/#!9/7bce8c

Of course you should first create a copy of your database and try these commands to ensure everything works fine before trying it in your production database.


问:
Update / EXISTS or MERGE for better performance? Slow updating on big table (millions of records)
I need some help with some performance issues:

I have a table CONTRATOS with 27 millions of records. This table has multiple columns but the important ones are: CONTRATO, CODIGO_ORIGEN.

It can exist more than one CONTRATO for each CODIGO_ORIGEN so i need to do this:

```<code>SELECT DISTINCT
    CODIGO_ORIGEN,
    FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
FROM TABLE CONTRATOS;
</code>```

After this we have 6 millions of records, the good ones...

What i need to do is update the "NOT FOUND" records (CONTRATO) in the table CONTRATOS with the value 'E' on the column ESTADO.

At first, i tried to do it everything in one step (query):

```<code>UPDATE / NOT EXISTS METHOD
--------------------------

    UPDATE CONTRATOS C
    SET ESTADO = 'E'
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM
        (
            SELECT DISTINCT
                CODIGO_ORIGEN,
                FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
            FROM TABLE CONTRATOS
        ) C2
        WHERE C.CONTRATO = C2.MAX_CONTRATO
    );

MERGE METHOD
---------------

    MERGE INTO CONTRATOS C
    USING
    (
        SELECT DISTINCT
            CODIGO_ORIGEN,
            FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
        FROM TABLE CONTRATOS
    ) C2 ON (C.CONTRATO = C2.MAX_CONTRATO)
    WHEN MATCHED THEN UPDATE SET ESTADO = 'E';
</code>```

But after seeing that it was too slow (both methods) i tried to do it using a temporal table where i can insert the valid rows: TEMP_CONTRATOS

```<code>    Note: This point goes pretty fast (15 min)

    INSERT INTO TEMP_CONTRATOS (MAX_CONTRATO, CODIGO_ORIGEN)
    SELECT DISTINCT
            CODIGO_ORIGEN,
            FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
    FROM TABLE CONTRATOS;

    Note: Here is the problem again

    UPDATE CONTRATOS C
    SET ESTADO = 'E'
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM TEMP_CONTRATOS TMP
        WHERE C.CONTRATO = TMP.MAX_CONTRATO
    );
</code>```

I have an index on both tables with the columns (CONTRATO/MAX_CONTRATO and CODIGO_ORIGEN) so i can improve the performance (right?) but im still getting too slow results...

The execution plan gives me over 700.000 of cost for 27 millions of records... Is it too much or is it ok considering the amount of records? It´s doing a TABLE FULL SCAN of both tables.

Is it a good idea using hints? is it a good idea going through indexes?... What is the best option? using Merge or Exists/Not exists / Not in??

Also, i´m not sure about creating an index for the ESTADO column because im updating that field and i read it´s not a good idea to create a index in a column where you perform updates... but i have to do a lot of queries joining with it.

Im using the V$SESSION_LONGOPS view and the session view of the sysdba user  to monitorize the process... Any better alternative?

I don´t know if i forget something important, i guess i do.

Bring me some light please. Any advice is appreciated.

Thank you in advance

Regards.

答:
Let me try and explain my thinking using the standard EMP table.

The principle is that rather than updating 20M rows out of 27M, it will be more efficient to recreate the 27M row table with the correct data. A very trivial example of this "modification to transformation" would be something like:

```<code>update emp
set sal=sal*1.1
where deptno=20
</code>```

becomes

```<code>create table empnew as
select empno, ename, job, mgr, hiredate, comm, deptno
  , case when deptno=20 then sal*1.1
         else sal
    end as sal
from emp
</code>```

Then you rename the tables.

In your example, you are looking for "missing" rows. A technique for this is to use an outer join and the look for NULLs in the key.

So if I have a copy of the emp table called tempemp, then I could write a query something like:

```<code>select nvl( t.deptno, -1 ) status, t.*, e.*
from emp e
left join
    ( select distinct deptno
    , first_value( hiredate ) over (partition by deptno order by sal ) fv
    from tempemp ) t
on t.fv = e.hiredate
</code>```

Here I am detecting the "missing" values and setting the status column to -1.

In your case, I think you can write your query something like

```<code>select nvl( c1.contracto, 'E' ) estado, c2.*, c1.*
from CONTRATOS c1
left join
    ( SELECT DISTINCT
                CODIGO_ORIGEN,
                FIRST_VALUE(CONTRATO)
                OVER (PARTITION BY CODIGO_ORIGEN
                      ORDER BY FECHA DESC) MAX_CONTRATO
            FROM  CONTRATOS
     ) c2
on C.CONTRATO = C2.MAX_CONTRATO
</code>```

If this is correct, then you can turn this into a CREATE TABLE AS (CTAS) statement. At this point, you can then take advantage of parallel execution, direct path loading and nologging.

I hope this is helpful

Body:
I need some help with some performance issues:

I have a table CONTRATOS with 27 millions of records. This table has multiple columns but the important ones are: CONTRATO, CODIGO_ORIGEN.

It can exist more than one CONTRATO for each CODIGO_ORIGEN so i need to do this:

SELECT DISTINCT
    CODIGO_ORIGEN,
    FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
FROM TABLE CONTRATOS;

After this we have 6 millions of records, the good ones...

What i need to do is update the "NOT FOUND" records (CONTRATO) in the table CONTRATOS with the value 'E' on the column ESTADO.

At first, i tried to do it everything in one step (query):

UPDATE / NOT EXISTS METHOD
--------------------------

    UPDATE CONTRATOS C
    SET ESTADO = 'E'
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM
        (
            SELECT DISTINCT
                CODIGO_ORIGEN,
                FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
            FROM TABLE CONTRATOS
        ) C2
        WHERE C.CONTRATO = C2.MAX_CONTRATO
    );

MERGE METHOD
---------------

    MERGE INTO CONTRATOS C
    USING
    (
        SELECT DISTINCT
            CODIGO_ORIGEN,
            FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
        FROM TABLE CONTRATOS
    ) C2 ON (C.CONTRATO = C2.MAX_CONTRATO)
    WHEN MATCHED THEN UPDATE SET ESTADO = 'E';

But after seeing that it was too slow (both methods) i tried to do it using a temporal table where i can insert the valid rows: TEMP_CONTRATOS

    Note: This point goes pretty fast (15 min)

    INSERT INTO TEMP_CONTRATOS (MAX_CONTRATO, CODIGO_ORIGEN)
    SELECT DISTINCT
            CODIGO_ORIGEN,
            FIRST_VALUE(CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY FECHA DESC) MAX_CONTRATO
    FROM TABLE CONTRATOS;

    Note: Here is the problem again

    UPDATE CONTRATOS C
    SET ESTADO = 'E'
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM TEMP_CONTRATOS TMP
        WHERE C.CONTRATO = TMP.MAX_CONTRATO
    );

I have an index on both tables with the columns (CONTRATO/MAX_CONTRATO and CODIGO_ORIGEN) so i can improve the performance (right?) but im still getting too slow results...

The execution plan gives me over 700.000 of cost for 27 millions of records... Is it too much or is it ok considering the amount of records? It´s doing a TABLE FULL SCAN of both tables.

Is it a good idea using hints? is it a good idea going through indexes?... What is the best option? using Merge or Exists/Not exists / Not in??

Also, i´m not sure about creating an index for the ESTADO column because im updating that field and i read it´s not a good idea to create a index in a column where you perform updates... but i have to do a lot of queries joining with it.

Im using the V$SESSION_LONGOPS view and the session view of the sysdba user  to monitorize the process... Any better alternative?

I don´t know if i forget something important, i guess i do.

Bring me some light please. Any advice is appreciated.

Thank you in advance

Regards.

Body:
Let me try and explain my thinking using the standard EMP table.

The principle is that rather than updating 20M rows out of 27M, it will be more efficient to recreate the 27M row table with the correct data. A very trivial example of this "modification to transformation" would be something like:

update emp
set sal=sal*1.1
where deptno=20

becomes

create table empnew as
select empno, ename, job, mgr, hiredate, comm, deptno
  , case when deptno=20 then sal*1.1
         else sal
    end as sal
from emp

Then you rename the tables.

In your example, you are looking for "missing" rows. A technique for this is to use an outer join and the look for NULLs in the key.

So if I have a copy of the emp table called tempemp, then I could write a query something like:

select nvl( t.deptno, -1 ) status, t.*, e.*
from emp e
left join
    ( select distinct deptno
    , first_value( hiredate ) over (partition by deptno order by sal ) fv
    from tempemp ) t
on t.fv = e.hiredate

Here I am detecting the "missing" values and setting the status column to -1.

In your case, I think you can write your query something like

select nvl( c1.contracto, 'E' ) estado, c2.*, c1.*
from CONTRATOS c1
left join
    ( SELECT DISTINCT
                CODIGO_ORIGEN,
                FIRST_VALUE(CONTRATO)
                OVER (PARTITION BY CODIGO_ORIGEN
                      ORDER BY FECHA DESC) MAX_CONTRATO
            FROM  CONTRATOS
     ) c2
on C.CONTRATO = C2.MAX_CONTRATO

If this is correct, then you can turn this into a CREATE TABLE AS (CTAS) statement. At this point, you can then take advantage of parallel execution, direct path loading and nologging.

I hope this is helpful


答:
There you go. (edited)

ls -dt */ | tail -n +11 | xargs rm -rf

First list directories recently modified then take all of them except first 10, then send them to rm -rf.

Title: Linux - Save only recent 10 folders and delete the rest

Body:
I have a folder that contains versions of my application, each time I upload a new version a new sub-folder is created for it, the sub-folder name is the current timestamp, here is a printout of the main folder used (ls -l |grep ^d):

drwxrwxr-x 7 root root 4096 2011-03-31 16:18 20110331161649
drwxrwxr-x 7 root root 4096 2011-03-31 16:21 20110331161914
drwxrwxr-x 7 root root 4096 2011-03-31 16:53 20110331165035
drwxrwxr-x 7 root root 4096 2011-03-31 16:59 20110331165712
drwxrwxr-x 7 root root 4096 2011-04-03 20:18 20110403201607
drwxrwxr-x 7 root root 4096 2011-04-03 20:38 20110403203613
drwxrwxr-x 7 root root 4096 2011-04-04 14:39 20110405143725
drwxrwxr-x 7 root root 4096 2011-04-06 15:24 20110406151805
drwxrwxr-x 7 root root 4096 2011-04-06 15:36 20110406153157
drwxrwxr-x 7 root root 4096 2011-04-06 16:02 20110406155913
drwxrwxr-x 7 root root 4096 2011-04-10 21:10 20110410210928
drwxrwxr-x 7 root root 4096 2011-04-10 21:50 20110410214939
drwxrwxr-x 7 root root 4096 2011-04-10 22:15 20110410221414
drwxrwxr-x 7 root root 4096 2011-04-11 22:19 20110411221810
drwxrwxr-x 7 root root 4096 2011-05-01 21:30 20110501212953
drwxrwxr-x 7 root root 4096 2011-05-01 23:02 20110501230121
drwxrwxr-x 7 root root 4096 2011-05-03 21:57 20110503215252
drwxrwxr-x 7 root root 4096 2011-05-06 16:17 20110506161546
drwxrwxr-x 7 root root 4096 2011-05-11 10:00 20110511095709
drwxrwxr-x 7 root root 4096 2011-05-11 10:13 20110511100938
drwxrwxr-x 7 root root 4096 2011-05-12 14:34 20110512143143
drwxrwxr-x 7 root root 4096 2011-05-13 22:13 20110513220824
drwxrwxr-x 7 root root 4096 2011-05-14 22:26 20110514222548
drwxrwxr-x 7 root root 4096 2011-05-14 23:03 20110514230258

I'm looking for a command that will leave the last 10 versions (sub-folders) and deletes the rest.

Any thoughts?


问:
PG::InsufficientPrivilege: ERROR: must be owner of database
Good morning!

Faced with the problem that when you run the tests, swears that the error with the database owner, but just before given privileges to the user at the database with the tests, please tell me where to dig.

The test itself takes place, but before it pops up this error, username and database match the settings in the database.yml

I found a similar article, but I have another error, and this decision does not apply: ActiveRecord::StatementInvalid: PG::Error: ERROR: must be owner of database

Error Code: PG :: InsufficientPrivilege: ERROR: must be owner of database test

System:

Rails: 5.0.0

Ruby: 2.3.1

PSQL: 9.5.3

答:
Had the same issue.
My solution was just to do what Postgres says:</p>

```<code>ALTER ROLE user1 WITH CREATEDB;

# ALTER DATABASE name OWNER TO new_owner;
</code>```

Body:
Had the same issue.
My solution was just to do what Postgres says:

ALTER ROLE user1 WITH CREATEDB;

# ALTER DATABASE name OWNER TO new_owner;


问:
Getting unresolved identifier error while building firebase login
I am getting unresolved identifier error for the email and password variables. Here is the code for the view controller, I think it's an issue with the curly brackets and where they are placed but have messed with it for a little while and can't figure it out. I am trying to get it so when the user enters their email/password it sends the string to the database so they can use it to log in in the future.</p>

```<code>import UIKit
import FirebaseAuth
import Firebase

class SignUpViewController: UIViewController {

    @IBOutlet weak var FirstNameTextField: UITextField!
    @IBOutlet weak var LastNameTextField: UITextField!
    @IBOutlet weak var EmailTextField: UITextField!
    @IBOutlet weak var PasswordTextField: UITextField!
    @IBOutlet weak var SignUpButton: UIButton!
    @IBOutlet weak var ErrorLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

         setUpElements()
        // Do any additional setup after loading the view.
    }

    func setUpElements() {

        //Hide error label
        ErrorLabel.alpha = 0

        //Style the elements
        Utilities.styleTextField(FirstNameTextField)

        Utilities.styleTextField(LastNameTextField)

        Utilities.styleTextField(EmailTextField)

        Utilities.styleTextField(PasswordTextField)

        Utilities.styleFilledButton(SignUpButton)

    }

    func Validatefields () -> String? {
        //Check that all fields are filled in
        if FirstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           LastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           EmailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           PasswordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {

            return "Please fill in all fields."
        }

        //Check if the password is secure
        let cleanedPassword = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

        if Utilities.isPasswordValid(cleanedPassword) == false {

            //password isn't secure enough
            return "Please make sure your password is at least 8 characters, contains a special character and a number."

        }

        return nil
    }

    @IBAction func SignUpTapped(_ sender: Any) {
        //Validate Fields
        let error = Validatefields()

        if error != nil {
            //something wrong with fields
           showError(error!)

        }

        else {

            //Create User
            Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
                //Check for errors
                if err != nil {

                    //there was an error
                    self.showError("Error Creating User")

                }
                else {
                    // Create cleaned (No white spaces) version of data
                    let Firstname = FirstNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let LastName = LastNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let email2 = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let password2 = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

                    //User was successfully created
                    let db = Firestore.firestore()

                    db.collection("users").addDocument(data: ["Firstname":firstName,"LastName":lastName, "uid": result!.user.uid ])  {(error) in

                        if error != nil {
                            //Show error message
                            self.showError("User FirstName and Lastname couldn't be saved, You should still be able to log in.")

                        }

                    }
                    //Transition to home screen
                    func Transitiontohome () {

                let homeViewController = storyboard?.instantiateViewController(identifier:Constants.Storyboard.homeViewController) as?
                    HomeViewController

                        view.window?.rootViewController = homeViewController
                        view.window?.makeKeyAndVisible()
                    }

            }

        }

    }

    }
    func showError (_ message:String) {
    ErrorLabel.text = message
    ErrorLabel.alpha = 1
}
}
</code>```

答:
Hmmm, I'm having a hard time finding out exactly where the error is. My first thought is let db = might not be right. I've included my code for you to try...

```<code>     // SIGN UP FUNCTION, first name, last name, email, password
let db = Database.database().reference()
func signUp(firstName: String, lastName: String, email: String, password: String, completion: @escaping (LocalUser?, Error?) -> Void) {
    let usersRef = db.child("users")
    Auth.auth().createUser(withEmail: email, password: password) {[weak self] (result, error) in

        if let uid = result?.user.uid {
            let newUser: [String: String] = ["firstName": firstName, "lastName": lastName, "email": email]
            let newLocalUser = LocalUser(firstName: firstName, lastName: lastName, email: email)
            usersRef.child(uid).setValue(newUser){(error: Error?, ref: DatabaseReference) in
                completion(newLocalUser, error)
            }
        } else {
            completion(nil, nil)
        }
    }
}
</code>```

^^^ This code is in a Swift file called "Firebase Functions" — however, in the sign up screen itself "signupViewController" I have this code (I'm not seeing this in your code, and this is the feature that properly saves your data through the acitivityIndicator)

```<code>    // Create the user, process data and go to next View Controller
    activityIndicator.startAnimating()
    firebaseServer.signUp(firstName: firstName, lastName: lastName, email: email, password: password) {[weak self] (user, error) in
        self?.activityIndicator.stopAnimating()
        if let user = user {
            newUser = user
        }

        if(error == nil) {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let signupVC = storyboard.instantiateViewController(identifier: "introductionTextViewController")
                self?.navigationController?.pushViewController(signupVC, animated: true)

        } else {
            print("An error occured")
        }
    }
</code>```

Does this all make sense?? My GitHub has all of this code, so feel free to take what might help! https://github.com/kcapretta/RadiusSocialNetworkingApp

Body:
I am getting unresolved identifier error for the email and password variables. Here is the code for the view controller, I think it's an issue with the curly brackets and where they are placed but have messed with it for a little while and can't figure it out. I am trying to get it so when the user enters their email/password it sends the string to the database so they can use it to log in in the future.

import UIKit
import FirebaseAuth
import Firebase

class SignUpViewController: UIViewController {

    @IBOutlet weak var FirstNameTextField: UITextField!
    @IBOutlet weak var LastNameTextField: UITextField!
    @IBOutlet weak var EmailTextField: UITextField!
    @IBOutlet weak var PasswordTextField: UITextField!
    @IBOutlet weak var SignUpButton: UIButton!
    @IBOutlet weak var ErrorLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

         setUpElements()
        // Do any additional setup after loading the view.
    }

    func setUpElements() {

        //Hide error label
        ErrorLabel.alpha = 0

        //Style the elements
        Utilities.styleTextField(FirstNameTextField)

        Utilities.styleTextField(LastNameTextField)

        Utilities.styleTextField(EmailTextField)

        Utilities.styleTextField(PasswordTextField)

        Utilities.styleFilledButton(SignUpButton)

    }

    func Validatefields () -> String? {
        //Check that all fields are filled in
        if FirstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           LastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           EmailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           PasswordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {

            return "Please fill in all fields."
        }

        //Check if the password is secure
        let cleanedPassword = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

        if Utilities.isPasswordValid(cleanedPassword) == false {

            //password isn't secure enough
            return "Please make sure your password is at least 8 characters, contains a special character and a number."

        }

        return nil
    }

    @IBAction func SignUpTapped(_ sender: Any) {
        //Validate Fields
        let error = Validatefields()

        if error != nil {
            //something wrong with fields
           showError(error!)

        }

        else {

            //Create User
            Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
                //Check for errors
                if err != nil {

                    //there was an error
                    self.showError("Error Creating User")

                }
                else {
                    // Create cleaned (No white spaces) version of data
                    let Firstname = FirstNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let LastName = LastNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let email2 = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let password2 = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

                    //User was successfully created
                    let db = Firestore.firestore()

                    db.collection("users").addDocument(data: ["Firstname":firstName,"LastName":lastName, "uid": result!.user.uid ])  {(error) in

                        if error != nil {
                            //Show error message
                            self.showError("User FirstName and Lastname couldn't be saved, You should still be able to log in.")

                        }

                    }
                    //Transition to home screen
                    func Transitiontohome () {

                let homeViewController = storyboard?.instantiateViewController(identifier:Constants.Storyboard.homeViewController) as?
                    HomeViewController

                        view.window?.rootViewController = homeViewController
                        view.window?.makeKeyAndVisible()
                    }

            }

        }

    }

    }
    func showError (_ message:String) {
    ErrorLabel.text = message
    ErrorLabel.alpha = 1
}
}

Body:
Hmmm, I'm having a hard time finding out exactly where the error is. My first thought is let db = might not be right. I've included my code for you to try...

     // SIGN UP FUNCTION, first name, last name, email, password
let db = Database.database().reference()
func signUp(firstName: String, lastName: String, email: String, password: String, completion: @escaping (LocalUser?, Error?) -> Void) {
    let usersRef = db.child("users")
    Auth.auth().createUser(withEmail: email, password: password) {[weak self] (result, error) in

        if let uid = result?.user.uid {
            let newUser: [String: String] = ["firstName": firstName, "lastName": lastName, "email": email]
            let newLocalUser = LocalUser(firstName: firstName, lastName: lastName, email: email)
            usersRef.child(uid).setValue(newUser){(error: Error?, ref: DatabaseReference) in
                completion(newLocalUser, error)
            }
        } else {
            completion(nil, nil)
        }
    }
}

^^^ This code is in a Swift file called "Firebase Functions" — however, in the sign up screen itself "signupViewController" I have this code (I'm not seeing this in your code, and this is the feature that properly saves your data through the acitivityIndicator)

    // Create the user, process data and go to next View Controller
    activityIndicator.startAnimating()
    firebaseServer.signUp(firstName: firstName, lastName: lastName, email: email, password: password) {[weak self] (user, error) in
        self?.activityIndicator.stopAnimating()
        if let user = user {
            newUser = user
        }

        if(error == nil) {
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let signupVC = storyboard.instantiateViewController(identifier: "introductionTextViewController")
                self?.navigationController?.pushViewController(signupVC, animated: true)

        } else {
            print("An error occured")
        }
    }

Does this all make sense?? My GitHub has all of this code, so feel free to take what might help! https://github.com/kcapretta/RadiusSocialNetworkingApp