问:
How to solve Prometheus chart Ingres/Service mapping?
Just installed stable/prometheus chart with below values and I'm able to access the server frontend from pods but not from host's web browser.

My values.yaml:

```<code>alertmanager:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - localhost/alerts

server:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - localhost/prom

pushgateway:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - localhost/push
</code>```

I use nginx ingress and ingresses get created but for some unknown reason, it doesn't seem to map to the service.

Some data:

I'm able to access the server from ingress pods (also all others) via default and dns service names:

```<code>kubectl exec -it nginx-ingress-controller-5cb489cd48-t4dgv -- sh
/etc/nginx $ curl prometheus-server.default.svc.cluster.local
<a href="/graph">Found</a>

/etc/nginx $ curl prometheus-server
<a href="/graph">Found</a>
</code>```

List of active ingresses created by the chart:

```<code>kubectl get ingress
NAME                      HOSTS       ADDRESS     PORTS   AGE
nginx-ingress             localhost   localhost   80      37h
prometheus-alertmanager   localhost   localhost   80      43m
prometheus-pushgateway    localhost   localhost   80      43m
prometheus-server         localhost   localhost   80      43m
</code>```

List of active service resources:

```<code>kubectl get svc
NAME                            TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
kubernetes                      ClusterIP      10.96.0.1        <none>        443/TCP                      37h
nginx-deployment                ClusterIP      10.100.1.167     <none>        80/TCP                       37h
nginx-ingress-controller        LoadBalancer   10.109.57.131    localhost     80:32382/TCP,443:30669/TCP   36h
nginx-ingress-default-backend   ClusterIP      10.107.91.35     <none>        80/TCP                       36h
php-deployment                  ClusterIP      10.105.73.26     <none>        9000/TCP                     37h
prometheus-alertmanager         ClusterIP      10.97.89.149     <none>        80/TCP                       44m
prometheus-kube-state-metrics   ClusterIP      None             <none>        80/TCP,81/TCP                44m
prometheus-node-exporter        ClusterIP      None             <none>        9100/TCP                     44m
prometheus-pushgateway          ClusterIP      10.105.81.111    <none>        9091/TCP                     44m
prometheus-server               ClusterIP      10.108.225.187   <none>        80/TCP                       44m
</code>```

On the other hand, if I declare subdomain as an ingress host, Prometheus is accessible:

```<code>alertmanager:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - alerts.localhost

server:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - prom.localhost

pushgateway:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - push.localhost
</code>```

Am I doing something wrong or there's some sort of issue with this?
Any suggestions?

Thanks in advance!

Version of Helm and Kubernetes:
Helm 3.0.3 / Kubernetes 1.15.5 (Docker for Mac, MacOS Catalina)

答:
I reproduced your scenario and by running some tests I understood that this is not going to work in the way you want it to work. This is not the right way to implement it.

Let's dive into it a bit.

You can add nginx.ingress.kubernetes.io/rewrite-target in your ingresses as in this example:

```<code>$ kubectl get ingresses. myprom-prometheus-pushgateway -oyaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /
  creationTimestamp: "2020-02-18T09:51:32Z"
  generation: 1
  labels:
    app: prometheus
    chart: prometheus-10.4.0
    component: pushgateway
    heritage: Helm
    release: myprom
  name: myprom-prometheus-pushgateway
  namespace: default
  resourceVersion: "3239"
  selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/myprom-prometheus-pushgateway
  uid: 499372f4-52b1-4b37-982c-b52e70657d37
spec:
  rules:
  - host: localhost
    http:
      paths:
      - backend:
          serviceName: myprom-prometheus-pushgateway
          servicePort: 9091
        path: /push
status:
  loadBalancer:
    ingress:
    - ip: 192.168.39.251
</code>```

After adding this, you are going to be capable to access as you intended. Unfortunately after doing this you're going to face a new problem. If we inspect the html output from a curl command we can see this:

```<code><!DOCTYPE html>

<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="robots" content="noindex,nofollow">
    <title>Prometheus Pushgateway</title>

    <link rel="shortcut icon" href="/static/favicon.ico?v=793293bdadd51fdaca69de5bb25637b0f93b656b">

    <script src="/static/jquery-3.4.1.min.js?v=793293bdadd51fdaca69de5bb25637b0f93b656b"></script>
    <script src="/static/bootstrap-4.3.1-dist/js/bootstrap.min.js?v=793293bdadd51fdaca69de5bb25637b0f93b656b"></script>
    <script src="/static/functions.js?v=793293bdadd51fdaca69de5bb25637b0f93b656b"></script>

    <link type="text/css" rel="stylesheet" href="/static/bootstrap-4.3.1-dist/css/bootstrap.min.css?v=793293bdadd51fdaca69de5bb25637b0f93b656b">
    <link type="text/css" rel="stylesheet" href="/static/prometheus.css?v=793293bdadd51fdaca69de5bb25637b0f93b656b">
    <link type="text/css" rel="stylesheet" href="/static/bootstrap4-glyphicons/css/bootstrap-glyphicons.min.css?v=793293bdadd51fdaca69de5bb25637b0f93b656b">
  </head>
</code>```

As can be seen, we have /static/jquery-3.4.1.min.js for example, so this is going to redirect your browser to a different location. The problem is that you don't have this location.

That's why i suggest you to avoid using path and stick tom your secondary solution that involves using a sub-domain.

```<code>alertmanager:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - alerts.localhost

server:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - prom.localhost

pushgateway:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - push.localhost
</code>```

Body:
Just installed stable/prometheus chart with below values and I'm able to access the server frontend from pods but not from host's web browser.

My values.yaml:

alertmanager:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - localhost/alerts

server:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - localhost/prom

pushgateway:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - localhost/push

I use nginx ingress and ingresses get created but for some unknown reason, it doesn't seem to map to the service.

Some data:

I'm able to access the server from ingress pods (also all others) via default and dns service names:

kubectl exec -it nginx-ingress-controller-5cb489cd48-t4dgv -- sh
/etc/nginx $ curl prometheus-server.default.svc.cluster.local
Found

/etc/nginx $ curl prometheus-server
Found

List of active ingresses created by the chart:

kubectl get ingress
NAME                      HOSTS       ADDRESS     PORTS   AGE
nginx-ingress             localhost   localhost   80      37h
prometheus-alertmanager   localhost   localhost   80      43m
prometheus-pushgateway    localhost   localhost   80      43m
prometheus-server         localhost   localhost   80      43m

List of active service resources:

kubectl get svc
NAME                            TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                      AGE
kubernetes                      ClusterIP      10.96.0.1        <none>        443/TCP                      37h
nginx-deployment                ClusterIP      10.100.1.167     <none>        80/TCP                       37h
nginx-ingress-controller        LoadBalancer   10.109.57.131    localhost     80:32382/TCP,443:30669/TCP   36h
nginx-ingress-default-backend   ClusterIP      10.107.91.35     <none>        80/TCP                       36h
php-deployment                  ClusterIP      10.105.73.26     <none>        9000/TCP                     37h
prometheus-alertmanager         ClusterIP      10.97.89.149     <none>        80/TCP                       44m
prometheus-kube-state-metrics   ClusterIP      None             <none>        80/TCP,81/TCP                44m
prometheus-node-exporter        ClusterIP      None             <none>        9100/TCP                     44m
prometheus-pushgateway          ClusterIP      10.105.81.111    <none>        9091/TCP                     44m
prometheus-server               ClusterIP      10.108.225.187   <none>        80/TCP                       44m

On the other hand, if I declare subdomain as an ingress host, Prometheus is accessible:

alertmanager:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - alerts.localhost

server:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - prom.localhost

pushgateway:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - push.localhost

Am I doing something wrong or there's some sort of issue with this?
Any suggestions?

Thanks in advance!

Version of Helm and Kubernetes:
Helm 3.0.3 / Kubernetes 1.15.5 (Docker for Mac, MacOS Catalina)

Body:
I reproduced your scenario and by running some tests I understood that this is not going to work in the way you want it to work. This is not the right way to implement it.

Let's dive into it a bit.

You can add nginx.ingress.kubernetes.io/rewrite-target in your ingresses as in this example:

$ kubectl get ingresses. myprom-prometheus-pushgateway -oyaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /
  creationTimestamp: "2020-02-18T09:51:32Z"
  generation: 1
  labels:
    app: prometheus
    chart: prometheus-10.4.0
    component: pushgateway
    heritage: Helm
    release: myprom
  name: myprom-prometheus-pushgateway
  namespace: default
  resourceVersion: "3239"
  selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/myprom-prometheus-pushgateway
  uid: 499372f4-52b1-4b37-982c-b52e70657d37
spec:
  rules:
  - host: localhost
    http:
      paths:
      - backend:
          serviceName: myprom-prometheus-pushgateway
          servicePort: 9091
        path: /push
status:
  loadBalancer:
    ingress:
    - ip: 192.168.39.251

After adding this, you are going to be capable to access as you intended. Unfortunately after doing this you're going to face a new problem. If we inspect the html output from a curl command we can see this:

<!DOCTYPE html>

<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="robots" content="noindex,nofollow">
    <title>Prometheus Pushgateway</title>

    <link rel="shortcut icon" href="/static/favicon.ico?v=793293bdadd51fdaca69de5bb25637b0f93b656b">

    <script src="/static/jquery-3.4.1.min.js?v=793293bdadd51fdaca69de5bb25637b0f93b656b"></script>
    <script src="/static/bootstrap-4.3.1-dist/js/bootstrap.min.js?v=793293bdadd51fdaca69de5bb25637b0f93b656b"></script>
    <script src="/static/functions.js?v=793293bdadd51fdaca69de5bb25637b0f93b656b"></script>

    <link type="text/css" rel="stylesheet" href="/static/bootstrap-4.3.1-dist/css/bootstrap.min.css?v=793293bdadd51fdaca69de5bb25637b0f93b656b">
    <link type="text/css" rel="stylesheet" href="/static/prometheus.css?v=793293bdadd51fdaca69de5bb25637b0f93b656b">
    <link type="text/css" rel="stylesheet" href="/static/bootstrap4-glyphicons/css/bootstrap-glyphicons.min.css?v=793293bdadd51fdaca69de5bb25637b0f93b656b">
  </head>

As can be seen, we have /static/jquery-3.4.1.min.js for example, so this is going to redirect your browser to a different location. The problem is that you don't have this location.

That's why i suggest you to avoid using path and stick tom your secondary solution that involves using a sub-domain.

alertmanager:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - alerts.localhost

server:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - prom.localhost

pushgateway:
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: nginx
    hosts:
      - push.localhost


来源: stackexchange

问:
How to select the members who has transacted on the last date of every month from a large data
I have data of members who have transacted everyday, I need list of all the members who have transacted on the last date of each month for the whole year.

