问:
Chaining promises but with different parameters
I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

```<code>app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});
</code>```

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)

答:
If what do you mean is like this :

function multiply(a) {
  return new Promise((resolve, reject) => {
    resolve(a * a)
  })
}

function promise1() {
  return new Promise((resolve, reject) => {
    resolve(5)
  })
}

promise1.then(add).then(res => console.log(res))
```

then the answer is yes.

Body:
I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)

Body:
If what do you mean is like this :

function multiply(a) {
  return new Promise((resolve, reject) => {
    resolve(a * a)
  })
}

function promise1() {
  return new Promise((resolve, reject) => {
    resolve(5)
  })
}

promise1.then(add).then(res => console.log(res))

then the answer is yes.


来源: stackexchange

问:
How to call a command from window pop in wpf
How call a delegate command from window pop up.
I'm showing a pop up window over a window..
The pop up window have button which need to call DelegateCommand from ViewModel.

Below is the code for Window > MyPopUp.xaml.cs

```<code>public partial class MyPopUp : Window
{
  public MyPopUp(){
     InitializeComponent();
    }
}
</code>```

Below is the code for ViewModel> > MyPopUpViewModel.cs

```<code>public class MyPopUpViewModel: BindableBase
{
    public MyPopUpViewModel()
    {
        AddCommand = new DelegateCommand(AddCommandCall);

    }

    private void AddCommandCall()
    {
        /// Command call Code here
    }

    public DelegateCommand AddCommand { get; private set; }

}
</code>```

MyPopUp.xaml code here

```<code><Window x:Class="Project"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:local="clr-namespace:Project.PopUpControls"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
     xmlns:prism="http://prismlibrary.com/"

    mc:Ignorable="d"
    Title="Create Levels" Height="700" Width="900"
    prism:ViewModelLocator.AutoWireViewModel="True">

<Grid>
    <Button
        Command="{Binding DataContext.AddCommand}"
        Content="test"
        Margin="0,5,0,0"
        FontSize="16"
        FontWeight="Normal"
        Width="100"
        HorizontalAlignment="Center"
        HorizontalContentAlignment="Center"
        VerticalAlignment="Top"
        VerticalContentAlignment="Center"
        Foreground="#ffffff"
        Background="#4e4e4e"/>
</Grid>
</code>```

Though when InitializeComponent(); is called in MyPopUp.xaml.cs  the window DataContext get all the commands in it from MyPopUpViewModel.cs

Then when clicked on button on pop up... It should call the command AddCommand, but it is not getting called.

Let me know what I'm missing or sommnething need to be added/change.

Thanks in advance.

答:
Please set DataContext for View</p>

```<code>InitializeComponent();
DataContext = new MyPopUpViewModel();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How call a delegate command from window pop up.
I'm showing a pop up window over a window..
The pop up window have button which need to call DelegateCommand from ViewModel.

Below is the code for Window > MyPopUp.xaml.cs

public partial class MyPopUp : Window
{
  public MyPopUp(){
     InitializeComponent();
    }
}

Below is the code for ViewModel> > MyPopUpViewModel.cs

public class MyPopUpViewModel: BindableBase
{
    public MyPopUpViewModel()
    {
        AddCommand = new DelegateCommand(AddCommandCall);

    }

    private void AddCommandCall()
    {
        /// Command call Code here
    }

    public DelegateCommand AddCommand { get; private set; }

}

MyPopUp.xaml code here

<Window x:Class="Project"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:local="clr-namespace:Project.PopUpControls"
    xmlns:system="clr-namespace:System;assembly=mscorlib"
     xmlns:prism="http://prismlibrary.com/"

    mc:Ignorable="d"
    Title="Create Levels" Height="700" Width="900"
    prism:ViewModelLocator.AutoWireViewModel="True">

<Grid>
    <Button
        Command="{Binding DataContext.AddCommand}"
        Content="test"
        Margin="0,5,0,0"
        FontSize="16"
        FontWeight="Normal"
        Width="100"
        HorizontalAlignment="Center"
        HorizontalContentAlignment="Center"
        VerticalAlignment="Top"
        VerticalContentAlignment="Center"
        Foreground="#ffffff"
        Background="#4e4e4e"/>
</Grid>

Though when InitializeComponent(); is called in MyPopUp.xaml.cs  the window DataContext get all the commands in it from MyPopUpViewModel.cs

Then when clicked on button on pop up... It should call the command AddCommand, but it is not getting called.

Let me know what I'm missing or sommnething need to be added/change.

Thanks in advance.

Body:
Please set DataContext for View

InitializeComponent();
DataContext = new MyPopUpViewModel();


问:
JTable use RowFilter to compare two columns
I have a JTable with a certain number of columns (all String). I would like to implement a filter that shows only the rows where the column2 and the column3 containing the same string.
Is it possible? I tried with the regExp but I don't see the way to compare table cell values.

答:
simply implement RowFilter directly:

```<code>  RowFilter filter = new RowFilter<Object, Integer>() {

       @Override
       public boolean include(Entry entry) {
            return entry.getValue(firstColumn).equals(entry.getValue(secondColumn));
       }
  }
</code>```

(null checks and full generics omitted)

ContentLicense: CC BY-SA 3.0

Body:
simply implement RowFilter directly:

  RowFilter filter = new RowFilter<Object, Integer>() {

       @Override
       public boolean include(Entry entry) {
            return entry.getValue(firstColumn).equals(entry.getValue(secondColumn));
       }
  }

(null checks and full generics omitted)


问:
Regular expression capability in AWS-Neptune using Gremlin
I was trying to simulate the "like" search in Neptune using Gremlin. However it is not it.get() function in Neptune. The other graphs like JanusGraph has this available. Is there any alternative for this in Neptune. When we try applying the filter options on the Gremlin provided sample graphs it is working fine. However it doesn't work with Neptune. For e.g. following query works in Gremlin provided sample graph however it doesn't work in Neptune.

g.V().filter{it.get().value('name').matches(".o.")}

g.V().filter{it.get().value('name').matches(".o.")} query working with Factory provided graph in Gremlin. Neptune it was not identifying it.get()

答: in your example above you are essentially sending in-line code (Groovy lambdas) to the Graph engine. It is common for hosted graph databases such as Neptune to not allow the submission of such in-line code snippets for a variety of reasons. Apache TinkerPop 3.4 takes a first step towards adding additional text searching predicates to the Gremlin language itself and avoiding the need for such lambda function usage. Once Neptune has support for Apache Tinkerpop 3.4 you will be able to do things such as startingWith, endingWith and contains searches.


问:
Attaching Application load balancer / Network Load balancer directly with aws Autoscaling group
How do I attach aws Application Load Balancer and Network Load balancer directly with auto-scaling group(ASG)?
In AWS Console only available option is for Classic Load Balancer.
What i want is whenever an instance is launched in autoscaling group it'll start reporting to Application/Network load balancer directly rather manually entering each instance in the target group.

答:
ALB and network load balancer can be added only via target groups/with ec2 mapped ... and not directly like classic load balancers.

Create a target group and follow the below steps;

```<code>Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

On the navigation pane, under Auto Scaling, choose Auto Scaling Groups.

Choose an existing group from the list.

On the Details tab, choose Edit.

Do one of the following:

[Classic Load Balancers] For Load Balancers, choose your load balancer.

[Target groups] For Target Groups, choose your target group.

Choose Save.
</code>```

Body:
ALB and network load balancer can be added only via target groups/with ec2 mapped ... and not directly like classic load balancers.

Create a target group and follow the below steps;

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.

On the navigation pane, under Auto Scaling, choose Auto Scaling Groups.

Choose an existing group from the list.

On the Details tab, choose Edit.

Do one of the following:

[Classic Load Balancers] For Load Balancers, choose your load balancer.

[Target groups] For Target Groups, choose your target group.

Choose Save.


问:
RabbitMQ, .NET Core and Kubernetes (configuration)
I'm trying to set up a few micro services in Kubernetes. Everything is working as expected, except the connection from one micro service to RabbitMQ.

Problem flow:

.NET Core app --> rabbitmq-kubernetes-service.yml --> RabbitMQ

In the .NET Core app the rabbit connection factory config looks like this:

```<code>"RabbitMQ": {
    "Host": "rabbitmq-service",
    "Port": 7000,
    "UserName": "guest",
    "Password": "guest"
}
</code>```

The kubernetes rabbit service looks like this:

```<code>apiVersion: v1
kind: Service
metadata:
  name: rabbitmq-service
spec:
  selector:
    app: rabbitmq
  ports:
    - port: 7000
      targetPort: 5672
</code>```

As well as the rabbit deployment:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbitmq
  labels:
    app: rabbitmq
spec:
  replicas: 1
  selector:
    matchLabels:
      app: rabbitmq
  template:
    metadata:
      labels:
        app: rabbitmq
    spec:
      containers:
        - name: rabbitmq
          image: <private ACR with vanilla cfg - the image is: rabbitmq:3.7.9-management-alpine>
          imagePullPolicy: Always
          resources:
            limits:
              cpu: "1"
              memory: 512Mi
            requests:
              cpu: "0.5"
          ports:
            - containerPort: 5672
</code>```

So this setup is currently not working in k8s. Locally it works like a charm with a basic docker-compose.

However, what I can do in k8s is to go from a LoadBalancer --> to the running rabbit pod and access the management GUI with these config settings.

```
apiVersion: v1
kind: Service
metadata:
  name: rabbitmqmanagement-loadbalancer
spec:
  type: LoadBalancer
  selector:
    app: rabbitmq
  ports:
  - port: 80
    targetPort: 15672
```

Where am I going wrong?

答:
I'm assuming you are running the .NET Core app outside the Kubernetes cluster.
If this is indeed the case then you need to use type: LoadBalancer.

LoadBalancer is used to expose a service to the internet.

ClusterIP exposes the service inside cluster-internal IP. So Service will be only accessible from within the cluster, also this is a default ServiceType.

NodePort exposes the service on each Node's IP at a static port.

For more details regarding Services please check the Kubernetes docs.

You can if the connection is working using a python script:

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(
        pika.ConnectionParameters(host='RABBITMQ_SERVER_IP'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
```

This script will try to connect RABBITMQ_SERVER_IP using port 5672.