My output needs to have a list of members (with all the columns) who have transacted on 31-Jan-2019, 28-Feb-2019 and so on upto 31-Dec-2019.

答:
```<code>month.ends <- as.Date(paste(unique(year(df$date)), unique(month(df$date)), "01", sep = "-"))-1

df %>% filter(date %in% month.ends)
</code>```

If you want just the unique member names with some other columns you can use the distinct function

ContentLicense: CC BY-SA 4.0

Body:
month.ends <- as.Date(paste(unique(year(df$date)), unique(month(df$date)), "01", sep = "-"))-1

df %>% filter(date %in% month.ends)

If you want just the unique member names with some other columns you can use the distinct function


问:
Run two scripts simultaneously in tkinter
I need two scripts two run simultaneously on click of a single button. Cannot use two buttons because the gui freezes after the first button click and waits for the first program to finish.
Here's the code:</p>

```<code>import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")

def clicked():
     os.system('python inference.py')
     os.system('python extract_frames.py')

    # I used the subprocess approach also but it still waits for the first program to finish

    subprocess.run("python inference.py  & python extract_frames.py",shell=True)

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()
</code>```

答:
You can use two subprocess.Popen(...) to run the two scripts in separate processes:

```<code>import subprocess
import tkinter as tk

proclist = []

def clicked():
    proclist.clear()
    for script in ('inference.py', 'extract_frames.py'):
        proc = subprocess.Popen(['python', script])
        proclist.append(proc)

def kill_tasks():
    for proc in proclist:
        if proc and proc.poll() is None:
            print('Killing process with PID', proc.pid)
            proc.kill()
    proclist.clear()

root = tk.Tk()
root.geometry('400x400')
root.title('GUI')

tk.Button(root, text='Start detecting', width=20, command=clicked).pack()
tk.Button(root, text='Kill tasks', width=20, command=kill_tasks).pack()

root.mainloop()
</code>```

Body:
I need two scripts two run simultaneously on click of a single button. Cannot use two buttons because the gui freezes after the first button click and waits for the first program to finish.
Here's the code:

import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")

def clicked():
     os.system('python inference.py')
     os.system('python extract_frames.py')

    # I used the subprocess approach also but it still waits for the first program to finish

    subprocess.run("python inference.py  & python extract_frames.py",shell=True)

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()

Body:
You can use two subprocess.Popen(...) to run the two scripts in separate processes:

import subprocess
import tkinter as tk

proclist = []

def clicked():
    proclist.clear()
    for script in ('inference.py', 'extract_frames.py'):
        proc = subprocess.Popen(['python', script])
        proclist.append(proc)

def kill_tasks():
    for proc in proclist:
        if proc and proc.poll() is None:
            print('Killing process with PID', proc.pid)
            proc.kill()
    proclist.clear()

root = tk.Tk()
root.geometry('400x400')
root.title('GUI')

tk.Button(root, text='Start detecting', width=20, command=clicked).pack()
tk.Button(root, text='Kill tasks', width=20, command=kill_tasks).pack()

root.mainloop()


问:
EF4.1 (Database First) Generic Repository: Problem with inconsistent data types
I am working on a new application which is using a legacy system's database.  Each table in the database (there are about 600) has a 'Deleted' column to flag whether or not the item should be displayed to users.  In my generic repository, I need to add LINQ expressions to filter out all items with Deleted == 1/True.

The problem I have ran into is that the "Deleted" column has different data types across tables.

It is a tinyint, smallint or bit in any given table.  Theoretically, this should not be much of an issue since the data will always be stored as a 1 or a 0 (well, should be, I suppose, but either way a number of some sort) which can be cast to any of the specific types mentioned above.  I'm just not sure how and/or where to go about casting this.

I created an interface which forces all of the entities to expose this property, but since the types are different, each entity with the different data types will cause issues.  I was hoping (although already knew it wouldn't work) I could change the interface to "object" or "dynamic" which still causes compile time errors, since the EDMX model is creating the data model classes.  I don't want to invest too much time in writing code in the T4 templates if that will not fix the issue.

When I change the EDMX model's entity properties to adhere to a specific datatype, I receive mapping errors ("Member Mapping specific is not valid. The type 'Edm.Byte[]' of member 'Deleted' in type 'MyEntity' is not compatible with 'SqlServer.bit[]' ....)

I doubt I'll be able to change the data types in the tables, since there are many different applications which use this database and I'm sure it will cause problems somewhere.

Has anyone else ran into a similar situation and come up with a working solution?

[EDIT]
I'm going with the solution recommended by Baldy and creating a view to wrap the table and create an additional column which will be used to cast the column to a bit.

答:
Generic approach is based on the fact that your entities share same behavior. In your case it means same property with the same type. Your entities don't fulfill this requirement and because of that you cannot use generic approach.

You must somehow inject generic behavior. What about this:

```<code>public interface IDeletable<TVal> where TVal : struct
{
    TVal Deleted { get; set; }
}

public class Entity : IDeletable<bool>
{
    public bool Deleted { get; set; }
    ...
}

public interface IDeletingStrategy<TEntity, TVal>
    where TEntity : class, IDeletable<TVal>
    where TVal : struct
{
    void Delete(TEntity entity);
    IQueryable<TEntity> GetActive(IQueryable<TEntity> query);
}

public class Repository<TEntity, TVal>
    where TEntity : class, IDeletable<TVal>
    where TVal : struct
{
   private IDeletingStrategy<TEntity,TVal> _deletingStrategy;

   public Repository(IDeletingStrategy<TEntity, TVal> deletingStrategy)
   {
       _deletingStrategy = deletingStrategy;
   }

   public void Delete(TEntity entity)
   {
       _deletingStrategy.Delete(entity);
       ...
   }

   public IQueryable<TEntity> GetActive()
   {
       return _deletingStrategy.GetActive(context.Set<TEntity>());
   }

}

public class BoolDeletingStrategy<TEntity> : IDeletingStrategy<TEntity, bool>
    where TEntity : class, IDeletable<bool>
{
    public void Delete(TEntity entity)
    {
        entity.Deleted = true;
    }

    public IQueryable<TEntity> GetActive(IQueryable<TEntity> query)
    {
        return query.Where(e => !e.Deleted);
    }
}
</code>```

And you will instantiate your repository like:

```<code>var repo = new Repository<Entity, bool>(new BoolDeletingStrategy<Entity>());
</code>```

I didn't test it but I guess it can work.

ContentLicense: CC BY-SA 3.0

Body:
Generic approach is based on the fact that your entities share same behavior. In your case it means same property with the same type. Your entities don't fulfill this requirement and because of that you cannot use generic approach.

You must somehow inject generic behavior. What about this:

public interface IDeletable<TVal> where TVal : struct
{
    TVal Deleted { get; set; }
}

public class Entity : IDeletable<bool>
{
    public bool Deleted { get; set; }
    ...
}

public interface IDeletingStrategy<TEntity, TVal>
    where TEntity : class, IDeletable<TVal>
    where TVal : struct
{
    void Delete(TEntity entity);
    IQueryable<TEntity> GetActive(IQueryable<TEntity> query);
}

public class Repository<TEntity, TVal>
    where TEntity : class, IDeletable<TVal>
    where TVal : struct
{
   private IDeletingStrategy<TEntity,TVal> _deletingStrategy;

   public Repository(IDeletingStrategy<TEntity, TVal> deletingStrategy)
   {
       _deletingStrategy = deletingStrategy;
   }

   public void Delete(TEntity entity)
   {
       _deletingStrategy.Delete(entity);
       ...
   }

   public IQueryable<TEntity> GetActive()
   {
       return _deletingStrategy.GetActive(context.Set<TEntity>());
   }

}

public class BoolDeletingStrategy<TEntity> : IDeletingStrategy<TEntity, bool>
    where TEntity : class, IDeletable<bool>
{
    public void Delete(TEntity entity)
    {
        entity.Deleted = true;
    }

    public IQueryable<TEntity> GetActive(IQueryable<TEntity> query)
    {
        return query.Where(e => !e.Deleted);
    }
}

And you will instantiate your repository like:

var repo = new Repository<Entity, bool>(new BoolDeletingStrategy<Entity>());

I didn't test it but I guess it can work.


问:
How to hash particular column in csv file | linux |
I have a scenario

where i want to hash some columns of csv file

how to do that with below data

```<code>ID|NAME|CITY|AGE
1|AB1|BBC|12
2|AB2|FGD|17
3|AB3|ASD|18
4|AB4|SDF|19
5|AB5|ASC|22
</code>```

The Column name NAME | AGE should get hashed with random values

like below output

```<code>ID|NAME|CITY|AGE
1|68b329da9111314099c7d8ad5cb9c940|BBC|77bAD9da9893er34099c7d8ad5cb9c940
2|69b32fga9893e34099c7d8ad5cb9c940|FGD|68bAD9da989yue34099c7d8ad5cb9c940
3|46b329da9893e3403453d8ad5cb9c940|ASD|60bfgD9da9893e34099c7d8ad5cb9c940
4|50Cd29da9893e34099c7d8ad5cb9c940|SDF|67bAD9da98973e34099c7d8ad5cb9c940
5|67bAD9da9893e34099c7d8ad5cb9c940|ASC|67bAD9da11893e34099c7d8ad5cb9c940
</code>```

When i tested this code below code gives me same value for the column 'NAME'  it should give  randomized values

```<code>awk '{
    tmp="echo " $2 " | openssl md5 | cut -f2 -d\" \""
tmp | getline cksum
close(tmp)
$2=cksum
print
}' < sample.csv
</code>```

output :

```<code> 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
</code>```

答:
You may use it like this:

```<code>awk 'function hash(s, cmd, hex, line) {
   cmd = "openssl md5 <<< \"" s "\""
   if ( (cmd | getline line) > 0)
      hex = line
   close(cmd)
   return hex
}
BEGIN {
   FS = OFS = "|"
}
NR == 1 {
   print
   next
}
{
   print $1, hash($2), $3, hash($4)
}' file
</code>```

```<code>ID|NAME|CITY|AGE
1|d44aec35a11ff6fa8a800120dbef1cd7|BBC|2737b49252e2a4c0fe4c342e92b13285
2|157aa4a48373eaf0415ea4229b3d4421|FGD|4d095eeac8ed659b1ce69dcef32ed0dc
3|ba3c08d4a65f1baa1d7220a6802b5710|ASD|cf4278314ef8e4b996e1b798d8eb92cf
4|69be622e1c0d417ceb9b8fb0aa9dc574|SDF|3bb50ff8eeb7ad116724b56a820139fa
5|427872b1ac3a22dc154688ddc2050516|ASC|2fc57d6f63a9ee7e2f21a26fa522e3b6
</code>```

Body:
I have a scenario

where i want to hash some columns of csv file

how to do that with below data

ID|NAME|CITY|AGE
1|AB1|BBC|12
2|AB2|FGD|17
3|AB3|ASD|18
4|AB4|SDF|19
5|AB5|ASC|22

The Column name NAME | AGE should get hashed with random values

like below output

ID|NAME|CITY|AGE
1|68b329da9111314099c7d8ad5cb9c940|BBC|77bAD9da9893er34099c7d8ad5cb9c940
2|69b32fga9893e34099c7d8ad5cb9c940|FGD|68bAD9da989yue34099c7d8ad5cb9c940
3|46b329da9893e3403453d8ad5cb9c940|ASD|60bfgD9da9893e34099c7d8ad5cb9c940
4|50Cd29da9893e34099c7d8ad5cb9c940|SDF|67bAD9da98973e34099c7d8ad5cb9c940
5|67bAD9da9893e34099c7d8ad5cb9c940|ASC|67bAD9da11893e34099c7d8ad5cb9c940

When i tested this code below code gives me same value for the column 'NAME'  it should give  randomized values

awk '{
    tmp="echo " $2 " | openssl md5 | cut -f2 -d\" \""
tmp | getline cksum
close(tmp)
$2=cksum
print
}' < sample.csv

output :

 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940
 68b329da9893e34099c7d8ad5cb9c940

Body:
You may use it like this:

awk 'function hash(s, cmd, hex, line) {
   cmd = "openssl md5 <<< \"" s "\""
   if ( (cmd | getline line) > 0)
      hex = line
   close(cmd)
   return hex
}
BEGIN {
   FS = OFS = "|"
}
NR == 1 {
   print
   next
}
{
   print $1, hash($2), $3, hash($4)
}' file

ID|NAME|CITY|AGE
1|d44aec35a11ff6fa8a800120dbef1cd7|BBC|2737b49252e2a4c0fe4c342e92b13285
2|157aa4a48373eaf0415ea4229b3d4421|FGD|4d095eeac8ed659b1ce69dcef32ed0dc
3|ba3c08d4a65f1baa1d7220a6802b5710|ASD|cf4278314ef8e4b996e1b798d8eb92cf
4|69be622e1c0d417ceb9b8fb0aa9dc574|SDF|3bb50ff8eeb7ad116724b56a820139fa
5|427872b1ac3a22dc154688ddc2050516|ASC|2fc57d6f63a9ee7e2f21a26fa522e3b6


问:
php mysql select not working on field "name"
I know it's strange but I have a select that returns null if the field named name is used. If I remove it then it works, and I already changed the data in the table. If I make a direct query to mysql it works. There might be something in the contents but I can't see anything strange.

Any suggestion that could help me investigate is welcome :(

```<code>class go {
   function Query($sql){

       $results = $this->db->query($sql);

       if (mysqli_num_rows($results)<1){
           throw new Exception('No Results');
       }

       $out = array();

       while ($r = $results->fetch_object()){
           $out[] = $r;
       }

       return json_encode($out);

       $out = null;
    }
}

$client = new go;

//not working
$sql = "select name from books limit 10";
$sql = "select name,description from books limit 10";
$sql = "select * from books limit 10";

// works!
$sql = "select description from books limit 10";

$data = $client->Query( $sql );
</code>```

UPDATE

I found that the problem comes out due to some latin accented characters like ó ñ é

答: DBMS some reserved keywords. Name is a reserved name in MYsQL. Change the name to another column name, maybe name1. I think that should work.Check list of reserved keywords for mysql https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-N.</p>

Body:
I know it's strange but I have a select that returns null if the field named name is used. If I remove it then it works, and I already changed the data in the table. If I make a direct query to mysql it works. There might be something in the contents but I can't see anything strange.

Any suggestion that could help me investigate is welcome :(

class go {
   function Query($sql){

       $results = $this->db->query($sql);

       if (mysqli_num_rows($results)<1){
           throw new Exception('No Results');
       }

       $out = array();

       while ($r = $results->fetch_object()){
           $out[] = $r;
       }

       return json_encode($out);

       $out = null;
    }
}

$client = new go;

//not working
$sql = "select name from books limit 10";
$sql = "select name,description from books limit 10";
$sql = "select * from books limit 10";

// works!
$sql = "select description from books limit 10";

$data = $client->Query( $sql );

UPDATE

I found that the problem comes out due to some latin accented characters like ó ñ é


问:
How to finish current activity in Android
I have an Android application.  I am making a loading screen with a progress bar.

I entered a delay in the onCreate method.  When the timer finishes, I want to finish the current activity and start a new one.

It just gives me an exception when it calls the finish() method.

```<code>public class LoadingScreen extends Activity{
    private LoadingScreen loadingScreen;
    Intent i = new Intent(this, HomeScreen.class);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);

        CountDownTimer timer = new CountDownTimer(10000, 1000) //10 second Timer
        {
            public void onTick(long l)
            {

            }

            @Override
            public void onFinish()
            {
                loadingScreen.finishActivity(0);
                startActivity(i);
            };
        }.start();
    }
}
</code>```

How can I change the code so that it ends when the progress bar is done?

答:
What I was doing was starting a new activity and then closing the current activity. So, remember this simple rule:

```<code>finish()
startActivity<...>()
</code>```

and not

```<code>startActivity<...>()
finish()
</code>```

Body:
I have an Android application.  I am making a loading screen with a progress bar.

I entered a delay in the onCreate method.  When the timer finishes, I want to finish the current activity and start a new one.

It just gives me an exception when it calls the finish() method.

public class LoadingScreen extends Activity{
    private LoadingScreen loadingScreen;
    Intent i = new Intent(this, HomeScreen.class);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);

        CountDownTimer timer = new CountDownTimer(10000, 1000) //10 second Timer
        {
            public void onTick(long l)
            {

            }

            @Override
            public void onFinish()
            {
                loadingScreen.finishActivity(0);
                startActivity(i);
            };
        }.start();
    }
}

How can I change the code so that it ends when the progress bar is done?

Body:
What I was doing was starting a new activity and then closing the current activity. So, remember this simple rule:

finish()
startActivity<...>()

and not

startActivity<...>()
finish()


问:
Angular test how to mock ActivatedRoute data
I have a real big problem with mocking ActivatedRoute data property. No matter what I am doing all it ends up with error message : Error: <spyOnProperty> : Property data does not have access type get. Moving stub const to separate mock class also not solving the issue. I have found that this should be straight forward but I am struggling with this for a few days now.

Component

```<code>@Component({
  selector: 'app-notifications',
  templateUrl: './notifications.component.html',
  styleUrls: ['./notifications.component.css']
})
export class NotificationsComponent implements OnInit {
  notifications: NotificationEntry[];

  constructor(
    private route: ActivatedRoute,
    private modalService: ModalService,
    private messageBoxService: MessageBoxService,
    private notificationsService: NotificationsService
  ) {}

  ngOnInit() {
    this.route.data.subscribe(
      (data: { notifications: NotificationEntry[] }) => {
        this.notifications = data.notifications;
      }
    );
  }
}
</code>```

Component.spec

```<code>describe('NotificationsComponent', () => {
  let component: NotificationsComponent;
  let fixture: ComponentFixture<NotificationsComponent>;

  const registryVersionBasicData = new RegistryVersionBasicData(
    false,
    'versionId',
    new JsonDate('Unspecified', 631894104000000000),
    'user',
    'comment'
  )

  const notifications = new NotificationEntry(
    new JsonDate('Unspecified', 631894104000000000),
    'summary',
    'message',
    NotificationEntityType.StressScenario,
    'instance name',
    'instance key',
    registryVersionBasicData,
    'additional information')

  const notificationsArray = [notifications]

  beforeEach(() => {
    const activatedRouteStub = { data: of({ notifications: notificationsArray }) };
    const modalServiceStub = {};
    const messageBoxServiceStub = {};
    const notificationsServiceStub = {};

    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [NotificationsComponent, OrderPipe, RenderDatePipe, VersionInfoPipe],
      providers: [
        { provide: ActivatedRoute, useValue: activatedRouteStub },
        { provide: ModalService, useValue: modalServiceStub },
        { provide: MessageBoxService, useValue: messageBoxServiceStub },
        { provide: NotificationsService, useValue: notificationsServiceStub },
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(NotificationsComponent);
    component = fixture.componentInstance;
  });

  it('can load instance', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get notifications entry', () => {
      const activatedRouteStub = TestBed.get(ActivatedRoute);
      spyOnProperty(activatedRouteStub, 'data')

      component.ngOnInit();

      expect(component.notifications).toEqual(notificationsArray)
    });
  });
});
</code>```

答:
Define your activatedRouteStub as follows-

```<code>class ActivatedRouteStub {
    private _data = new BehaviorSubject(notifications);
    get data() {
        return this._data;
    }
    set data(notifications: NotificationEntry[]) {
        this.data.next(notifications)
    }
}
</code>```

Then use it in your providers as

```<code>{ provide: ActivatedRoute, useValue: new ActivatedRouteStub()}
</code>```

Now you can change the data by doing

```<code>const activeRoute = testBed.get(ActivatedRoute);
activeRoute.data = [new Notification()];
</code>```

Body:
I have a real big problem with mocking ActivatedRoute data property. No matter what I am doing all it ends up with error message : Error: <spyOnProperty> : Property data does not have access type get. Moving stub const to separate mock class also not solving the issue. I have found that this should be straight forward but I am struggling with this for a few days now.

Component

@Component({
  selector: 'app-notifications',
  templateUrl: './notifications.component.html',
  styleUrls: ['./notifications.component.css']
})
export class NotificationsComponent implements OnInit {
  notifications: NotificationEntry[];

  constructor(
    private route: ActivatedRoute,
    private modalService: ModalService,
    private messageBoxService: MessageBoxService,
    private notificationsService: NotificationsService
  ) {}

  ngOnInit() {
    this.route.data.subscribe(
      (data: { notifications: NotificationEntry[] }) => {
        this.notifications = data.notifications;
      }
    );
  }
}

Component.spec