Script requires a library pika which can be installed using pip install pika.

Body:
I'm trying to set up a few micro services in Kubernetes. Everything is working as expected, except the connection from one micro service to RabbitMQ.

Problem flow:

.NET Core app --> rabbitmq-kubernetes-service.yml --> RabbitMQ

In the .NET Core app the rabbit connection factory config looks like this:

"RabbitMQ": {
    "Host": "rabbitmq-service",
    "Port": 7000,
    "UserName": "guest",
    "Password": "guest"
}

The kubernetes rabbit service looks like this:

apiVersion: v1
kind: Service
metadata:
  name: rabbitmq-service
spec:
  selector:
    app: rabbitmq
  ports:
    - port: 7000
      targetPort: 5672

As well as the rabbit deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: rabbitmq
  labels:
    app: rabbitmq
spec:
  replicas: 1
  selector:
    matchLabels:
      app: rabbitmq
  template:
    metadata:
      labels:
        app: rabbitmq
    spec:
      containers:
        - name: rabbitmq
          image: <private ACR with vanilla cfg - the image is: rabbitmq:3.7.9-management-alpine>
          imagePullPolicy: Always
          resources:
            limits:
              cpu: "1"
              memory: 512Mi
            requests:
              cpu: "0.5"
          ports:
            - containerPort: 5672

So this setup is currently not working in k8s. Locally it works like a charm with a basic docker-compose.

However, what I can do in k8s is to go from a LoadBalancer --> to the running rabbit pod and access the management GUI with these config settings.

apiVersion: v1
kind: Service
metadata:
  name: rabbitmqmanagement-loadbalancer
spec:
  type: LoadBalancer
  selector:
    app: rabbitmq
  ports:
  - port: 80
    targetPort: 15672

Where am I going wrong?

Body:
I'm assuming you are running the .NET Core app outside the Kubernetes cluster.
If this is indeed the case then you need to use type: LoadBalancer.

LoadBalancer is used to expose a service to the internet.

ClusterIP exposes the service inside cluster-internal IP. So Service will be only accessible from within the cluster, also this is a default ServiceType.

NodePort exposes the service on each Node's IP at a static port.

For more details regarding Services please check the Kubernetes docs.

You can if the connection is working using a python script:

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(
        pika.ConnectionParameters(host='RABBITMQ_SERVER_IP'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()

This script will try to connect RABBITMQ_SERVER_IP using port 5672.

Script requires a library pika which can be installed using pip install pika.


问:
Change the border of a rectangle on hover in pygame
I have a rectangle :

```<code>PlayButton = pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(324, 380, 354, 35))
</code>```

and I want to make the border of the rectangle change colour say to red whenever the user hovered over the rectangle

```<code># Checks if the rectangle is hovered over
if PlayButton.collidepoint(pygame.mouse.get_pos()):
            print ('mouse is over newGameButton')
</code>```

Thanks

答:
Set a state variable when the the muose hover:

hover = PlayButton.collidepoint(pygame.mouse.get_pos())
```

<p>Draw an additional <code>pygame.draw.rect()</code> where the <code>width</code> parameter is set:</p>

<p>e.g. red border with a thickness of 3</p>

<pre class="lang-py prettyprint-override"><code>if hover:
    pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(324, 380, 354, 35), 3)
</code>```

Body:
I have a rectangle :

PlayButton = pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(324, 380, 354, 35))

and I want to make the border of the rectangle change colour say to red whenever the user hovered over the rectangle

# Checks if the rectangle is hovered over
if PlayButton.collidepoint(pygame.mouse.get_pos()):
            print ('mouse is over newGameButton')

Thanks

Body:
Set a state variable when the the muose hover:

hover = PlayButton.collidepoint(pygame.mouse.get_pos())

Draw an additional pygame.draw.rect() where the width parameter is set:

e.g. red border with a thickness of 3

if hover:
    pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(324, 380, 354, 35), 3)


问:
Creating new column in Spark using lit()
I'm quite new to Spark and Python so perhaps this is really obvious to someone more experienced.

I've created one column manually, and want to create another column where all values are 's'. The course I'm taking suggests using the lit() function. However, I cannot for the life of me figure out how. This code gives a this error: "TypeError: 'Column' object is not callable"

```<code>wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word'])
wordsDF.show()
from pyspark.sql.functions import lit, concat
pluralDF = ([(wordsDF.word.lit(),'s',)], ['words', 's'])
pluralDF.show()
</code>```