describe('NotificationsComponent', () => {
  let component: NotificationsComponent;
  let fixture: ComponentFixture<NotificationsComponent>;

  const registryVersionBasicData = new RegistryVersionBasicData(
    false,
    'versionId',
    new JsonDate('Unspecified', 631894104000000000),
    'user',
    'comment'
  )

  const notifications = new NotificationEntry(
    new JsonDate('Unspecified', 631894104000000000),
    'summary',
    'message',
    NotificationEntityType.StressScenario,
    'instance name',
    'instance key',
    registryVersionBasicData,
    'additional information')

  const notificationsArray = [notifications]

  beforeEach(() => {
    const activatedRouteStub = { data: of({ notifications: notificationsArray }) };
    const modalServiceStub = {};
    const messageBoxServiceStub = {};
    const notificationsServiceStub = {};

    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [NotificationsComponent, OrderPipe, RenderDatePipe, VersionInfoPipe],
      providers: [
        { provide: ActivatedRoute, useValue: activatedRouteStub },
        { provide: ModalService, useValue: modalServiceStub },
        { provide: MessageBoxService, useValue: messageBoxServiceStub },
        { provide: NotificationsService, useValue: notificationsServiceStub },
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(NotificationsComponent);
    component = fixture.componentInstance;
  });

  it('can load instance', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('should get notifications entry', () => {
      const activatedRouteStub = TestBed.get(ActivatedRoute);
      spyOnProperty(activatedRouteStub, 'data')

      component.ngOnInit();

      expect(component.notifications).toEqual(notificationsArray)
    });
  });
});

Body:
Define your activatedRouteStub as follows-

class ActivatedRouteStub {
    private _data = new BehaviorSubject(notifications);
    get data() {
        return this._data;
    }
    set data(notifications: NotificationEntry[]) {
        this.data.next(notifications)
    }
}

Then use it in your providers as

{ provide: ActivatedRoute, useValue: new ActivatedRouteStub()}

Now you can change the data by doing

const activeRoute = testBed.get(ActivatedRoute);
activeRoute.data = [new Notification()];


问:
Increase max pod on Node
docker info : Server Version: 18.06.3-ce

```<code>[root@lgn-test-cp65 ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.9", GitCommit:"16236ce91790d4c75b79f6ce96841db1c843e7d2", GitTreeState:"clean", BuildDate:"2019-03-25T06:40:24Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.9", GitCommit:"16236ce91790d4c75b79f6ce96841db1c843e7d2", GitTreeState:"clean", BuildDate:"2019-03-25T06:30:48Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}
</code>```

I'm trying to increase MaxPods in Node but it's not working.
I would like to increase MaxPods from 110 to 200

My command

```<code>kubelet --max-pods=200 --kubeconfig=/root/.kube/config
</code>```

And result

```<code>[root@lgn-test-cp65 ~]# kubelet --max-pods=200 --kubeconfig=/root/.kube/config
Flag --max-pods has been deprecated, This parameter should be set via the config file specified by the Kubelet's --config flag. See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-config-file/ for more information.
I0218 11:16:09.655793   22675 server.go:408] Version: v1.11.9
I0218 11:16:09.656132   22675 plugins.go:97] No cloud provider specified.
W0218 11:16:19.708398   22675 manager.go:251] Timeout trying to communicate with docker during initialization, will retry
I0218 11:16:20.723226   22675 server.go:648] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
I0218 11:16:20.727579   22675 container_manager_linux.go:243] container manager verified user specified cgroup-root exists: []
I0218 11:16:20.727635   22675 container_manager_linux.go:248] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>}]} QOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s ExperimentalPodPidsLimit:-1 EnforceCPULimits:true}
I0218 11:16:20.727862   22675 container_manager_linux.go:267] Creating device plugin manager: true
I0218 11:16:20.727938   22675 state_mem.go:36] [cpumanager] initializing new in-memory state store
I0218 11:16:20.728028   22675 state_mem.go:84] [cpumanager] updated default cpuset: ""
I0218 11:16:20.728043   22675 state_mem.go:92] [cpumanager] updated cpuset assignments: "map[]"
I0218 11:16:20.728221   22675 kubelet.go:299] Watching apiserver
I0218 11:16:20.749497   22675 client.go:75] Connecting to docker on unix:///var/run/docker.sock
I0218 11:16:20.749540   22675 client.go:104] Start docker client with request timeout=2m0s
W0218 11:16:20.752947   22675 docker_service.go:545] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0218 11:16:20.752989   22675 docker_service.go:238] Hairpin mode set to "hairpin-veth"
I0218 11:16:20.780638   22675 docker_service.go:253] Docker cri networking managed by kubernetes.io/no-op
I0218 11:16:20.939375   22675 docker_service.go:258] Docker Info: &{ID:RS55:WJBO:XXTM:PPAJ:HLUV:UBH7:ZWFK:WERN:ZIHT:PAJ6:2RWI:7WOA Containers:429 ContainersRunning:302 ContainersPaused:0 ContainersStopped:127 Images:59 Driver:devicemapper DriverStatus:[[Pool Name docker-253:0-67351869-pool] [Pool Blocksize 65.54kB] [Base Device Size 10.74GB] [Backing Filesystem xfs] [Udev Sync Supported true] [Data file /dev/loop0] [Metadata file /dev/loop1] [Data loop file /var/lib/docker/devicemapper/devicemapper/data] [Metadata loop file /var/lib/docker/devicemapper/devicemapper/metadata] [Data Space Used 23.34GB] [Data Space Total 107.4GB] [Data Space Available 84.03GB] [Metadata Space Used 62.43MB] [Metadata Space Total 2.147GB] [Metadata Space Available 2.085GB] [Thin Pool Minimum Free Space 10.74GB] [Deferred Removal Enabled true] [Deferred Deletion Enabled true] [Deferred Deleted Device Count 0] [Library Version 1.02.158-RHEL7 (2019-05-13)]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog]} MemoryLimit:true SwapLimit:true KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:1358 OomKillDisable:true NGoroutines:1195 SystemTime:2020-02-18T11:16:20.857237756+01:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:1 KernelVersion:3.10.0-1062.9.1.el7.x86_64 OperatingSystem:CentOS Linux 7 (Core) OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc42042c070 NCPU:16 MemTotal:67385786368 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:lgn-test-cp65.intranet.novaliance.com Labels:[] ExperimentalBuild:false ServerVersion:18.06.3-ce ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:docker-runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:<nil>} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID:468a545b9edcd5932818eb9de8e72413e616e86e Expected:468a545b9edcd5932818eb9de8e72413e616e86e} RuncCommit:{ID:a592beb5bc4c4092b1b1bac971afed27687340c5 Expected:a592beb5bc4c4092b1b1bac971afed27687340c5} InitCommit:{ID:fec3683 Expected:fec3683} SecurityOptions:[name=seccomp,profile=default]}
I0218 11:16:20.939536   22675 docker_service.go:271] Setting cgroupDriver to cgroupfs
I0218 11:16:21.050308   22675 kuberuntime_manager.go:186] Container runtime docker initialized, version: 18.06.3-ce, apiVersion: 1.38.0
I0218 11:16:21.050912   22675 csi_plugin.go:138] kubernetes.io/csi: plugin initializing...
E0218 11:16:21.056297   22675 kubelet.go:1252] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
I0218 11:16:21.057696   22675 server.go:129] Starting to listen on 0.0.0.0:10250
I0218 11:16:21.058671   22675 server.go:302] Adding debug handlers to kubelet server.
F0218 11:16:21.059593   22675 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use
</code>```

thanks for your help. I already made the config file and it's not working.

```<code>[root@lgn-test-cp65 ~]# kubelet --config=maxpod.yaml --kubeconfig=/root/.kube/config
I0218 13:50:09.199888   26656 server.go:408] Version: v1.11.9
I0218 13:50:09.200319   26656 plugins.go:97] No cloud provider specified.
I0218 13:50:09.374179   26656 server.go:648] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
I0218 13:50:09.393932   26656 container_manager_linux.go:243] container manager verified user specified cgroup-root exists: []
I0218 13:50:09.393977   26656 container_manager_linux.go:248] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>} {Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>}]} QOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s ExperimentalPodPidsLimit:-1 EnforceCPULimits:true}
I0218 13:50:09.394140   26656 container_manager_linux.go:267] Creating device plugin manager: true
I0218 13:50:09.394223   26656 state_mem.go:36] [cpumanager] initializing new in-memory state store
I0218 13:50:09.394326   26656 state_mem.go:84] [cpumanager] updated default cpuset: ""
I0218 13:50:09.394343   26656 state_mem.go:92] [cpumanager] updated cpuset assignments: "map[]"
I0218 13:50:09.394518   26656 kubelet.go:299] Watching apiserver
I0218 13:50:09.399816   26656 client.go:75] Connecting to docker on unix:///var/run/docker.sock
I0218 13:50:09.399857   26656 client.go:104] Start docker client with request timeout=2m0s
W0218 13:50:09.402418   26656 docker_service.go:545] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0218 13:50:09.402466   26656 docker_service.go:238] Hairpin mode set to "hairpin-veth"
I0218 13:50:09.408834   26656 docker_service.go:253] Docker cri networking managed by kubernetes.io/no-op
I0218 13:50:09.464778   26656 docker_service.go:258] Docker Info: &{ID:RS55:WJBO:XXTM:PPAJ:HLUV:UBH7:ZWFK:WERN:ZIHT:PAJ6:2RWI:7WOA Containers:424 ContainersRunning:333 ContainersPaused:0 ContainersStopped:91 Images:59 Driver:devicemapper DriverStatus:[[Pool Name docker-253:0-67351869-pool] [Pool Blocksize 65.54kB] [Base Device Size 10.74GB] [Backing Filesystem xfs] [Udev Sync Supported true] [Data file /dev/loop0] [Metadata file /dev/loop1] [Data loop file /var/lib/docker/devicemapper/devicemapper/data] [Metadata loop file /var/lib/docker/devicemapper/devicemapper/metadata] [Data Space Used 23.05GB] [Data Space Total 107.4GB] [Data Space Available 84.32GB] [Metadata Space Used 62.6MB] [Metadata Space Total 2.147GB] [Metadata Space Available 2.085GB] [Thin Pool Minimum Free Space 10.74GB] [Deferred Removal Enabled true] [Deferred Deletion Enabled true] [Deferred Deleted Device Count 0] [Library Version 1.02.158-RHEL7 (2019-05-13)]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog]} MemoryLimit:true SwapLimit:true KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:1231 OomKillDisable:true NGoroutines:933 SystemTime:2020-02-18T13:50:09.448721588+01:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:1 KernelVersion:3.10.0-1062.9.1.el7.x86_64 OperatingSystem:CentOS Linux 7 (Core) OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc4204089a0 NCPU:16 MemTotal:67385786368 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:lgn-test-cp65.intranet.novaliance.com Labels:[] ExperimentalBuild:false ServerVersion:18.06.3-ce ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:docker-runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:<nil>} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID:468a545b9edcd5932818eb9de8e72413e616e86e Expected:468a545b9edcd5932818eb9de8e72413e616e86e} RuncCommit:{ID:a592beb5bc4c4092b1b1bac971afed27687340c5 Expected:a592beb5bc4c4092b1b1bac971afed27687340c5} InitCommit:{ID:fec3683 Expected:fec3683} SecurityOptions:[name=seccomp,profile=default]}
I0218 13:50:09.464926   26656 docker_service.go:271] Setting cgroupDriver to cgroupfs
I0218 13:50:09.506807   26656 kuberuntime_manager.go:186] Container runtime docker initialized, version: 18.06.3-ce, apiVersion: 1.38.0
I0218 13:50:09.507488   26656 csi_plugin.go:138] kubernetes.io/csi: plugin initializing...
I0218 13:50:09.508605   26656 server.go:129] Starting to listen on 0.0.0.0:10250
E0218 13:50:09.508656   26656 kubelet.go:1252] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
I0218 13:50:09.508868   26656 server.go:986] Started kubelet
E0218 13:50:09.509041   26656 server.go:733] Starting health server failed: listen tcp 127.0.0.1:10248: bind: address already in use
I0218 13:50:09.509923   26656 server.go:302] Adding debug handlers to kubelet server.
F0218 13:50:09.510787   26656 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use
</code>```

maxpod.yaml

```<code>apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
maxPods: 200
</code>```

答:
--max-pods has been deprecated. Please use --config flag.

First, save the following content in a file.

```<code>apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
maxPods: 200
</code>```

Then, pass it via kubelet.

```<code>kubelet --config=<file.yaml> --kubeconfig=/root/.kube/config
</code>```

Title: Increase max pod on Node

Body:
docker info : Server Version: 18.06.3-ce

[root@lgn-test-cp65 ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.9", GitCommit:"16236ce91790d4c75b79f6ce96841db1c843e7d2", GitTreeState:"clean", BuildDate:"2019-03-25T06:40:24Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.9", GitCommit:"16236ce91790d4c75b79f6ce96841db1c843e7d2", GitTreeState:"clean", BuildDate:"2019-03-25T06:30:48Z", GoVersion:"go1.10.8", Compiler:"gc", Platform:"linux/amd64"}

I'm trying to increase MaxPods in Node but it's not working.
I would like to increase MaxPods from 110 to 200

My command

kubelet --max-pods=200 --kubeconfig=/root/.kube/config

And result

[root@lgn-test-cp65 ~]# kubelet --max-pods=200 --kubeconfig=/root/.kube/config
Flag --max-pods has been deprecated, This parameter should be set via the config file specified by the Kubelet's --config flag. See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-config-file/ for more information.
I0218 11:16:09.655793   22675 server.go:408] Version: v1.11.9
I0218 11:16:09.656132   22675 plugins.go:97] No cloud provider specified.
W0218 11:16:19.708398   22675 manager.go:251] Timeout trying to communicate with docker during initialization, will retry
I0218 11:16:20.723226   22675 server.go:648] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
I0218 11:16:20.727579   22675 container_manager_linux.go:243] container manager verified user specified cgroup-root exists: []
I0218 11:16:20.727635   22675 container_manager_linux.go:248] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>}]} QOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s ExperimentalPodPidsLimit:-1 EnforceCPULimits:true}
I0218 11:16:20.727862   22675 container_manager_linux.go:267] Creating device plugin manager: true
I0218 11:16:20.727938   22675 state_mem.go:36] [cpumanager] initializing new in-memory state store
I0218 11:16:20.728028   22675 state_mem.go:84] [cpumanager] updated default cpuset: ""
I0218 11:16:20.728043   22675 state_mem.go:92] [cpumanager] updated cpuset assignments: "map[]"
I0218 11:16:20.728221   22675 kubelet.go:299] Watching apiserver
I0218 11:16:20.749497   22675 client.go:75] Connecting to docker on unix:///var/run/docker.sock
I0218 11:16:20.749540   22675 client.go:104] Start docker client with request timeout=2m0s
W0218 11:16:20.752947   22675 docker_service.go:545] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0218 11:16:20.752989   22675 docker_service.go:238] Hairpin mode set to "hairpin-veth"
I0218 11:16:20.780638   22675 docker_service.go:253] Docker cri networking managed by kubernetes.io/no-op
I0218 11:16:20.939375   22675 docker_service.go:258] Docker Info: &{ID:RS55:WJBO:XXTM:PPAJ:HLUV:UBH7:ZWFK:WERN:ZIHT:PAJ6:2RWI:7WOA Containers:429 ContainersRunning:302 ContainersPaused:0 ContainersStopped:127 Images:59 Driver:devicemapper DriverStatus:[[Pool Name docker-253:0-67351869-pool] [Pool Blocksize 65.54kB] [Base Device Size 10.74GB] [Backing Filesystem xfs] [Udev Sync Supported true] [Data file /dev/loop0] [Metadata file /dev/loop1] [Data loop file /var/lib/docker/devicemapper/devicemapper/data] [Metadata loop file /var/lib/docker/devicemapper/devicemapper/metadata] [Data Space Used 23.34GB] [Data Space Total 107.4GB] [Data Space Available 84.03GB] [Metadata Space Used 62.43MB] [Metadata Space Total 2.147GB] [Metadata Space Available 2.085GB] [Thin Pool Minimum Free Space 10.74GB] [Deferred Removal Enabled true] [Deferred Deletion Enabled true] [Deferred Deleted Device Count 0] [Library Version 1.02.158-RHEL7 (2019-05-13)]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog]} MemoryLimit:true SwapLimit:true KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:1358 OomKillDisable:true NGoroutines:1195 SystemTime:2020-02-18T11:16:20.857237756+01:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:1 KernelVersion:3.10.0-1062.9.1.el7.x86_64 OperatingSystem:CentOS Linux 7 (Core) OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc42042c070 NCPU:16 MemTotal:67385786368 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:lgn-test-cp65.intranet.novaliance.com Labels:[] ExperimentalBuild:false ServerVersion:18.06.3-ce ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:docker-runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:<nil>} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID:468a545b9edcd5932818eb9de8e72413e616e86e Expected:468a545b9edcd5932818eb9de8e72413e616e86e} RuncCommit:{ID:a592beb5bc4c4092b1b1bac971afed27687340c5 Expected:a592beb5bc4c4092b1b1bac971afed27687340c5} InitCommit:{ID:fec3683 Expected:fec3683} SecurityOptions:[name=seccomp,profile=default]}
I0218 11:16:20.939536   22675 docker_service.go:271] Setting cgroupDriver to cgroupfs
I0218 11:16:21.050308   22675 kuberuntime_manager.go:186] Container runtime docker initialized, version: 18.06.3-ce, apiVersion: 1.38.0
I0218 11:16:21.050912   22675 csi_plugin.go:138] kubernetes.io/csi: plugin initializing...
E0218 11:16:21.056297   22675 kubelet.go:1252] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
I0218 11:16:21.057696   22675 server.go:129] Starting to listen on 0.0.0.0:10250
I0218 11:16:21.058671   22675 server.go:302] Adding debug handlers to kubelet server.
F0218 11:16:21.059593   22675 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use

thanks for your help. I already made the config file and it's not working.

[root@lgn-test-cp65 ~]# kubelet --config=maxpod.yaml --kubeconfig=/root/.kube/config
I0218 13:50:09.199888   26656 server.go:408] Version: v1.11.9
I0218 13:50:09.200319   26656 plugins.go:97] No cloud provider specified.
I0218 13:50:09.374179   26656 server.go:648] --cgroups-per-qos enabled, but --cgroup-root was not specified.  defaulting to /
I0218 13:50:09.393932   26656 container_manager_linux.go:243] container manager verified user specified cgroup-root exists: []
I0218 13:50:09.393977   26656 container_manager_linux.go:248] Creating Container Manager object based on Node Config: {RuntimeCgroupsName: SystemCgroupsName: KubeletCgroupsName: ContainerRuntime:docker CgroupsPerQOS:true CgroupRoot:/ CgroupDriver:cgroupfs KubeletRootDir:/var/lib/kubelet ProtectKernelDefaults:false NodeAllocatableConfig:{KubeReservedCgroupName: SystemReservedCgroupName: EnforceNodeAllocatable:map[pods:{}] KubeReserved:map[] SystemReserved:map[] HardEvictionThresholds:[{Signal:nodefs.inodesFree Operator:LessThan Value:{Quantity:<nil> Percentage:0.05} GracePeriod:0s MinReclaim:<nil>} {Signal:imagefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.15} GracePeriod:0s MinReclaim:<nil>} {Signal:memory.available Operator:LessThan Value:{Quantity:100Mi Percentage:0} GracePeriod:0s MinReclaim:<nil>} {Signal:nodefs.available Operator:LessThan Value:{Quantity:<nil> Percentage:0.1} GracePeriod:0s MinReclaim:<nil>}]} QOSReserved:map[] ExperimentalCPUManagerPolicy:none ExperimentalCPUManagerReconcilePeriod:10s ExperimentalPodPidsLimit:-1 EnforceCPULimits:true}
I0218 13:50:09.394140   26656 container_manager_linux.go:267] Creating device plugin manager: true
I0218 13:50:09.394223   26656 state_mem.go:36] [cpumanager] initializing new in-memory state store
I0218 13:50:09.394326   26656 state_mem.go:84] [cpumanager] updated default cpuset: ""
I0218 13:50:09.394343   26656 state_mem.go:92] [cpumanager] updated cpuset assignments: "map[]"
I0218 13:50:09.394518   26656 kubelet.go:299] Watching apiserver
I0218 13:50:09.399816   26656 client.go:75] Connecting to docker on unix:///var/run/docker.sock
I0218 13:50:09.399857   26656 client.go:104] Start docker client with request timeout=2m0s
W0218 13:50:09.402418   26656 docker_service.go:545] Hairpin mode set to "promiscuous-bridge" but kubenet is not enabled, falling back to "hairpin-veth"
I0218 13:50:09.402466   26656 docker_service.go:238] Hairpin mode set to "hairpin-veth"
I0218 13:50:09.408834   26656 docker_service.go:253] Docker cri networking managed by kubernetes.io/no-op
I0218 13:50:09.464778   26656 docker_service.go:258] Docker Info: &{ID:RS55:WJBO:XXTM:PPAJ:HLUV:UBH7:ZWFK:WERN:ZIHT:PAJ6:2RWI:7WOA Containers:424 ContainersRunning:333 ContainersPaused:0 ContainersStopped:91 Images:59 Driver:devicemapper DriverStatus:[[Pool Name docker-253:0-67351869-pool] [Pool Blocksize 65.54kB] [Base Device Size 10.74GB] [Backing Filesystem xfs] [Udev Sync Supported true] [Data file /dev/loop0] [Metadata file /dev/loop1] [Data loop file /var/lib/docker/devicemapper/devicemapper/data] [Metadata loop file /var/lib/docker/devicemapper/devicemapper/metadata] [Data Space Used 23.05GB] [Data Space Total 107.4GB] [Data Space Available 84.32GB] [Metadata Space Used 62.6MB] [Metadata Space Total 2.147GB] [Metadata Space Available 2.085GB] [Thin Pool Minimum Free Space 10.74GB] [Deferred Removal Enabled true] [Deferred Deletion Enabled true] [Deferred Deleted Device Count 0] [Library Version 1.02.158-RHEL7 (2019-05-13)]] SystemStatus:[] Plugins:{Volume:[local] Network:[bridge host macvlan null overlay] Authorization:[] Log:[awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog]} MemoryLimit:true SwapLimit:true KernelMemory:true CPUCfsPeriod:true CPUCfsQuota:true CPUShares:true CPUSet:true IPv4Forwarding:true BridgeNfIptables:true BridgeNfIP6tables:true Debug:false NFd:1231 OomKillDisable:true NGoroutines:933 SystemTime:2020-02-18T13:50:09.448721588+01:00 LoggingDriver:json-file CgroupDriver:cgroupfs NEventsListener:1 KernelVersion:3.10.0-1062.9.1.el7.x86_64 OperatingSystem:CentOS Linux 7 (Core) OSType:linux Architecture:x86_64 IndexServerAddress:https://index.docker.io/v1/ RegistryConfig:0xc4204089a0 NCPU:16 MemTotal:67385786368 GenericResources:[] DockerRootDir:/var/lib/docker HTTPProxy: HTTPSProxy: NoProxy: Name:lgn-test-cp65.intranet.novaliance.com Labels:[] ExperimentalBuild:false ServerVersion:18.06.3-ce ClusterStore: ClusterAdvertise: Runtimes:map[runc:{Path:docker-runc Args:[]}] DefaultRuntime:runc Swarm:{NodeID: NodeAddr: LocalNodeState:inactive ControlAvailable:false Error: RemoteManagers:[] Nodes:0 Managers:0 Cluster:<nil>} LiveRestoreEnabled:false Isolation: InitBinary:docker-init ContainerdCommit:{ID:468a545b9edcd5932818eb9de8e72413e616e86e Expected:468a545b9edcd5932818eb9de8e72413e616e86e} RuncCommit:{ID:a592beb5bc4c4092b1b1bac971afed27687340c5 Expected:a592beb5bc4c4092b1b1bac971afed27687340c5} InitCommit:{ID:fec3683 Expected:fec3683} SecurityOptions:[name=seccomp,profile=default]}
I0218 13:50:09.464926   26656 docker_service.go:271] Setting cgroupDriver to cgroupfs
I0218 13:50:09.506807   26656 kuberuntime_manager.go:186] Container runtime docker initialized, version: 18.06.3-ce, apiVersion: 1.38.0
I0218 13:50:09.507488   26656 csi_plugin.go:138] kubernetes.io/csi: plugin initializing...
I0218 13:50:09.508605   26656 server.go:129] Starting to listen on 0.0.0.0:10250
E0218 13:50:09.508656   26656 kubelet.go:1252] Image garbage collection failed once. Stats initialization may not have completed yet: failed to get imageFs info: unable to find data for container /
I0218 13:50:09.508868   26656 server.go:986] Started kubelet
E0218 13:50:09.509041   26656 server.go:733] Starting health server failed: listen tcp 127.0.0.1:10248: bind: address already in use
I0218 13:50:09.509923   26656 server.go:302] Adding debug handlers to kubelet server.
F0218 13:50:09.510787   26656 server.go:141] listen tcp 0.0.0.0:10250: bind: address already in use