(I use the the show function to display the result to make sure I've got it right. If I only run line 1 and 2, it shows my list of animals, but line 4 and 5 fail.)

The code given by the tutor as a hint is this (for line 4):

```<code>pluralDF = wordsDF.<FILL IN>
</code>```

Any help is much appreciated. Thanks!

答:
try:

pluralDF = wordsDF.withColumn("words", lit('s'))

Body:
I'm quite new to Spark and Python so perhaps this is really obvious to someone more experienced.

I've created one column manually, and want to create another column where all values are 's'. The course I'm taking suggests using the lit() function. However, I cannot for the life of me figure out how. This code gives a this error: "TypeError: 'Column' object is not callable"

wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word'])
wordsDF.show()
from pyspark.sql.functions import lit, concat
pluralDF = ([(wordsDF.word.lit(),'s',)], ['words', 's'])
pluralDF.show()

(I use the the show function to display the result to make sure I've got it right. If I only run line 1 and 2, it shows my list of animals, but line 4 and 5 fail.)

The code given by the tutor as a hint is this (for line 4):

pluralDF = wordsDF.<FILL IN>

Any help is much appreciated. Thanks!


问:
Go synchronization and concurrency model
I'm a new Go learner, and I'm following gobyexample.com to learn the basics. When I reach the "closing channels" section, the tutorial inserts this code snippet (I'll remove original comments):

    package main

    import "fmt"

    func main() {
        jobs := make(chan int, 5)
        done := make(chan bool)

       go func() {
           for {
               j, more := <-jobs
               if more {
                   fmt.Println("received job", j)
               } else {
                   fmt.Println("received all jobs")
                   done <- true
                   return
               }
           }
       }()

       for j := 1; j <= 18; j++ {
           jobs <- j
           fmt.Println("sent job", j)
       }
       close(jobs)
       fmt.Println("sent all jobs")

       <-done
    }
```

<p>The original code was setting a 3 instead of a 18 in the job sender loop.</p>

<p>Executing this code in play.golang.org it is what I don't fully understand. It always outputs the following:</p>

```sent job 1
sent job 2
sent job 3
sent job 4
sent job 5
received job 1
received job 2
received job 3
received job 4
received job 5
received job 6
sent job 6
sent job 7
sent job 8
sent job 9
sent job 10
sent job 11
sent job 12
received job 7
received job 8
received job 9
received job 10
received job 11
received job 12
received job 13
sent job 13
sent job 14
sent job 15
sent job 16
sent job 17
sent job 18
sent all jobs
received job 14
received job 15
received job 16
received job 17
received job 18
received all jobs
```

So I understand that the "queue" of a channel (I'm aware this terminology is not the most accurate, but for the purpose of learning myself it is what I understand about what a channel is) is of size 5 so the first 10 log messages are fine for me.

But how can be the message 6 and 13 be output their reception prior than their actual sending? How can be 7 messages sent in a row, if the channel size is 5? What am I missing from this?

答:
But how can be the message 6 and 13 be output their reception prior than their actual sending?

We only know fmt.Println("received job", j) was printed before fmt.Println("sent job", j) was printed, and this is plausible in concurrent working code.

How can be 7 messages sent in a row, if the channel size is 5?

Again, because we dont know exactly which statement prints out first, this can be expected. The Queue can already be reduced and we still are printing.

Body:
I'm a new Go learner, and I'm following gobyexample.com to learn the basics. When I reach the "closing channels" section, the tutorial inserts this code snippet (I'll remove original comments):

    package main

    import "fmt"

    func main() {
        jobs := make(chan int, 5)
        done := make(chan bool)

       go func() {
           for {
               j, more := <-jobs
               if more {
                   fmt.Println("received job", j)
               } else {
                   fmt.Println("received all jobs")
                   done <- true
                   return
               }
           }
       }()

       for j := 1; j <= 18; j++ {
           jobs <- j
           fmt.Println("sent job", j)
       }
       close(jobs)
       fmt.Println("sent all jobs")

       <-done
    }

The original code was setting a 3 instead of a 18 in the job sender loop.

Executing this code in play.golang.org it is what I don't fully understand. It always outputs the following:

sent job 1
sent job 2
sent job 3
sent job 4
sent job 5
received job 1
received job 2
received job 3
received job 4
received job 5
received job 6
sent job 6
sent job 7
sent job 8
sent job 9
sent job 10
sent job 11
sent job 12
received job 7
received job 8
received job 9
received job 10
received job 11
received job 12
received job 13
sent job 13
sent job 14
sent job 15
sent job 16
sent job 17
sent job 18
sent all jobs
received job 14
received job 15
received job 16
received job 17
received job 18
received all jobs

So I understand that the "queue" of a channel (I'm aware this terminology is not the most accurate, but for the purpose of learning myself it is what I understand about what a channel is) is of size 5 so the first 10 log messages are fine for me.

But how can be the message 6 and 13 be output their reception prior than their actual sending? How can be 7 messages sent in a row, if the channel size is 5? What am I missing from this?


问:
How can I solve this stream reading problem?
I am trying to read the response from an URL sending JSON body. But my code is not being able to read the complete response. There is a problem in my code but I am not getting that.

```<code>val url: URL = new URL("https://jsonplaceholder.typicode.com/todos/1")
val httpsConnection: HttpsURLConnection = url.openConnection().asInstanceOf[HttpsURLConnection]
httpsConnection.setRequestMethod("GET")
httpsConnection.setRequestProperty("Accept", "application/json")
httpsConnection.setRequestProperty("Accept-Language", "en_US")
val streamReader: InputStreamReader = new InputStreamReader(httpsConnection.getInputStream)
val bufferedReader = new BufferedReader(streamReader)
val stringBuffer: StringBuffer =new StringBuffer()
while(bufferedReader.readLine() != null){
  stringBuffer.append(bufferedReader.readLine())
}

println(stringBuffer.toString)
</code>```

This above code is not giving me the actual result.
But if I avoid the regular Java style and use scala source:

```<code>Source.fromInputStream(httpsConnection.getInputStream,"UTF8").getLines().foreach(println)
</code>```

this gives the actual JSON.

What is the problem in my first section of codes?

答:
In this place:

```<code>while(bufferedReader.readLine() != null){
  stringBuffer.append(bufferedReader.readLine())
}
</code>```

you're calling readLine twice first to check if it's not null, then to append to stringBuffer. But actually, the second call gets another line, so you're losing every second line.

The usual way to read buffered stream in Java  is:

```<code>String line;

while ((line = r.readLine()) != null) {
   // do your stuff...
}
</code>```

but assignments in Scala returns Unit so it won't work.

So maybe using Stream.continually would be way to go?

```<code>Stream
    .continually(bufferedReader.readLine())
    .takeWhile(_ != null)
    .foreach(stringBuffer.append)
</code>```

Body:
I am trying to read the response from an URL sending JSON body. But my code is not being able to read the complete response. There is a problem in my code but I am not getting that.

val url: URL = new URL("https://jsonplaceholder.typicode.com/todos/1")
val httpsConnection: HttpsURLConnection = url.openConnection().asInstanceOf[HttpsURLConnection]
httpsConnection.setRequestMethod("GET")
httpsConnection.setRequestProperty("Accept", "application/json")
httpsConnection.setRequestProperty("Accept-Language", "en_US")
val streamReader: InputStreamReader = new InputStreamReader(httpsConnection.getInputStream)
val bufferedReader = new BufferedReader(streamReader)
val stringBuffer: StringBuffer =new StringBuffer()
while(bufferedReader.readLine() != null){
  stringBuffer.append(bufferedReader.readLine())
}

println(stringBuffer.toString)

This above code is not giving me the actual result.
But if I avoid the regular Java style and use scala source:

Source.fromInputStream(httpsConnection.getInputStream,"UTF8").getLines().foreach(println)

this gives the actual JSON.

What is the problem in my first section of codes?

Body:
In this place:

while(bufferedReader.readLine() != null){
  stringBuffer.append(bufferedReader.readLine())
}

you're calling readLine twice first to check if it's not null, then to append to stringBuffer. But actually, the second call gets another line, so you're losing every second line.

The usual way to read buffered stream in Java  is:

String line;

while ((line = r.readLine()) != null) {
   // do your stuff...
}

but assignments in Scala returns Unit so it won't work.

So maybe using Stream.continually would be way to go?

Stream
    .continually(bufferedReader.readLine())
    .takeWhile(_ != null)
    .foreach(stringBuffer.append)


问:
How to reference IdentityDbContext in database project shared across solution
I would like to take advantage of the IdentityDbContext that comes out of the box in Visual Studio templates for ASP.NET Core projects. However, I would like my entities and migrations to live in a shared project to be referenced by different components of the solution (Web, API, background services, etc.).

My shared database project was going to be a .NET Standard project, but it looks like I'll have to add a reference to Microsoft.AspNetCore.Identity.EntityFrameworkCore. It feels weird introducing to a Standard project a dependency on a Core assembly that is specifically for ASP.NET. Will that pose any problems?

答:
You must inherit some of Identity classes(IdentityUser) for your Entity objects so you must reference the Microsoft.AspNetCore.Identity.EntityFrameworkCore but I do not recommend   to store Identity classes with other Entity classes related to your business layer.

Identity is about infrastructure of your project. Just store Identity related classes Dbbontext, entity classes and services on the same project that you already store Db access codes thats reference EntityFrameworkCore.

Holding two different projects on solution that reference EntityFrameworkCore just a violation of seperation of concerns not more. If you want to hold 2 different projects just use same versions of EfCore.


问:
Trying to access dataTable variable outside ajax is giving undefined
I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.

I'm doing the same as in this example, only difference is the data is coming from an Ajax request.

Can you please help me understand why is that happening?

$(document).ready(function() {
  var campId;
  var t_OmnitureCode;

  // Campaign input autocomplete
  $("#campaign").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "promotion",
        type: "GET",
        data: {
          term: request.term,
          action: "searchCampaign"
        },
        dataType: "json",
        success: function(data) {
          if (!data.length) {
            var result = [{
              label: "no match found",
              value: "-1"
            }];
            response(result);
          } else {
            response($.map(data, function(item) {
              return {
                label: item.name,
                value: item.campaignId
              }
            }));
          }
        }
      });
    },
    select: function(event, ui) {
      event.preventDefault();
      campId = ui.item.value;
      if (campId != "-1") {
        this.value = ui.item.label;

        // This will apply datatables getting the content from an Ajax call
        t_OmnitureCode = applyDataTableOmnitureCode(campId);
      }
    },
    focus: function(event, ui) {
      event.preventDefault();
      this.value = ui.item.label;
    }
  });

  // Handling form submission
  $("#frm_promotion").on("submit", function(e) {
    var form = this;
    // Variable for datatable "t_OmnitureCode" is undefined below
    var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
```

<p><strong>EDIT:</strong>
Just realized that even while assigning the variable (<code>t_OmnitureCode = applyDataTableOmnitureCode(campId);</code>) it is undefined, not sure why.</p>

<p>Here is the applyDataTableOmnitureCode code:</p>

```function applyDataTableOmnitureCode(campId) {
    $("#tbl_omnitureCode").DataTable({
        destroy: true,
        scrollX: true,
        fixedColumns: {
            leftColumns: 1
        },
        "ajax": {
            "url": "promotion",
            "type": "GET",
            "data": {
                action: "searchOmnitureCodesByCampaignId",
                campaignId: campId
            },
            "dataSrc": ""
        },
        "columns": [
            { "data": "key" },
            { "data": "omnitureCode" },
            { "data": "urlAppName" },
            { "data": "language" },
            { "data": "channel" },
            { "data": "createDateTime", "defaultContent": "" },
            { "data": "updateDateTime", "defaultContent": "" }
        ],
        "columnDefs": [
            { "targets": 0, "checkboxes": { "selectRow": true } }
        ],
        "select": {
            "style": "multi"
        },
        "order": [[1, "asc"]],
        "fnInitComplete": function() {
            $("#omnitureCodeSection").show();
        }
    });
};
```

答:
It's a matter of scope : You declare the variable table inside $(document).ready function.
You may want to put it outside in the global scope :

var table;

$(document).ready(function() {
  table = $('#example').DataTable({

...
});

Body:
I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.

I'm doing the same as in this example, only difference is the data is coming from an Ajax request.

Can you please help me understand why is that happening?

$(document).ready(function() {
  var campId;
  var t_OmnitureCode;

  // Campaign input autocomplete
  $("#campaign").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "promotion",
        type: "GET",
        data: {
          term: request.term,
          action: "searchCampaign"
        },
        dataType: "json",
        success: function(data) {
          if (!data.length) {
            var result = [{
              label: "no match found",
              value: "-1"
            }];
            response(result);
          } else {
            response($.map(data, function(item) {
              return {
                label: item.name,
                value: item.campaignId
              }
            }));
          }
        }
      });
    },
    select: function(event, ui) {
      event.preventDefault();
      campId = ui.item.value;
      if (campId != "-1") {
        this.value = ui.item.label;

        // This will apply datatables getting the content from an Ajax call
        t_OmnitureCode = applyDataTableOmnitureCode(campId);
      }
    },
    focus: function(event, ui) {
      event.preventDefault();
      this.value = ui.item.label;
    }
  });

  // Handling form submission
  $("#frm_promotion").on("submit", function(e) {
    var form = this;
    // Variable for datatable "t_OmnitureCode" is undefined below
    var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();

EDIT:
Just realized that even while assigning the variable (t_OmnitureCode = applyDataTableOmnitureCode(campId);) it is undefined, not sure why.

Here is the applyDataTableOmnitureCode code:

function applyDataTableOmnitureCode(campId) {
    $("#tbl_omnitureCode").DataTable({
        destroy: true,
        scrollX: true,
        fixedColumns: {
            leftColumns: 1
        },
        "ajax": {
            "url": "promotion",
            "type": "GET",
            "data": {
                action: "searchOmnitureCodesByCampaignId",
                campaignId: campId
            },
            "dataSrc": ""
        },
        "columns": [
            { "data": "key" },
            { "data": "omnitureCode" },
            { "data": "urlAppName" },
            { "data": "language" },
            { "data": "channel" },
            { "data": "createDateTime", "defaultContent": "" },
            { "data": "updateDateTime", "defaultContent": "" }
        ],
        "columnDefs": [
            { "targets": 0, "checkboxes": { "selectRow": true } }
        ],
        "select": {
            "style": "multi"
        },
        "order": [[1, "asc"]],
        "fnInitComplete": function() {
            $("#omnitureCodeSection").show();
        }
    });
};


问:
Pentaho - upload file using API
I need to upload a file using an API.

I tried REST CLIENT and didn't find any options.
Tried with HTTP POST and that responded with 415.

Please suggest how to accomplish this

答:
This solution uses only standard classes of jre 7. Add a step Modified Java Script Value in your transformation. You will have to add two columns in the flow: URL_FORM_POST_MULTIPART_COLUMN and FILE_URL_COLUMN, you can add as many files as you want, you will just have to call outputStreamToRequestBody.write more times.

```<code>    try
    {
        //in this step you will need to add two columns from the previous flow -> URL_FORM_POST_MULTIPART_COLUMN, FILE_URL_COLUMN
        var serverUrl =  new java.net.URL(URL_FORM_POST_MULTIPART_COLUMN);

        var boundaryString = "999aaa000zzz09za";
        var openBoundary  = java.lang.String.format("\n\n--%s\nContent-Disposition: form-data\nContent-Type: text/xml\n\n" , boundaryString);
        var closeBoundary = java.lang.String.format("\n\n--%s--\n", boundaryString);

        // var netIPSocketAddress = java.net.InetSocketAddress("127.0.0.1", 8888);
        // var proxy = java.net.Proxy(java.net.Proxy.Type.HTTP , netIPSocketAddress);
        // var urlConnection = serverUrl.openConnection(proxy);
        var urlConnection = serverUrl.openConnection();

        urlConnection.setDoOutput(true); // Indicate that we want to write to the HTTP request body
        urlConnection.setRequestMethod("POST");
        //urlConnection.addRequestProperty("Authorization", "Basic " + Authorization);
        urlConnection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);

        var outputStreamToRequestBody = urlConnection.getOutputStream();

        outputStreamToRequestBody.write(openBoundary.getBytes(java.nio.charset.StandardCharsets.UTF_8));
        outputStreamToRequestBody.write(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(FILE_URL_COLUMN)));
        outputStreamToRequestBody.write(closeBoundary.getBytes(java.nio.charset.StandardCharsets.UTF_8));

        outputStreamToRequestBody.flush();

        var httpResponseReader = new java.io.BufferedReader(new java.io.InputStreamReader(urlConnection.getInputStream()));

        var lineRead = "";
        var finalText = "";
        while((lineRead = httpResponseReader.readLine()) != null) {
            finalText += lineRead;
        }

        var status = urlConnection.getResponseCode();
        var result = finalText;
        var time   = new Date();

    }
    catch(e)
    {
        Alert(e);
    }
</code>```

Title: Pentaho - upload file using API

Body:
This solution uses only standard classes of jre 7. Add a step Modified Java Script Value in your transformation. You will have to add two columns in the flow: URL_FORM_POST_MULTIPART_COLUMN and FILE_URL_COLUMN, you can add as many files as you want, you will just have to call outputStreamToRequestBody.write more times.

    try
    {
        //in this step you will need to add two columns from the previous flow -> URL_FORM_POST_MULTIPART_COLUMN, FILE_URL_COLUMN
        var serverUrl =  new java.net.URL(URL_FORM_POST_MULTIPART_COLUMN);

        var boundaryString = "999aaa000zzz09za";
        var openBoundary  = java.lang.String.format("\n\n--%s\nContent-Disposition: form-data\nContent-Type: text/xml\n\n" , boundaryString);
        var closeBoundary = java.lang.String.format("\n\n--%s--\n", boundaryString);

        // var netIPSocketAddress = java.net.InetSocketAddress("127.0.0.1", 8888);
        // var proxy = java.net.Proxy(java.net.Proxy.Type.HTTP , netIPSocketAddress);
        // var urlConnection = serverUrl.openConnection(proxy);
        var urlConnection = serverUrl.openConnection();

        urlConnection.setDoOutput(true); // Indicate that we want to write to the HTTP request body
        urlConnection.setRequestMethod("POST");
        //urlConnection.addRequestProperty("Authorization", "Basic " + Authorization);
        urlConnection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);

        var outputStreamToRequestBody = urlConnection.getOutputStream();

        outputStreamToRequestBody.write(openBoundary.getBytes(java.nio.charset.StandardCharsets.UTF_8));
        outputStreamToRequestBody.write(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(FILE_URL_COLUMN)));
        outputStreamToRequestBody.write(closeBoundary.getBytes(java.nio.charset.StandardCharsets.UTF_8));

        outputStreamToRequestBody.flush();

        var httpResponseReader = new java.io.BufferedReader(new java.io.InputStreamReader(urlConnection.getInputStream()));

        var lineRead = "";
        var finalText = "";
        while((lineRead = httpResponseReader.readLine()) != null) {
            finalText += lineRead;
        }

        var status = urlConnection.getResponseCode();
        var result = finalText;
        var time   = new Date();

    }
    catch(e)
    {
        Alert(e);
    }


问:
Why does compiling this code result in a syntax error?
I wrote the following code but i am getting the error as i mentioned can any one tell</p>

```<code>protected void btnGenerate_Click(object sender, EventArgs e)
{
    DataRow[] dRow;
    DataTable dt = new DataTable();
    foreach (GridViewRow grRow in grdACH.Rows)
    {
        CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
        if (chkItem.Checked)
        {
            chkItm = true;
            chkcnt++;
            strBankTypeID = ((Label)grRow.FindControl("lblBankType")).Text.ToString();
            strBnkArray.Append(strBankTypeID);
            strBnkArray.Append(",");
        }
    }
    oEmpDeposits.getEmpDepositDetails(out local_ds, strFedTaxId, PayperiodNumber, PayrollYear, strPayFreqType);

for (int i = 0; i < local_ds.Tables[0].Rows.Count; i++)
    {
        string strTrim = strBnkArray.ToString().TrimEnd(',');
        strTrim = "BankAccountTypeID='" + strTrim[i] + "'";
        if (strTrim.Contains("BankAccountTypeID=',"))
        {
            strTrim = "BankAccountTypeID='" + strTrim[i] + "'";
        }

        dRow = local_ds.Tables[0].Select(strTrim);
    }
}
</code>```

答:
The syntax error comes from this statement:

```<code>dRow = local_ds.Tables[0].Select(strBnkArray.ToString().TrimEnd(','));
</code>```

There is something wrong with the expression you are trying to use.

That expression is made up from this:

```<code>strBnkArray.ToString().TrimEnd(',')
</code>```

Check what that is and you find the answer. Like this perhaps:

```<code>string mySelectStatement = strBnkArray.ToString().TrimEnd(',');
dRow = local_ds.Tables[0].Select(mySelectStatement);
</code>```

Body:
I wrote the following code but i am getting the error as i mentioned can any one tell

protected void btnGenerate_Click(object sender, EventArgs e)
{
    DataRow[] dRow;
    DataTable dt = new DataTable();
    foreach (GridViewRow grRow in grdACH.Rows)
    {
        CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
        if (chkItem.Checked)
        {
            chkItm = true;
            chkcnt++;
            strBankTypeID = ((Label)grRow.FindControl("lblBankType")).Text.ToString();
            strBnkArray.Append(strBankTypeID);
            strBnkArray.Append(",");
        }
    }
    oEmpDeposits.getEmpDepositDetails(out local_ds, strFedTaxId, PayperiodNumber, PayrollYear, strPayFreqType);

for (int i = 0; i < local_ds.Tables[0].Rows.Count; i++)
    {
        string strTrim = strBnkArray.ToString().TrimEnd(',');
        strTrim = "BankAccountTypeID='" + strTrim[i] + "'";
        if (strTrim.Contains("BankAccountTypeID=',"))
        {
            strTrim = "BankAccountTypeID='" + strTrim[i] + "'";
        }

        dRow = local_ds.Tables[0].Select(strTrim);
    }
}

Body:
The syntax error comes from this statement:

dRow = local_ds.Tables[0].Select(strBnkArray.ToString().TrimEnd(','));

There is something wrong with the expression you are trying to use.

That expression is made up from this:

strBnkArray.ToString().TrimEnd(',')

Check what that is and you find the answer. Like this perhaps:

string mySelectStatement = strBnkArray.ToString().TrimEnd(',');
dRow = local_ds.Tables[0].Select(mySelectStatement);


问:
Text not being set in inflated view's TextView
I have a custom view that inflates over an activity:

```<code>class NeedMoreTimeScreen @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {

    fun inflate(context: Context) {

        LayoutInflater
            .from(context)
            .inflate(R.layout.screen_more_time, this, true)

        val inflatedView = LayoutInflater
            .from(context)
            .inflate(R.layout.screen_more_time, this, true)

        inflatedView.visibility = View.VISIBLE

        val countDownTextView = inflatedView.findViewById<TextView>(R.id.countDownText)

        countDownTextView.text = "text I want to appear"
    }
}
</code>```

.xml for the custom view:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <RelativeLayout
            android:id="@+id/holder"
            android:layout_width="768px"
            android:layout_height="840px"
            android:background="@color/main_background">

        <TextView
                android:text="10s"
                android:textAppearance="@style/ScreenTitle"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="160px"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/countDownText"/>

    </RelativeLayout>
</FrameLayout>
</code>```

The text appears in the TextView when I give it text in its .xml, but setting it programmatically does not appear to be executed. Why?

答:
Try below code,</p>

```<code>public class NeedMoreTimeScreen : RelativeLayout
{
    constructor(context: Context?) : super(context)
    {
        init();
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    {
        init();
    }
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        init();
    }

    private fun init()
    {
        // apply your inflation code here

        val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        layoutInflater.inflate(R.layout.screen_more_time, this, true)

        countDownTextView.text = "text I want to appear"
    }
}
</code>```

Body:
I have a custom view that inflates over an activity:

class NeedMoreTimeScreen @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {

    fun inflate(context: Context) {

        LayoutInflater
            .from(context)
            .inflate(R.layout.screen_more_time, this, true)

        val inflatedView = LayoutInflater
            .from(context)
            .inflate(R.layout.screen_more_time, this, true)

        inflatedView.visibility = View.VISIBLE

        val countDownTextView = inflatedView.findViewById<TextView>(R.id.countDownText)

        countDownTextView.text = "text I want to appear"
    }
}

.xml for the custom view:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <RelativeLayout
            android:id="@+id/holder"
            android:layout_width="768px"
            android:layout_height="840px"
            android:background="@color/main_background">

        <TextView
                android:text="10s"
                android:textAppearance="@style/ScreenTitle"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="160px"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/countDownText"/>

    </RelativeLayout>
</FrameLayout>

The text appears in the TextView when I give it text in its .xml, but setting it programmatically does not appear to be executed. Why?

Body:
Try below code,

public class NeedMoreTimeScreen : RelativeLayout
{
    constructor(context: Context?) : super(context)
    {
        init();
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    {
        init();
    }
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        init();
    }

    private fun init()
    {
        // apply your inflation code here

        val layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        layoutInflater.inflate(R.layout.screen_more_time, this, true)

        countDownTextView.text = "text I want to appear"
    }
}


问:
Trigger standard HTML validation (form) without using submit button?
Anyone who know how I can trigger the standard HTML5 validation in a form without using a submit button? (JavaScript or jQuery).

I do not want to send POST/GET request, only do the validation.

答:
This is my implementation of the solution suggested by @mhm, where I discarded the use of jQuery.

The variable formId contains the id of the form and msg is an object with messages of my application.

This implementation tries to notify the user with the native HTML 5 error messages, if not possible then alert a generic form error message.

If there are no errors I submit the form.

```<code>let applyForm = document.getElementById(formId);

if (!applyForm.checkValidity()) {
  if (applyForm.reportValidity) {
    applyForm.reportValidity();
  } else {
    alert(msg.ieErrorForm);
  }
} else {
  applyForm.submit();
}
</code>```

Body:
This is my implementation of the solution suggested by @mhm, where I discarded the use of jQuery.

The variable formId contains the id of the form and msg is an object with messages of my application.

This implementation tries to notify the user with the native HTML 5 error messages, if not possible then alert a generic form error message.

If there are no errors I submit the form.

let applyForm = document.getElementById(formId);

if (!applyForm.checkValidity()) {
  if (applyForm.reportValidity) {
    applyForm.reportValidity();
  } else {
    alert(msg.ieErrorForm);
  }
} else {
  applyForm.submit();
}


问:
Python HTTP request with json data isn't getting php response with json data
I am trying to send a python http request with some json data (I will use this json data in a later case) to server. Server should give a response with some json data (using PHP). Unfortunately there is no any response even though request status code is 200. Any help please!</p>

```<code>#request.py

import requests
import urllib3
import json
import os
import time
import sys

#http Request
url = 'http://localhost/response.php'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

while True:

    postMessage = '{"Info": {"ID": 1, "IP": "192.168.1.1"}}'
    response = requests.post(url, json=postMessage, headers=headers)
    #trying to decode the response
    try:
        decodedresponse = json.loads(response.text)
        print(decodedresponse)

    except(ValueError, KeyError, TypeError):
        print("some Error")

#always getting the above print statement!

    break
</code>```

```<code>#response.php

<?php

if(!empty($_POST['json'])){
  $data = [ 'a', 'b', 'c' ];
  header('Content-type:application/json;charset=utf-8');
  echo json_encode($data);

}
 ?>

</code>```

答:
You should remove quotes on assignment of postMessage in your:

```<code>postMessage = {"Info": {"ID": 1, "IP": "192.168.1.1"}}
</code>```

And change your php code to:

```<code><?php
$data = file_get_contents("php://input");
header('Content-type:application/json;charset=utf-8');
echo json_encode($data);
?>
</code>```

Body:
I am trying to send a python http request with some json data (I will use this json data in a later case) to server. Server should give a response with some json data (using PHP). Unfortunately there is no any response even though request status code is 200. Any help please!

#request.py

import requests
import urllib3
import json
import os
import time
import sys

#http Request
url = 'http://localhost/response.php'
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

while True:

    postMessage = '{"Info": {"ID": 1, "IP": "192.168.1.1"}}'
    response = requests.post(url, json=postMessage, headers=headers)
    #trying to decode the response
    try:
        decodedresponse = json.loads(response.text)
        print(decodedresponse)

    except(ValueError, KeyError, TypeError):
        print("some Error")

#always getting the above print statement!

    break

#response.php

<?php

if(!empty($_POST['json'])){
  $data = [ 'a', 'b', 'c' ];
  header('Content-type:application/json;charset=utf-8');
  echo json_encode($data);

}
 ?>

Body:
You should remove quotes on assignment of postMessage in your:

postMessage = {"Info": {"ID": 1, "IP": "192.168.1.1"}}

And change your php code to:

<?php
$data = file_get_contents("php://input");
header('Content-type:application/json;charset=utf-8');
echo json_encode($data);
?>


问:
Why aren't the table headers empty after I delete them?
I work with Visual Studio 2019, C# and WPF. I try to delete my tableheader dynamically, but i have some problems.

Problem method description:

I have a method, to select the datapackagename and create a Datatable with them as Datatableheaders. That works so far fine, the problem is to delete the old Headers of the table at the second or third run. I tested some different ways to delete the headers but nothing work for me.

When i use the "First try" (show Problem method) nothing will be deleted, because my tableforDataStream hasn't any columns(watched with debugger at second method run). But when I change tableforDataStream to my DataGrid(dgTable3) I have 3 columns there and I can't add new columns to my tableforDataStream(for example watch last picture left table).

The second and third try are most the same like first try with the exception that I can check if there are some columns left. I have already tried tableforDataStream.Reset; but that haven't any sense it's the same solution like "First try"

Problem method:

```<code>private void CreateOverviewTable_Click(object sender, RoutedEventArgs e)
    {
        if (isConnected != 0)
        {
            //tableforDataStream.Columns.Clear();   <--- First try to delete the old tableforDataStream.Header
            if (dgTable3.Columns.Count != 0)
            {
                while(dgTable3.Columns.Count > 0)
                {
                    //tableforDataStream.Columns.RemoveAt(0);   <--- Second try to delete the old tableforDataStream.Header
                    dgTable3.Columns.RemoveAt(0); //<--- Third try to delete the old tableforDataStream.Header
                }
            }

            int anzZeilen = tableSelectedVar.Rows.Count;
            if (anzZeilen != 0)
            {
                dgTable1.Visibility = Visibility.Collapsed;
                dgTable3.Visibility = Visibility.Visible;

                //Create an array for the data packages(VarName, SaveAddress, VarSize)
                string[,] inhaltVar = new string[anzZeilen, 3];

                //Copie all infos from the Variable into the array
                for (int i = 0; i <= anzZeilen - 1; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        inhaltVar[i, j] = tableSelectedVar.Rows[i].ItemArray[j].ToString();
                    }
                }

                //Create for every data package a column inside the tableforDataStream
                for (int k = 0; k <= (inhaltVar.GetLength(0) - 1); k++)
                {
                    try
                    {
                        //insert the VarName as tableforDataStream.Header
                        tableforDataStream.Columns.Add(inhaltVar[k, 0]);
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show("The variable was already send to machine");
                    }
                }
                //send Data over UDP to the machine
                if (isConnected == 1)
                {
                    SendDataToMachine(inhaltVar);
                }
                else
                {
                    MessageBox.Show("Please start first the connection");
                }
            }
            else
            {
                MessageBox.Show("Please insert minimum one Variable for overwatch", null, MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        else
        {
            MessageBox.Show("Please start the conection to machine");
        }
    }
</code>```

This picture show the result of "First try" at the second method run, the red arrows should be deleted and the green arrows should be there.

That's my GUI when i delete my DataGrid(dgTable3) like in the actual "problem method"

EDIT: Add more information and insert the new problem method.

答:
You should clear the columns from the DataGrid or GridView:

```<code>dgTable1.Columns.Clear();
</code>```

Body:
I work with Visual Studio 2019, C# and WPF. I try to delete my tableheader dynamically, but i have some problems.

Problem method description:

I have a method, to select the datapackagename and create a Datatable with them as Datatableheaders. That works so far fine, the problem is to delete the old Headers of the table at the second or third run. I tested some different ways to delete the headers but nothing work for me.

When i use the "First try" (show Problem method) nothing will be deleted, because my tableforDataStream hasn't any columns(watched with debugger at second method run). But when I change tableforDataStream to my DataGrid(dgTable3) I have 3 columns there and I can't add new columns to my tableforDataStream(for example watch last picture left table).

The second and third try are most the same like first try with the exception that I can check if there are some columns left. I have already tried tableforDataStream.Reset; but that haven't any sense it's the same solution like "First try"

Problem method:

private void CreateOverviewTable_Click(object sender, RoutedEventArgs e)
    {
        if (isConnected != 0)
        {
            //tableforDataStream.Columns.Clear();   <--- First try to delete the old tableforDataStream.Header
            if (dgTable3.Columns.Count != 0)
            {
                while(dgTable3.Columns.Count > 0)
                {
                    //tableforDataStream.Columns.RemoveAt(0);   <--- Second try to delete the old tableforDataStream.Header
                    dgTable3.Columns.RemoveAt(0); //<--- Third try to delete the old tableforDataStream.Header
                }
            }

            int anzZeilen = tableSelectedVar.Rows.Count;
            if (anzZeilen != 0)
            {
                dgTable1.Visibility = Visibility.Collapsed;
                dgTable3.Visibility = Visibility.Visible;

                //Create an array for the data packages(VarName, SaveAddress, VarSize)
                string[,] inhaltVar = new string[anzZeilen, 3];

                //Copie all infos from the Variable into the array
                for (int i = 0; i <= anzZeilen - 1; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        inhaltVar[i, j] = tableSelectedVar.Rows[i].ItemArray[j].ToString();
                    }
                }

                //Create for every data package a column inside the tableforDataStream
                for (int k = 0; k <= (inhaltVar.GetLength(0) - 1); k++)
                {
                    try
                    {
                        //insert the VarName as tableforDataStream.Header
                        tableforDataStream.Columns.Add(inhaltVar[k, 0]);
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show("The variable was already send to machine");
                    }
                }
                //send Data over UDP to the machine
                if (isConnected == 1)
                {
                    SendDataToMachine(inhaltVar);
                }
                else
                {
                    MessageBox.Show("Please start first the connection");
                }
            }
            else
            {
                MessageBox.Show("Please insert minimum one Variable for overwatch", null, MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        else
        {
            MessageBox.Show("Please start the conection to machine");
        }
    }

This picture show the result of "First try" at the second method run, the red arrows should be deleted and the green arrows should be there.

That's my GUI when i delete my DataGrid(dgTable3) like in the actual "problem method"

EDIT: Add more information and insert the new problem method.

Body:
You should clear the columns from the DataGrid or GridView:

dgTable1.Columns.Clear();


问:
DatabaseError: unable to open database file on django
I have a Django 1.5 application running on apache2 server and using sqlite database.

The setting for the database is as follow

```<code>DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.sqlite3',
       'NAME': '/var/www/html/project/devdb',
       'USER': '',
       'PASSWORD': '',
       'HOST': '',
       'PORT': '',
   }
}
</code>```

where devdb is the database file generated.

When I run migration commands from the terminal console, it works fine and data is migrated to the database.

But when I visit the application URL, it gives the error

```<code>DatabaseError at /url_path/
attempt to write a readonly database
</code>```

Then I change the permission of file using

```<code>sudo chown 777 devdb
</code>```

Then it starts giving the error

```<code>DatabaseError at /url_path/
unable to open database file
</code>```

ls -la gives following output for the devdb file

```<code>-rwxr-xr-x  1 ubuntu ubuntu   1036 May 11  2018 manage.py
-rw-rw-r--  1 ubuntu ubuntu 291840 May 28 09:31 devdb
</code>```

Getting user of the apache2 running using

```<code>ps -ef | egrep '(httpd|apache2|apache)' | grep -v `whoami` | grep -v root | head -n1 | awk '{print $1}'
</code>```

gives www-data

But changing owner of the file to www-data again gives unable to open database file.

答:
A sqlite db needs to be owned by www-data and so does the directory it is in.

So if your app is in /var/www/app do

```<code>cd /var/www
chown www-data:www-data app
cd app
chown ww-data:www-data devdb
</code>```

Body:
I have a Django 1.5 application running on apache2 server and using sqlite database.

The setting for the database is as follow

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.sqlite3',
       'NAME': '/var/www/html/project/devdb',
       'USER': '',
       'PASSWORD': '',
       'HOST': '',
       'PORT': '',
   }
}

where devdb is the database file generated.

When I run migration commands from the terminal console, it works fine and data is migrated to the database.

But when I visit the application URL, it gives the error

DatabaseError at /url_path/
attempt to write a readonly database

Then I change the permission of file using

sudo chown 777 devdb

Then it starts giving the error

DatabaseError at /url_path/
unable to open database file

ls -la gives following output for the devdb file

-rwxr-xr-x  1 ubuntu ubuntu   1036 May 11  2018 manage.py
-rw-rw-r--  1 ubuntu ubuntu 291840 May 28 09:31 devdb

Getting user of the apache2 running using

ps -ef | egrep '(httpd|apache2|apache)' | grep -v `whoami` | grep -v root | head -n1 | awk '{print $1}'

gives www-data

But changing owner of the file to www-data again gives unable to open database file.

Body:
A sqlite db needs to be owned by www-data and so does the directory it is in.

So if your app is in /var/www/app do

cd /var/www
chown www-data:www-data app
cd app
chown ww-data:www-data devdb


问:
JTable use RowFilter to compare two columns
I have a JTable with a certain number of columns (all String). I would like to implement a filter that shows only the rows where the column2 and the column3 containing the same string.
Is it possible? I tried with the regExp but I don't see the way to compare table cell values.

答:
You can use a RowFilter that compares the data in both columns to each other.

http://download.oracle.com/javase/6/docs/api/javax/swing/RowFilter.html


问:
How to create Action and Call action in MS Dynamics CRM?
How to create Action step by step and Call action in MS Dynamics CRM?
How many ways to call action in MS Dynamics CRM?
What the benefits of action instead of Workflow/plugin?</p>

答:
Actions

Actions are a type of process in Microsoft Dynamics 365. You can invoke actions, including custom actions, directly from a workflow or dialog, without writing code! More information:  Invoke custom actions from a workflow or dialog

Actions can also be invoked by running custom code that uses the Microsoft Dynamics 365 Web services.

You can call actions:

It can be called from both client & server side, enabling the Single Point of Approach (Implement once, consume anywhere), for ex:- From code that executes within a plug-in, custom workflow and any C# code.
From a command that is placed in the application and executes the operation using JavaScript code.
Can receive input parameters and return output parameters in a straight forward manner, similar to an Organization level Web Service
From an integration with another system that uses the Microsoft Dynamics 365 web services.
From a custom client application that uses the Microsoft Dynamics 365 web services.

Why use actions?

Actions open a range of possibilities for composing business logic. Before Actions, the primary way to implement business processes was limited to plug-ins or custom workflow activities. With Actions, you can perform operations, such as Create, Update, Delete, Assign, or Perform Action. Internally, an action creates a custom Dynamics 365 message. With Actions you can create a custom message (for example: submitquote , leadtoax etc.  Once an action is defined and activated, a developer can use that message like any of the other messages provided by the Microsoft Dynamics 365 platform.

Suppose you have button on Quote form which sends information from CRM to another platform (for ex another platform is AX).

Create and activate a Custom Action (Settings > Process)

Now you can call this Action(ofs_submitquotetoax) from JavaScript on some event (OnLoad, OnSave,etc). In this example I am calling the action from SUBMIT QUOTE button on Quote form which sending quote information to other system (AX).

```<code> // Call this below method from Button click event or from any event on the form

// For Alert.showLoding method you can see another Alert.js library

// For Process.callAction method you can see another Process.js library

// You can download Alert.js & Process.js from this Path: https://drive.google.com/drive/folders/0B2CUbevE8v9YMkZlMEhUZ3NJc1U

function submitquote() {

    var actionName = "ofs_submitquoteax";

    var entityName = Xrm.Page.data.entity.getEntityName();

    var entityId = Xrm.Page.data.entity.getId();

    Alert.showLoading("Submitting...", 400, 150);

    var inputParams = [

                      {

                          key: "EntityRef", type: Process.Type.EntityReference,

                          value: new Process.EntityReference(entityName, entityId)

                      }

    ];

    // call process callection method

    Process.callAction(actionName, inputParams, cloneSuccessCallback, errorCallback);

}

function cloneSuccessCallback() {

    Alert.hide();

    Alert.show("Action Success", "", null, "SUCCESS");

    Alert.hide();

    var entityName = Xrm.Page.data.entity.getEntityName();

    var entityId = Xrm.Page.data.entity.getId();

    Xrm.Utility.openEntityForm(entityName, entityId);

    //Xrm.Page.data.refresh();

}

function errorCallback(error, trace) {

    alert(error);

    alert(alert(error));

}
</code>```

e, for this event you can register & trigger a Plugin and receive the input-parameter (in our case we sending input-parameter key as EntityRef in which we are sending entityName and entityId.

Parameters: Action Unique Name, Input Parameters (array), Success Callback (function), Error Callback (function), CRM Base URL (not required on forms/views)

Each Input Parameter object should contain key, value, and type. Types are defined by the Process.Type enum. EntityReference values should be an object containing id and entityType.

The Success Callback function should accept one argument which is an array of output parameters, each containing key, and value.

You can write plugin in below way and access input parameter

```<code>protected override void ExecuteCrmPlugin(LocalPluginContext localContext)

    {   // Register the plugin in PreValidation stage as this plugin will trigger from Javascript (Action)

        if (localContext == null)

        {

            throw new InvalidPluginExecutionException("localContext");

        }

        IPluginExecutionContext context = localContext.PluginExecutionContext;

        if (context.Depth > 1) { return; }

        IOrganizationService service = localContext.OrganizationService;

        ITracingService trace = localContext.TracingService;

        Entity quoteEntity = null;

        EntityReference qEntity = null;

        if (context.InputParameters.Contains("EntityRef") && context.InputParameters["EntityRef"] is EntityReference)

        {

            //if (context.PrimaryEntityName.ToLower() != "quote") { return; }

             qEntity = context.InputParameters["EntityRef"] as EntityReference;

            if (qEntity.LogicalName.ToLower().Equals("quote"))

            {

                try

                {

                    quoteEntity = service.Retrieve("quote", qEntity.Id, new ColumnSet("ofs_parentaccountid", "quotenumber", "revisionnumber", "ofs_well"));

              // Execute Your logic

                }

                catch (Exception ex)

                {

                    trace.Trace(string.Format("Exception Quote_Create_AXIntegration Plugin: {0}", new[] { ex.ToString() }));

                }

            }

        }

        else { return; }

    }
</code>```

Register your plugin and then register the step in below way, you can notice your custom message name in below screen-shot "ofs_submitquoteax";

Ref:https://community.dynamics.com/crm/b/mylifemicrosoftdynamiccrm/archive/2017/04/17/microsoft-dynamics-crm-actions

Body:
Actions

Actions are a type of process in Microsoft Dynamics 365. You can invoke actions, including custom actions, directly from a workflow or dialog, without writing code! More information:  Invoke custom actions from a workflow or dialog

Actions can also be invoked by running custom code that uses the Microsoft Dynamics 365 Web services.

You can call actions:

It can be called from both client & server side, enabling the Single Point of Approach (Implement once, consume anywhere), for ex:- From code that executes within a plug-in, custom workflow and any C# code.
From a command that is placed in the application and executes the operation using JavaScript code.
Can receive input parameters and return output parameters in a straight forward manner, similar to an Organization level Web Service
From an integration with another system that uses the Microsoft Dynamics 365 web services.
From a custom client application that uses the Microsoft Dynamics 365 web services.

Why use actions?

Actions open a range of possibilities for composing business logic. Before Actions, the primary way to implement business processes was limited to plug-ins or custom workflow activities. With Actions, you can perform operations, such as Create, Update, Delete, Assign, or Perform Action. Internally, an action creates a custom Dynamics 365 message. With Actions you can create a custom message (for example: submitquote , leadtoax etc.  Once an action is defined and activated, a developer can use that message like any of the other messages provided by the Microsoft Dynamics 365 platform.

Suppose you have button on Quote form which sends information from CRM to another platform (for ex another platform is AX).

Create and activate a Custom Action (Settings > Process)

Now you can call this Action(ofs_submitquotetoax) from JavaScript on some event (OnLoad, OnSave,etc). In this example I am calling the action from SUBMIT QUOTE button on Quote form which sending quote information to other system (AX).

 // Call this below method from Button click event or from any event on the form

// For Alert.showLoding method you can see another Alert.js library

// For Process.callAction method you can see another Process.js library

// You can download Alert.js & Process.js from this Path: https://drive.google.com/drive/folders/0B2CUbevE8v9YMkZlMEhUZ3NJc1U

function submitquote() {

    var actionName = "ofs_submitquoteax";

    var entityName = Xrm.Page.data.entity.getEntityName();

    var entityId = Xrm.Page.data.entity.getId();

    Alert.showLoading("Submitting...", 400, 150);

    var inputParams = [

                      {

                          key: "EntityRef", type: Process.Type.EntityReference,

                          value: new Process.EntityReference(entityName, entityId)

                      }

    ];

    // call process callection method

    Process.callAction(actionName, inputParams, cloneSuccessCallback, errorCallback);

}

function cloneSuccessCallback() {

    Alert.hide();

    Alert.show("Action Success", "", null, "SUCCESS");

    Alert.hide();

    var entityName = Xrm.Page.data.entity.getEntityName();

    var entityId = Xrm.Page.data.entity.getId();

    Xrm.Utility.openEntityForm(entityName, entityId);

    //Xrm.Page.data.refresh();

}

function errorCallback(error, trace) {

    alert(error);

    alert(alert(error));

}

e, for this event you can register & trigger a Plugin and receive the input-parameter (in our case we sending input-parameter key as EntityRef in which we are sending entityName and entityId.

Parameters: Action Unique Name, Input Parameters (array), Success Callback (function), Error Callback (function), CRM Base URL (not required on forms/views)

Each Input Parameter object should contain key, value, and type. Types are defined by the Process.Type enum. EntityReference values should be an object containing id and entityType.

The Success Callback function should accept one argument which is an array of output parameters, each containing key, and value.

You can write plugin in below way and access input parameter

protected override void ExecuteCrmPlugin(LocalPluginContext localContext)

    {   // Register the plugin in PreValidation stage as this plugin will trigger from Javascript (Action)

        if (localContext == null)

        {

            throw new InvalidPluginExecutionException("localContext");

        }

        IPluginExecutionContext context = localContext.PluginExecutionContext;

        if (context.Depth > 1) { return; }

        IOrganizationService service = localContext.OrganizationService;

        ITracingService trace = localContext.TracingService;

        Entity quoteEntity = null;

        EntityReference qEntity = null;

        if (context.InputParameters.Contains("EntityRef") && context.InputParameters["EntityRef"] is EntityReference)

        {

            //if (context.PrimaryEntityName.ToLower() != "quote") { return; }

             qEntity = context.InputParameters["EntityRef"] as EntityReference;

            if (qEntity.LogicalName.ToLower().Equals("quote"))

            {

                try

                {

                    quoteEntity = service.Retrieve("quote", qEntity.Id, new ColumnSet("ofs_parentaccountid", "quotenumber", "revisionnumber", "ofs_well"));

              // Execute Your logic

                }

                catch (Exception ex)

                {

                    trace.Trace(string.Format("Exception Quote_Create_AXIntegration Plugin: {0}", new[] { ex.ToString() }));

                }

            }

        }

        else { return; }

    }

Register your plugin and then register the step in below way, you can notice your custom message name in below screen-shot "ofs_submitquoteax";

Ref:https://community.dynamics.com/crm/b/mylifemicrosoftdynamiccrm/archive/2017/04/17/microsoft-dynamics-crm-actions


答:
readLine is called twice, and InputStreamReader should use the charset of the source.
Here I took ISO-8859-1 as it will not give an error, as UTF-8 might.
Also readLine drops the line ending, and StringBuilder is faster.</p>

```<code>val streamReader: InputStreamReader = new InputStreamReader(httpsConnection.getInputStream,
    "ISO-8859-1")
val bufferedReader = new BufferedReader(streamReader)
val stringBuilder: StringBuilder = new StringBuilder()
while (true) {
  val line = bufferedReader.readLine();
  if (line == null) {
      break;
  }
  stringBuilder.append(line).append("\r\n");
}
</code>```

Title: How can I solve this stream reading problem?

Body:
readLine is called twice, and InputStreamReader should use the charset of the source.
Here I took ISO-8859-1 as it will not give an error, as UTF-8 might.
Also readLine drops the line ending, and StringBuilder is faster.

val streamReader: InputStreamReader = new InputStreamReader(httpsConnection.getInputStream,
    "ISO-8859-1")
val bufferedReader = new BufferedReader(streamReader)
val stringBuilder: StringBuilder = new StringBuilder()
while (true) {
  val line = bufferedReader.readLine();
  if (line == null) {
      break;
  }
  stringBuilder.append(line).append("\r\n");
}


问:
Connection to server in Docker container on localhost very slow
I wanted to try Docker as a tool for local development — I used docker-compose to spin up 3 containers: one for the database (postgres), front-end (running webpack and node sass in watch mode) and backend (Elixir/Phoenix).

Everything works great, except that when I hit localhost:4000 the page load is really slow — 10-15 seconds just to get the login page, which is static.

I checked the logs from docker-compose and the server response times are fast as usual, which to me it means that something is slowing down the connection to the container.

When I ran the server directly in the Terminal again, everything is pretty fast, e.g. takes 1s to load the same page.

I'm new to Docker so I suspect I might be missing something configuration-wise. Any ideas are appreciated. Thank you!

Configuration

docker-compose.yml

```<code>version: "3.6"

services:
  postgres:
    container_name: postgres
    image: postgres:11.0-alpine
    ports:
      - 5432:5432
    volumes:
      - postgres:/var/lib/postgresql/data

  front-end:
    container_name: front-end
    env_file:
      - "docker/dev/.env"
    build:
      context: "."
      dockerfile: "docker/dev/Dockerfile.front-end"
    volumes:
      - .:/app
      - node_modules:/app/node_modules
      - static:/app/priv/static
    command: npm run dev

  backend:
    container_name: backend
    build:
      context: "."
      dockerfile: "docker/dev/Dockerfile.backend"
    env_file:
      - "docker/dev/.env"
    depends_on:
      - postgres
      - front-end
    ports:
      - 4000:4000
    stdin_open: true
    tty: true
    volumes:
      - .:/app
      - elixir-deps:/app/deps
      - static:/app/priv/static
    command: iex -S mix phx.server

volumes:
  postgres:
  elixir-deps:
  node_modules:
  static:
    driver_opts:
      type: "tmpfs"
      device: "tmpfs"
</code>```

Dockerfile.front-end

```<code>FROM node:8.10-alpine

WORKDIR /app

COPY package.json ./
COPY package-lock.json ./

RUN npm install

COPY . .
</code>```

Dockerfile.backend

```<code>FROM elixir:1.8-alpine

RUN apk update && apk add build-base inotify-tools postgresql-dev

WORKDIR /app

COPY mix.exs ./
COPY mix.lock ./

RUN mix local.hex --force && mix local.rebar --force \
    && mix deps.get && mix deps.compile

COPY . .

EXPOSE 4000
</code>```

Versions & other info:

```<code>MacOS Mojave 10.14.3
Docker Desktop 2.0.0.3 (Engine 18.09.2, Compose: 1.23.2)

MacBook Pro 13" (Early 2015, 16GB RAM/3.1GHz Core i7)
</code>```

答:
Update 5 June 2020:

It is significantly better to use docker-sync for local development.

First make sure you down existing services to remove old volumes.

Then create a docker-sync.yml like so:

```<code>version: "2"
options:
  # Renamed compose file to `docker-compose.dev.yml`
  compose-dev-file-path: 'docker-compose.dev.yml'

syncs:
  # This name should be unique and should not clash with
  # an existing container or service name. You can use it
  # as a volume in docker compose yml.
  project:
    src: '.'
    sync_excludes: ['node_modules', 'deps', '_build']
</code>```

Now you can use the project volume instead of - .:/app for front-end and backend services, e.g.

```<code>    volumes:
      - project:/app:nocopy
      - elixir-deps:/app/deps
      - elixir-build:/app/_build
      - static:/app/priv/static:ro
</code>```

Run docker-sync start to start it in the background, followed by running docker-compose up --build --detach as usual.

Original answer:

As one commenter pointed out (@DavidMaze), there are currently known performance issues with Docker for Mac. How much are they linked to my use case I cannot tell, but after reading the Performance tuning guide in the official docs, I managed to make some progress in performance:

docker-compose.yml

```<code>version: "3.6"

services:
  postgres:
    container_name: postgres
    image: postgres:11.0-alpine
    ports:
      - 5432:5432
    volumes:
      - postgres:/var/lib/postgresql/data

  front-end:
    container_name: front-end
    env_file:
      - "docker/dev/.env"
    build:
      context: "."
      dockerfile: "docker/dev/Dockerfile.front-end"
    volumes:
      - .:/app:delegated
      - node_modules:/app/node_modules
      - static:/app/priv/static
    command: npm run dev

  backend:
    container_name: backend
    build:
      context: "."
      dockerfile: "docker/dev/Dockerfile.backend"
    env_file:
      - "docker/dev/.env"
    depends_on:
      - postgres
      - front-end
    ports:
      - 4000:4000
    stdin_open: true
    tty: true
    volumes:
      - .:/app:delegated
      - elixir-deps:/app/deps
      - elixir-build:/app/_build
      - static:/app/priv/static:ro
    command: iex -S mix phx.server

volumes:
  postgres:
  elixir-deps:
  elixir-build:
  node_modules:
  static:
    driver_opts:
      type: "tmpfs"
      device: "tmpfs"
</code>```

Note the use of :delegated when declaring the .:/app:delegated volumes.

Although this is an improvement, it is still much slower for day-to-day development than running things natively, so I'm welcoming other answers to my question. For the time being, I think that's probably the best solution.

Body:
I wanted to try Docker as a tool for local development — I used docker-compose to spin up 3 containers: one for the database (postgres), front-end (running webpack and node sass in watch mode) and backend (Elixir/Phoenix).

Everything works great, except that when I hit localhost:4000 the page load is really slow — 10-15 seconds just to get the login page, which is static.

I checked the logs from docker-compose and the server response times are fast as usual, which to me it means that something is slowing down the connection to the container.

When I ran the server directly in the Terminal again, everything is pretty fast, e.g. takes 1s to load the same page.

I'm new to Docker so I suspect I might be missing something configuration-wise. Any ideas are appreciated. Thank you!

Configuration

docker-compose.yml

version: "3.6"

services:
  postgres:
    container_name: postgres
    image: postgres:11.0-alpine
    ports:
      - 5432:5432
    volumes:
      - postgres:/var/lib/postgresql/data

  front-end:
    container_name: front-end
    env_file:
      - "docker/dev/.env"
    build:
      context: "."
      dockerfile: "docker/dev/Dockerfile.front-end"
    volumes:
      - .:/app
      - node_modules:/app/node_modules
      - static:/app/priv/static
    command: npm run dev

  backend:
    container_name: backend
    build:
      context: "."
      dockerfile: "docker/dev/Dockerfile.backend"
    env_file:
      - "docker/dev/.env"
    depends_on:
      - postgres
      - front-end
    ports:
      - 4000:4000
    stdin_open: true
    tty: true
    volumes:
      - .:/app
      - elixir-deps:/app/deps
      - static:/app/priv/static
    command: iex -S mix phx.server

volumes:
  postgres:
  elixir-deps:
  node_modules:
  static:
    driver_opts:
      type: "tmpfs"
      device: "tmpfs"

Dockerfile.front-end

FROM node:8.10-alpine

WORKDIR /app

COPY package.json ./
COPY package-lock.json ./

RUN npm install

COPY . .

Dockerfile.backend

FROM elixir:1.8-alpine

RUN apk update && apk add build-base inotify-tools postgresql-dev

WORKDIR /app

COPY mix.exs ./
COPY mix.lock ./

RUN mix local.hex --force && mix local.rebar --force \
    && mix deps.get && mix deps.compile

COPY . .

EXPOSE 4000

Versions & other info:

MacOS Mojave 10.14.3
Docker Desktop 2.0.0.3 (Engine 18.09.2, Compose: 1.23.2)

MacBook Pro 13" (Early 2015, 16GB RAM/3.1GHz Core i7)

Body:
Update 5 June 2020:

It is significantly better to use docker-sync for local development.

First make sure you down existing services to remove old volumes.

Then create a docker-sync.yml like so:

version: "2"
options:
  # Renamed compose file to `docker-compose.dev.yml`
  compose-dev-file-path: 'docker-compose.dev.yml'

syncs:
  # This name should be unique and should not clash with
  # an existing container or service name. You can use it
  # as a volume in docker compose yml.
  project:
    src: '.'
    sync_excludes: ['node_modules', 'deps', '_build']

Now you can use the project volume instead of - .:/app for front-end and backend services, e.g.

    volumes:
      - project:/app:nocopy
      - elixir-deps:/app/deps
      - elixir-build:/app/_build
      - static:/app/priv/static:ro

Run docker-sync start to start it in the background, followed by running docker-compose up --build --detach as usual.

Original answer:

As one commenter pointed out (@DavidMaze), there are currently known performance issues with Docker for Mac. How much are they linked to my use case I cannot tell, but after reading the Performance tuning guide in the official docs, I managed to make some progress in performance:

docker-compose.yml

version: "3.6"

services:
  postgres:
    container_name: postgres
    image: postgres:11.0-alpine
    ports:
      - 5432:5432
    volumes:
      - postgres:/var/lib/postgresql/data

  front-end:
    container_name: front-end
    env_file:
      - "docker/dev/.env"
    build:
      context: "."
      dockerfile: "docker/dev/Dockerfile.front-end"
    volumes:
      - .:/app:delegated
      - node_modules:/app/node_modules
      - static:/app/priv/static
    command: npm run dev

  backend:
    container_name: backend
    build:
      context: "."
      dockerfile: "docker/dev/Dockerfile.backend"
    env_file:
      - "docker/dev/.env"
    depends_on:
      - postgres
      - front-end
    ports:
      - 4000:4000
    stdin_open: true
    tty: true
    volumes:
      - .:/app:delegated
      - elixir-deps:/app/deps
      - elixir-build:/app/_build
      - static:/app/priv/static:ro
    command: iex -S mix phx.server

volumes:
  postgres:
  elixir-deps:
  elixir-build:
  node_modules:
  static:
    driver_opts:
      type: "tmpfs"
      device: "tmpfs"

Note the use of :delegated when declaring the .:/app:delegated volumes.

Although this is an improvement, it is still much slower for day-to-day development than running things natively, so I'm welcoming other answers to my question. For the time being, I think that's probably the best solution.


问:
Chaining promises but with different parameters
I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

```<code>app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});
</code>```

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)

答:
As an another alternative to callback hells and Promise.then.then, You could also use async/await for that :

const loadTextFile = file => new Promise( (resolve, reject) => {
      // Fetch the files etc.
      resolve(data);
})

const loadFiles = async (request, response) => {
  const measureList = await loadTextFile('tables');
  const roleList = await loadTextFile('roles');

  // Do something with roleList and measureList

  response.send(finalData);
}

app.get('/visual', loadFiles);```

Body:
I previously used callbacks for all my nodejs functions that need to access mysql or txt files. This lead to ugly code stacking the callbacks inside of each other so I converted them to promises. How can I chain the promises but with different parameters each time?

I know how to chain them with .then(), but I don't know how to pass different arguments each time.

app.get('/visual', function (request, response) {
    loadTextFile('tables', function (measureList) {
         loadTextFile('roles', function (roleList) {
              // Do something with roleList and measureList
         });
    });
});

This is how my code looked before with the callbacks, how can I convert them to use then()? (I know how to convert loadTextFile to a promise.)


问:
Global Variable with ActiveX Control Elements
I am a bit lost with learning VBA currently and I don't know what topic to google.

In my Excel-Sheet, I have a Button and a ComboBox. By pressing the Button, I load some data into VBA. The title of certain data entries is added as Item into the ComboBox. The other data is added into a jagged array s.

Now, by changing the ComboBox-Selection, I want to access array s. How can I do this?

The code is in the sheet1/workbook control in the VBA Editor

Public Sub CommandButton1_Click()
    Dim s() As Variant

    Code Execution

    For i = 1 To m
        s(i) = SomeArray
    Next i

    For j = 1 To i - 1
        Sheets("Sheet1").ComboBox1.AddItem b(j)
    Next j