maxpod.yaml

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
maxPods: 200

Body:
--max-pods has been deprecated. Please use --config flag.

First, save the following content in a file.

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
maxPods: 200

Then, pass it via kubelet.

kubelet --config=<file.yaml> --kubeconfig=/root/.kube/config


问:
deferred mail plesk, mail can't send mail out of server
My problem is about sending email out of the circle mail server, exemple:

From: name@mydomainename.com
To: name@gmail.com or any other domaine name

The message appeare on plesk under Mail Queue

Messages in queue: 47 deferred, 0 held, 0 incoming, 0 active, 0 corrupted, 47 total.

I was trying many times to re-sending all deferred emails in the queue by taping en console:

postsuper -r ALL

but the same problem all the time.

Now, when I send mail, exemple:

From: name@mydomainename.com
To: name1@mydomainename.com

it works correctly

答:
Before going into configuration changes, have you checked if your domain is blacklisted or not? Were you able to receive E-mails from other domains such as Gmail?

Sending/receiving Emails to/from the same domain is nearly always possible. No matter how messed up the configurations are you will still manage to deliver emails within the domain itself.

Usually I've found that the reason behind this problem is the blacklisted IPs. Make sure that your domain IP is not blacklisted.

https://mxtoolbox.com/blacklists.aspx


问:
Source level debugging of generated code in IntelliJ
I want to debug into code generated by Dagger in IntelliJ. The source files generated by Dagger are put into /target/generated-test-sources/test-annotations and /target/generated-sources/annotations.

I've looked at the Run/Debug Configurations dialog, and didn't see anything obvious. I've also checked the Module Settings and both of these are listed as Source Folders so IntelliJ definitely knows they're source, but for some reason won't hit on any breakpoints I put in generated code.

答:
My working warkaround is:

expand the generated artifact (jar, war, ear, ...)

open (and decompile) the class file

put here the breakpoint

At this point IntelliJ fires breakpoints as expected.


问:
Facebook Graph API: how do I delete a status message (of mine)
I've written a small facebook client app which can post and retrieve status messages.

Now I want to be able to delete this status messages I have posted. I tried to achieve this by opening the following URL:

```<code>"https://graph.facebook.com/" + postID + "?method=delete&access_token=" + AccessToken;
</code>```

If I do this I get an error message 403 (invalid).

I can delete a status message, if it was posted by my program. But I can't delete it if it was posted by some other program. But this is what I need to do :(

Do I need special rights to remove a status message? Which? Or do I need to use another call to remove it?

答:
I think i'm late with my answer, but i hope someone can still use it. But i think you have to prepend your userid to the ID of the status message you want to delete.

Like this: https://graph.facebook.com/64568227_27863456432483453?access_token={access_token} where 64568227 is the userID and 27863456432483453 is the status message id.

ContentLicense: CC BY-SA 2.5

Body:
I've written a small facebook client app which can post and retrieve status messages.

Now I want to be able to delete this status messages I have posted. I tried to achieve this by opening the following URL:

"https://graph.facebook.com/" + postID + "?method=delete&access_token=" + AccessToken;

If I do this I get an error message 403 (invalid).

I can delete a status message, if it was posted by my program. But I can't delete it if it was posted by some other program. But this is what I need to do :(

Do I need special rights to remove a status message? Which? Or do I need to use another call to remove it?


问:
Delete empty folders inside working directory
I have number of empty folders inside a working directory. Want to remove those empty folders in R. Can somebody help me out on this.</p>

答:
We can delete folders using:

```<code>unlink("path_to_non_empty_dir", recursive=TRUE)
</code>```

Edit: removed part about non-empty folders

From ?unlink:

If recursive = FALSE directories are not deleted, not even empty ones.

Body:
We can delete folders using:

unlink("path_to_non_empty_dir", recursive=TRUE)

Edit: removed part about non-empty folders

From ?unlink:

If recursive = FALSE directories are not deleted, not even empty ones.


问:
Allowed memory size of 536870912 bytes exhausted (tried to allocate 268439552 bytes)
```<code>$html = file_get_html('https://m.gsmarena.com/');
$videos = [];
foreach ($html->find('div.swiper-half-slide') as $video) {
foreach ($video->find('strong')as $name){

   echo $name->innertext;
   $videos[]=$name;
}}
print_r($videos);
</code>```

im getting fatalerror Allowed memory size of 536870912 bytes exhausted (tried to allocate 268439552 bytes) in C:\xampp\htdocs\scrappingpractise\scraper.php on line 24

答: You are running out of memory, by default PHP allows you to allocate 256mb for each execution. You can change it in your php.ini file, the option it's called memory_limit

Body:
$html = file_get_html('https://m.gsmarena.com/');
$videos = [];
foreach ($html->find('div.swiper-half-slide') as $video) {
foreach ($video->find('strong')as $name){

   echo $name->innertext;
   $videos[]=$name;
}}
print_r($videos);

im getting fatalerror Allowed memory size of 536870912 bytes exhausted (tried to allocate 268439552 bytes) in C:\xampp\htdocs\scrappingpractise\scraper.php on line 24


问:
Is it possible to implement multiple test runners in pyunitest? while only running the test suite once
```<code>if __name__ == '__main__':
    if is_running_under_teamcity():
        runner = TeamcityTestRunner()
    else:
        runner =  HTMLTestRunner.HTMLTestRunner(
                stream=outfile,
                title='Test Report',
                description='This is an example.'
                )
    unittest.main(testRunner=runner)
</code>```

I am currently running some tests using unittest module in python this is my current code above. I am deploying this test setup on Teamcity, the first module allows me to convert the output into teamcity-messages and the second creates a html report of the results. Is there a way I can run both of these runners while only running one set of tests? The only option I can see at the minuete is to either try and combine both these modules into a hybrid or using another testing module that Teamcity supports. However I would like to keep the dependancies as low as possible

Any ideas would be great :)

答:
Any ideas would be great :)

Looks like you'll have to handroll it, looking at the code TeamcityTestRunner is a pretty simple extension of the standard TextTestRunner, however HTMLTestRunner is a way more complex beast.

Sadly this is one area of the stdlib which is really badly architected: one could expect the test runner to be concerned solely with discovering and running tests, however it's also tasked with part of the test reporting rather than have an entirely separate test reporter (this test reporting is furthermore a split responsability with the test result, which shouldn't be part of that one's job description either).

Frankly if you don't have any further customisation I'd suggest just using pytest as your test runner instead of unittest with a custom runner:

it should be able to run unittest tests fine

IME it has better separation of concerns and pluggability so having multiple reporters / formatters should work out of the box

pytest-html certainly has no issue generating its reports without affecting the normal text output

according to the readme teamcity gets automatically enabled and used for pytest

so I'd assume generating html reports during your teamcity builds would work fine (to test)