End Sub

Public Sub ComboBox1_Change()
    Sheets("Steuerung").Cells(1, 1).Value = ComboBox1.ListIndex
    Sheets("Steuerung").Cells(2, 1).Value = UBound(s, ComboBox1.ListIndex + 1)
End Sub
```

The last line UBound(s, ...) results in an error, since the variable is unknown.

I don't know how to tackle this issue.

PS: Sorry, if I used wrong names but my Excel isn't the english one.

答:
You need to do two things: declare the jagged array as Public at the module level and also be sure to initialize it.  For example, your module can look like this:

```<code>Option Explicit

Public Const MAX_ARRAYS As Long = 25
Public s As Variant      'my jagged array

Public Sub InitializeTheArray()
    '--- initializes the jagged array, only if necessary
    If Not IsArray(s) Then
        '--- perform initialization here...
        '    at least establish some dimensions
        ReDim s(1 To MAX_ARRAYS)
    End If
End Sub

Public Sub CommandButton1_Click()
    InitializeTheArray
    Code Execution
    For i = 1 To m
        s(i) = SomeArray
    Next i

    For j = 1 To i - 1
        Sheets("Sheet1").ComboBox1.AddItem b(j)
    Next j
End Sub

Public Sub ComboBox1_Change()
    InitializeTheArray
    Sheets("Steuerung").Cells(1, 1).Value = ComboBox1.ListIndex
    Sheets("Steuerung").Cells(2, 1).Value = UBound(s, ComboBox1.ListIndex + 1)
End Sub
</code>```

Calling InitializeTheArray within each of your routines can guarantee that the public array is always initialized to some degree.

Body:
I am a bit lost with learning VBA currently and I don't know what topic to google.

In my Excel-Sheet, I have a Button and a ComboBox. By pressing the Button, I load some data into VBA. The title of certain data entries is added as Item into the ComboBox. The other data is added into a jagged array s.

Now, by changing the ComboBox-Selection, I want to access array s. How can I do this?

The code is in the sheet1/workbook control in the VBA Editor

Public Sub CommandButton1_Click()
    Dim s() As Variant

    Code Execution

    For i = 1 To m
        s(i) = SomeArray
    Next i

    For j = 1 To i - 1
        Sheets("Sheet1").ComboBox1.AddItem b(j)
    Next j
End Sub

Public Sub ComboBox1_Change()
    Sheets("Steuerung").Cells(1, 1).Value = ComboBox1.ListIndex
    Sheets("Steuerung").Cells(2, 1).Value = UBound(s, ComboBox1.ListIndex + 1)
End Sub

The last line UBound(s, ...) results in an error, since the variable is unknown.

I don't know how to tackle this issue.

PS: Sorry, if I used wrong names but my Excel isn't the english one.

Body:
You need to do two things: declare the jagged array as Public at the module level and also be sure to initialize it.  For example, your module can look like this:

Option Explicit

Public Const MAX_ARRAYS As Long = 25
Public s As Variant      'my jagged array

Public Sub InitializeTheArray()
    '--- initializes the jagged array, only if necessary
    If Not IsArray(s) Then
        '--- perform initialization here...
        '    at least establish some dimensions
        ReDim s(1 To MAX_ARRAYS)
    End If
End Sub

Public Sub CommandButton1_Click()
    InitializeTheArray
    Code Execution
    For i = 1 To m
        s(i) = SomeArray
    Next i

    For j = 1 To i - 1
        Sheets("Sheet1").ComboBox1.AddItem b(j)
    Next j
End Sub

Public Sub ComboBox1_Change()
    InitializeTheArray
    Sheets("Steuerung").Cells(1, 1).Value = ComboBox1.ListIndex
    Sheets("Steuerung").Cells(2, 1).Value = UBound(s, ComboBox1.ListIndex + 1)
End Sub

Calling InitializeTheArray within each of your routines can guarantee that the public array is always initialized to some degree.


问:
Configure log4j to log all but one level
Using log4j or log4j2 is it possible to configure a logging appender (or a logger) to match all levels but one? E.g. if I want to log all but INFO to one appender (that is, log levels both above and below INFO, but not INFO)?</p>

答:
Updated from comments. You can use  LevelRangeFilter as per D.B. suggestion or create custom level logger.

Levels are ordered (log4j2) as

```<code>Standard Level  intLevel
OFF                0
FATAL             100
ERROR             200
WARN              300
INFO              400
DEBUG             500
TRACE             600
ALL           Integer.MAX_VALUE
</code>```

Therefore if you set log.setLevel(Level.WARN); it will log only WARN, ERROR and FATAL levels.

You can create custom level  with 0<intLevel<100 to log only there.
See here

Body:
Updated from comments. You can use  LevelRangeFilter as per D.B. suggestion or create custom level logger.

Levels are ordered (log4j2) as

Standard Level  intLevel
OFF                0
FATAL             100
ERROR             200
WARN              300
INFO              400
DEBUG             500
TRACE             600
ALL           Integer.MAX_VALUE

Therefore if you set log.setLevel(Level.WARN); it will log only WARN, ERROR and FATAL levels.

You can create custom level  with 0<intLevel<100 to log only there.
See here