and you can eventually migrate to using pytest tests (which are so much better it's not even funny)

Body:
if __name__ == '__main__':
    if is_running_under_teamcity():
        runner = TeamcityTestRunner()
    else:
        runner =  HTMLTestRunner.HTMLTestRunner(
                stream=outfile,
                title='Test Report',
                description='This is an example.'
                )
    unittest.main(testRunner=runner)

I am currently running some tests using unittest module in python this is my current code above. I am deploying this test setup on Teamcity, the first module allows me to convert the output into teamcity-messages and the second creates a html report of the results. Is there a way I can run both of these runners while only running one set of tests? The only option I can see at the minuete is to either try and combine both these modules into a hybrid or using another testing module that Teamcity supports. However I would like to keep the dependancies as low as possible

Any ideas would be great :)


问:
Custom Rule class in Laravel - how to get message working?
Working on an existing project, so keeping the code structure the same as other developers is critical.

I've created a new Rule and added my Validator::extend to the boot(). However I can't get the validation error to display my custom message. Instead is just displays a default "validation.ruleName"

I'm writing a Validation rule that uses ImLiam's NHS Number validation package. The validate() and passes() work successfully. But the error message never changes.

How can I get the messages() method to display the custom output of the exception? (Instead of "validation.nhsnumber" in screenshot below?

App\Forms\MyForm: (using Kris Forms)

```<code>public function buildForm()
{
    $this->add('nhs_number', 'number', [
        'label' => 'NHS Number',
        'rules' => 'nullable|nhsnumber',
    ]);
    ...
}
</code>```

App\Providers\AppServiceProvider:

```<code>public function boot()
{

        Validator::extend('nhsnumber', \App\Rules\ValidNhsNumber::class);
}
</code>```

App\Rules\ValidNhsNumber:

```<code>namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use ImLiam\NhsNumber\InvalidNhsNumberException;
use ImLiam\NhsNumber\NhsNumber;

class ValidNhsNumber implements Rule
{
    private $message;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        try {
            $nhsNumber = new NhsNumber($value);
            $nhsNumber->validate(); // Will throw exception here if false
            return true;
        } catch (InvalidNhsNumberException $e) {
            $this->message = $e->getMessage();
        }
    }

    public function validate($attribute, $value, $params): bool
    {
        return $this->passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
</code>```

答:
Your message property is null. Laravels validator will attempt to get the error message calling your message() method, and if nothing is returning it'll use get_class($this) and then attempt to construct an error message.

This method can either return a translation placeholder such as validation.nhsnumber or it can return the actual message. In the example you have given, it's just not returning anything.

Body:
Working on an existing project, so keeping the code structure the same as other developers is critical.

I've created a new Rule and added my Validator::extend to the boot(). However I can't get the validation error to display my custom message. Instead is just displays a default "validation.ruleName"

I'm writing a Validation rule that uses ImLiam's NHS Number validation package. The validate() and passes() work successfully. But the error message never changes.

How can I get the messages() method to display the custom output of the exception? (Instead of "validation.nhsnumber" in screenshot below?

App\Forms\MyForm: (using Kris Forms)

public function buildForm()
{
    $this->add('nhs_number', 'number', [
        'label' => 'NHS Number',
        'rules' => 'nullable|nhsnumber',
    ]);
    ...
}

App\Providers\AppServiceProvider:

public function boot()
{

        Validator::extend('nhsnumber', \App\Rules\ValidNhsNumber::class);
}

App\Rules\ValidNhsNumber:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use ImLiam\NhsNumber\InvalidNhsNumberException;
use ImLiam\NhsNumber\NhsNumber;

class ValidNhsNumber implements Rule
{
    private $message;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        try {
            $nhsNumber = new NhsNumber($value);
            $nhsNumber->validate(); // Will throw exception here if false
            return true;
        } catch (InvalidNhsNumberException $e) {
            $this->message = $e->getMessage();
        }
    }

    public function validate($attribute, $value, $params): bool
    {
        return $this->passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}


问:
How can I convert this list of numbers and symbols into a string?
is there a way too convert a list like this into a normal string?
list->string does not work because it isn't a list of chars.
It is a bit problematic because the list consists of symbols and numbers :/

(list + 4 * 5 - 3 6)         //-> "+4*5-36"

答:
I will show you in mit-scheme:

```<code>
(define input '(+ 4 * 5 - 3 6))

(fold-right (lambda (x acc)
              (string-append ((cond ((number? x) number->string )
                                    ((symbol? x) symbol->string ))
                                    (else (error "unknown case" x))
                              x)
                             acc))
            ""
            input)
</code>```

Example:

```<code>1 ]=>
(define input '(+ 4 * 5 - 3 6))
;Value: input
...
;Value: "+4*5-36"
</code>```

In case the list contains more kind of symbolic expressions, apart from numbers and symbols, you extend the cond-statement with other cases.

Also, do not forget to quote the input, otherwise + gets evaluated to a strange value.

Body:
I will show you in mit-scheme:

(define input '(+ 4 * 5 - 3 6))

(fold-right (lambda (x acc)
              (string-append ((cond ((number? x) number->string )
                                    ((symbol? x) symbol->string ))
                                    (else (error "unknown case" x))
                              x)
                             acc))
            ""
            input)

Example:

1 ]=>
(define input '(+ 4 * 5 - 3 6))
;Value: input
...
;Value: "+4*5-36"

In case the list contains more kind of symbolic expressions, apart from numbers and symbols, you extend the cond-statement with other cases.

Also, do not forget to quote the input, otherwise + gets evaluated to a strange value.


问:
Encode JSON in bash script
I'm trying to import a Template to my Zabbix server with Zabbix API, i used this:

```<code>fileJSON=\""$(cat template_file)"\"

curl  -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "configuration.import",
    "params": {
        "format": "json",
        "rules": {
            "templates": {
                "createMissing": true,
                "updateExisting": true
            }
        },
        "source": $fileJSON
    },
    "auth": "6a977cd94b26b6156698459ac4d0f769",
    "id": 1
}' 'http://127.0.0.1/zabbix/api_jsonrpc.php' | jq '.'
</code>```

Here is the output:

```<code>{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}
</code>```

I just don't see any error… i tried to use an online parser website but he Don't see any error.
This var is directly filled with the export method of Zabbix (in JSON).
Here is the content of the file:

```<code>{
  "jsonrpc": "2.0",
  "result": "{\"zabbix_export\":{\"version\":\"4.4\",\"date\":\"2020-02-18T08:47:31Z\",\"groups\":[{\"name\":\"System\"}],\"templates\":[{\"template\":\"Template Systeme\",\"name\":\"Template Systeme\",\"groups\":[{\"name\":\"System\"}],\"discovery_rules\":[{\"name\":\"D\\u00e9couverte des services\",\"key\":\"service.discovery\",\"delay\":\"30s\"}]}]}}",
  "id": 1
}
</code>```

I think that the error is the format of the fileJSON, how to encode this variable in JSON format ?

答:
you're submitting your JSON using single quotes '{...}' which do not result in the interpolation of your $fileJSON - hence you receive that error.

Use double quotations instead:

```<code>curl  -s -X POST -H 'Content-Type: application/json-rpc' -d "{
...
</code>```

you would need then quote the inner quotation marks of your JSON too.

There's also an easier way to interpolate $fileJSON, use it like this:

```<code>curl  -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "configuration.import",
    "params": {
        "format": "json",
        "rules": {
            "templates": {
                "createMissing": true,
                "updateExisting": true
            }
        },
        "source": '"$fileJSON"'
    },
    "auth": "6a977cd94b26b6156698459ac4d0f769",
    "id": 1
}' ...
</code>```

that way will spare you a hassle quoting inner quotation marks

Title: Encode JSON in bash script

Body:
I'm trying to import a Template to my Zabbix server with Zabbix API, i used this:

fileJSON=\""$(cat template_file)"\"

curl  -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "configuration.import",
    "params": {
        "format": "json",
        "rules": {
            "templates": {
                "createMissing": true,
                "updateExisting": true
            }
        },
        "source": $fileJSON
    },
    "auth": "6a977cd94b26b6156698459ac4d0f769",
    "id": 1
}' 'http://127.0.0.1/zabbix/api_jsonrpc.php' | jq '.'

Here is the output:

{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":"Invalid JSON. An error occurred on the server while parsing the JSON text."},"id":null}

I just don't see any error… i tried to use an online parser website but he Don't see any error.
This var is directly filled with the export method of Zabbix (in JSON).
Here is the content of the file:

{
  "jsonrpc": "2.0",
  "result": "{\"zabbix_export\":{\"version\":\"4.4\",\"date\":\"2020-02-18T08:47:31Z\",\"groups\":[{\"name\":\"System\"}],\"templates\":[{\"template\":\"Template Systeme\",\"name\":\"Template Systeme\",\"groups\":[{\"name\":\"System\"}],\"discovery_rules\":[{\"name\":\"D\\u00e9couverte des services\",\"key\":\"service.discovery\",\"delay\":\"30s\"}]}]}}",
  "id": 1
}

I think that the error is the format of the fileJSON, how to encode this variable in JSON format ?

Body:
you're submitting your JSON using single quotes '{...}' which do not result in the interpolation of your $fileJSON - hence you receive that error.

Use double quotations instead:

curl  -s -X POST -H 'Content-Type: application/json-rpc' -d "{
...

you would need then quote the inner quotation marks of your JSON too.

There's also an easier way to interpolate $fileJSON, use it like this:

curl  -s -X POST -H 'Content-Type: application/json-rpc' -d '{
    "jsonrpc": "2.0",
    "method": "configuration.import",
    "params": {
        "format": "json",
        "rules": {
            "templates": {
                "createMissing": true,
                "updateExisting": true
            }
        },
        "source": '"$fileJSON"'
    },
    "auth": "6a977cd94b26b6156698459ac4d0f769",
    "id": 1
}' ...

that way will spare you a hassle quoting inner quotation marks


问:
Left Join With Where Clause
I need to retrieve all default settings from the settings table but also grab the character setting if exists for x character.

But this query is only retrieving those settings where character is = 1, not the default settings if the user havent setted anyone.

```<code>SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1'
</code>```

So i should need something like this:

```<code>array(
    '0' => array('somekey' => 'keyname', 'value' => 'thevalue'),
    '1' => array('somekey2' => 'keyname2'),
    '2' => array('somekey3' => 'keyname3')
)
</code>```

Where key 1 and 2 are the default values when key 0 contains the default value with the character value.

答:
For this problem, as for many others involving non-trivial left joins such as left-joining on inner-joined tables, I find it convenient and somewhat more readable to split the query with a with clause. In your example,

```<code>with settings_for_char as (
  select setting_id, value from character_settings where character_id = 1
)
select
  settings.*,
  settings_for_char.value
from
  settings
  left join settings_for_char on settings_for_char.setting_id = settings.id;
</code>```

Title: Left Join With Where Clause

Body:
I need to retrieve all default settings from the settings table but also grab the character setting if exists for x character.

But this query is only retrieving those settings where character is = 1, not the default settings if the user havent setted anyone.

SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1'

So i should need something like this:

array(
    '0' => array('somekey' => 'keyname', 'value' => 'thevalue'),
    '1' => array('somekey2' => 'keyname2'),
    '2' => array('somekey3' => 'keyname3')
)

Where key 1 and 2 are the default values when key 0 contains the default value with the character value.

Body:
For this problem, as for many others involving non-trivial left joins such as left-joining on inner-joined tables, I find it convenient and somewhat more readable to split the query with a with clause. In your example,

with settings_for_char as (
  select setting_id, value from character_settings where character_id = 1
)
select
  settings.*,
  settings_for_char.value
from
  settings
  left join settings_for_char on settings_for_char.setting_id = settings.id;


问:
How to append data to a file?
I trying to write into the txt file.

But with out losing the data that is already stored in the file.

But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.

My code is:

```<code>public void addWorker(Worker worker){
        workers.put(worker.getId(), worker);

    }

    public void printWorker (String id){
    Worker work = (Worker) workers.get( id );

    if (work == null) {
        System.out.println("Worker NOT found");
    }

    else {
         work.printText();
     }
    }
       public void printWorkers() {
           if (workers.size() == 0) {
               System.out.println("No workres");
                return;
           }

           Collection<Worker> c = workers.values();
           Iterator<Worker> itr = c.iterator();
           System.out.println("Workers in division "+dName+ ":");
           while (itr.hasNext()) {
                  Worker wo = itr.next();
                  wo.printText();
           }
       }

       public void writeToFile(){
           PrintWriter pw = null;
           try{
               pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
               Collection<Worker> c = workers.values();
               Iterator<Worker> itr = c.iterator();
               while (itr.hasNext()) {
                   Worker wo = itr.next();
                   pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
                   pw.println();
               }
            }
            catch(Exception e) {
                System.out.println(e);
            }
            finally {
                if (pw != null) {
                    pw.close();
                }
            }

        }

}
</code>```

Can you help me?

答:
You have to set the Stream to append mode like this: </p>

```<code>pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));
</code>```

Title: How to append data to a file?

Body:
I trying to write into the txt file.

But with out losing the data that is already stored in the file.

But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.

My code is:

public void addWorker(Worker worker){
        workers.put(worker.getId(), worker);

    }

    public void printWorker (String id){
    Worker work = (Worker) workers.get( id );

    if (work == null) {
        System.out.println("Worker NOT found");
    }

    else {
         work.printText();
     }
    }
       public void printWorkers() {
           if (workers.size() == 0) {
               System.out.println("No workres");
                return;
           }

           Collection<Worker> c = workers.values();
           Iterator<Worker> itr = c.iterator();
           System.out.println("Workers in division "+dName+ ":");
           while (itr.hasNext()) {
                  Worker wo = itr.next();
                  wo.printText();
           }
       }

       public void writeToFile(){
           PrintWriter pw = null;
           try{
               pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
               Collection<Worker> c = workers.values();
               Iterator<Worker> itr = c.iterator();
               while (itr.hasNext()) {
                   Worker wo = itr.next();
                   pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
                   pw.println();
               }
            }
            catch(Exception e) {
                System.out.println(e);
            }
            finally {
                if (pw != null) {
                    pw.close();
                }
            }

        }

}

Can you help me?

Body:
You have to set the Stream to append mode like this:

pw = new PrintWriter(new FileWriter("d:\\stam\\stam.txt", true));


问:
Gradle: Add dependency of subproject as dependency of the root project
We are running our Java EE applications in WAS 8.5 and Gradle 5.* to build them.

In the past we packaged our .war application in an .ear archive, which we then deployed on our server. We had to separate our libraries from our applications and include them as shared libraries, because in our experience it made deploying much slower and in some cases used up all system memory, crashing the server.

After some experimentation, we realized that we don't need to extract the dependencies into shared libraries, because we can include them in the lib folder of our .ear archive.

Currently, we get this done by defining the dependencies of our .war application as compileOnly and redefining them as earlib in the root project (which generates the .ear archive). I'm looking for a way to automate this procedure.

The script I used looks something like this:

```<code>project.configurations.named('deploy').getAllDependencies().withType(ProjectDependency.class).forEach({dependency ->
    project.configurations.named('earlib').getAllDependencies()
        .addAll(dependency.dependentProject.configurations.named('earlib').getAllDependencies())
})

// This loosely resembles the actual code I used. The thought process is right, it just might have a couple syntax errors.

// Obviously, I defined an `earlib` configuration in the subproject
</code>```

I tried running this code in the configuration phase, as well as in the doFirst{} section of the ear task. They all had different problems.

The former didn't work, because it seems like in the configuration phase when this code ran, the dependencies weren't configured yet.

The latter didn't work, because I can't just add dependencies during runtime (thinking back, it sounds ridiculous that I even tried it).

My question is: Can I find a phase in the build lifecycle, where I can find and modify the dependencies? Is there another workaround to solve my problem?

答:
The technical answer to your questions is that you can use either:

A configuration.incoming.beforeResolve hook to do it last minute, only when the configuration really needs to be resolved.

Use an afterEvaluate block, assuming all the other dependencies are not defined in an afterEvaluate themselves.

However, the right solution would be to leverage the dependency management engine of Gradle and effectively declare that your root project, the one building the EAR, has dependencies on the specific configurations of the subprojects.

Not knowing your full setup and details, I believe the above would still be the more correct solution, though you may have to filter the subproject artifacts from the resulting graph.

Ideas on how this works in recent Gradle version: https://docs.gradle.org/6.2/userguide/cross_project_publications.html Most of the things explained there should work with the latest 5.x versions.

Body:
We are running our Java EE applications in WAS 8.5 and Gradle 5.* to build them.

In the past we packaged our .war application in an .ear archive, which we then deployed on our server. We had to separate our libraries from our applications and include them as shared libraries, because in our experience it made deploying much slower and in some cases used up all system memory, crashing the server.

After some experimentation, we realized that we don't need to extract the dependencies into shared libraries, because we can include them in the lib folder of our .ear archive.

Currently, we get this done by defining the dependencies of our .war application as compileOnly and redefining them as earlib in the root project (which generates the .ear archive). I'm looking for a way to automate this procedure.

The script I used looks something like this:

project.configurations.named('deploy').getAllDependencies().withType(ProjectDependency.class).forEach({dependency ->
    project.configurations.named('earlib').getAllDependencies()
        .addAll(dependency.dependentProject.configurations.named('earlib').getAllDependencies())
})

// This loosely resembles the actual code I used. The thought process is right, it just might have a couple syntax errors.

// Obviously, I defined an `earlib` configuration in the subproject

I tried running this code in the configuration phase, as well as in the doFirst{} section of the ear task. They all had different problems.

The former didn't work, because it seems like in the configuration phase when this code ran, the dependencies weren't configured yet.

The latter didn't work, because I can't just add dependencies during runtime (thinking back, it sounds ridiculous that I even tried it).

My question is: Can I find a phase in the build lifecycle, where I can find and modify the dependencies? Is there another workaround to solve my problem?


问:
PostgreSQL creating trigger which blocks the too much updated rows

I would like to create a trigger procedure, which disable the update transaction when someone want to modify more then 5 records on a table.
I am trying with this code, but not works.

```<code>create FUNCTION tr_test1_trx() RETURNS trigger AS $tr_test1_trx$declare
counter_ integer := 0;
begin
raise notice 'trigger fired';
select COUNT(*) into counter_ from att_test.tr_test1 where object_name = new.object_name;
if counter_>5 then
RAISE EXCEPTION 'ERROR: CANNOT UPDATE MORE THAN 5';
END IF;
END;
$tr_test1_trx$ LANGUAGE plpgsql;

CREATE TRIGGER tr_test1_trx BEFORE INSERT OR UPDATE ON att_test.tr_test1
FOR EACH row EXECUTE PROCEDURE tr_test1_trx();
</code>```

答:
You need a statement level trigger, not a row level trigger for that.

```<code>create or replace function block_mass_changes()
  returns trigger
as
$$
declare
  l_numrows integer;
begin
  select count(*)
    into l_numrows
  from new_rows;
  raise notice 'Rows: %', l_numrows;
  if l_numrows > 5 then
    raise 'Updating or inserting more than 5 rows is not allowed';
  end if;
  return null;
end;
$$
language plpgsql;
</code>```

Then you need to create one trigger for UPDATE and one for INSERT because it's not possible to define a statement level trigger for two actions:

```<code>CREATE TRIGGER block_updates_trigger
    AFTER UPDATE ON att_test.tr_test1
    REFERENCING NEW TABLE AS new_rows
    FOR EACH STATEMENT EXECUTE FUNCTION block_mass_changes();

CREATE TRIGGER block_inserts_trigger
    AFTER INSERT ON att_test.tr_test1
    REFERENCING NEW TABLE AS new_rows
    FOR EACH STATEMENT EXECUTE FUNCTION block_mass_changes();
</code>```

Body:
I would like to create a trigger procedure, which disable the update transaction when someone want to modify more then 5 records on a table.
I am trying with this code, but not works.

create FUNCTION tr_test1_trx() RETURNS trigger AS $tr_test1_trx$declare
counter_ integer := 0;
begin
raise notice 'trigger fired';
select COUNT(*) into counter_ from att_test.tr_test1 where object_name = new.object_name;
if counter_>5 then
RAISE EXCEPTION 'ERROR: CANNOT UPDATE MORE THAN 5';
END IF;
END;
$tr_test1_trx$ LANGUAGE plpgsql;

CREATE TRIGGER tr_test1_trx BEFORE INSERT OR UPDATE ON att_test.tr_test1
FOR EACH row EXECUTE PROCEDURE tr_test1_trx();

Body:
You need a statement level trigger, not a row level trigger for that.

create or replace function block_mass_changes()
  returns trigger
as
$$
declare
  l_numrows integer;
begin
  select count(*)
    into l_numrows
  from new_rows;
  raise notice 'Rows: %', l_numrows;
  if l_numrows > 5 then
    raise 'Updating or inserting more than 5 rows is not allowed';
  end if;
  return null;
end;
$$
language plpgsql;

Then you need to create one trigger for UPDATE and one for INSERT because it's not possible to define a statement level trigger for two actions:

CREATE TRIGGER block_updates_trigger
    AFTER UPDATE ON att_test.tr_test1
    REFERENCING NEW TABLE AS new_rows
    FOR EACH STATEMENT EXECUTE FUNCTION block_mass_changes();

CREATE TRIGGER block_inserts_trigger
    AFTER INSERT ON att_test.tr_test1
    REFERENCING NEW TABLE AS new_rows
    FOR EACH STATEMENT EXECUTE FUNCTION block_mass_changes();