问:
Django can't find model property
In my Django project, I have a models.py that looks like this:

from django.db import models

class Battle(models.Model):

    def __str__(self):
        return self.battle_name

    battle_name = models.CharField(max_length=200)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    password = models.CharField(max_length=50)
```

<p>When I drop to the Django shell (<code>python manage.py shell</code>), I can't interact either of the DateTimeField properties.</p>

```$ python manage.py shell
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from battles.models import Battle
>>> Battle.objects.all()
<QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]>
>>> Battle.objects.filter(battle_name='my first battle')
<QuerySet [<Battle: my first battle>]>
>>> import datetime
>>> Battle.objects.filter(end_time<datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
>>> Battle.objects.filter(end_time < datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
```

Am I missing something?

答:
Let me add a bit of explanation..

```<code>Battle.objects.filter(end_time < datetime.datetime.now())
</code>```

here filter() is a callable that accepts arguments (args or kwargs). With the above code you are trying to pass a boolean value (object < object) to the filter callable as argument. Now, does a boolean value True or False specify anything about a model field?

What you should be doing is pass a keyword argument, namely

```<code>Battle.objects.filter(end_time__lt=datetime.datetime.now())
</code>```

Now the filter() gets the info it needs, the kwarg parameter end_time__lt (which specifies the model field along with the compare method) and the value that needs to be compared with datetime.datetime.now()

Title: Django can't find model property

Body:
In my Django project, I have a models.py that looks like this:

from django.db import models

class Battle(models.Model):

    def __str__(self):
        return self.battle_name

    battle_name = models.CharField(max_length=200)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    password = models.CharField(max_length=50)

When I drop to the Django shell (python manage.py shell), I can't interact either of the DateTimeField properties.

$ python manage.py shell
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from battles.models import Battle
>>> Battle.objects.all()
<QuerySet [<Battle: my first battle>, <Battle: Take back the motherland>, <Battle: this is the big one>]>
>>> Battle.objects.filter(battle_name='my first battle')
<QuerySet [<Battle: my first battle>]>
>>> import datetime
>>> Battle.objects.filter(end_time<datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined
>>> Battle.objects.filter(end_time < datetime.datetime.now())
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'end_time' is not defined

Am I missing something?

Body:
Let me add a bit of explanation..

Battle.objects.filter(end_time < datetime.datetime.now())

here filter() is a callable that accepts arguments (args or kwargs). With the above code you are trying to pass a boolean value (object < object) to the filter callable as argument. Now, does a boolean value True or False specify anything about a model field?

What you should be doing is pass a keyword argument, namely

Battle.objects.filter(end_time__lt=datetime.datetime.now())

Now the filter() gets the info it needs, the kwarg parameter end_time__lt (which specifies the model field along with the compare method) and the value that needs to be compared with datetime.datetime.now()


来源: stackexchange

问:
Update Azure Batch application from build pipeline
How can one update an Azure Batch application with a task in a build pipeline on AzureDevOps?</p>

答: You can use the Azure CLI task (use task version 1.0 which is based on the 2.0 az cli) in your pipeline and use the az batch application commands to update your Application Packages.</p>

ContentLicense: CC BY-SA 4.0


问:
overloaded method not seen in subclass

Possible Duplicates:

  C++ overload resolution

  Why does an overridden function in the derived class hide other overloads of the base class?

Why the following example:

```<code>class A {
    public:
        void f(int x){ }
};

class B : public A {
    public:
        void f(float a, int b){ }
};

int main(){
    B *b = new B;
    b->f(1);
};
</code>```

causes:

test.cpp: In function ‘int main()’:
test.cpp:13: error: no matching function for call to ‘B::f(int)’
test.cpp:8: note: candidates are: void B::f(float, int)

f(int) and f(float, int) have different signatures. Why is it causing an error?

EDIT

I understand it's hiding. I am asking why is this happening?

答:
Essentially, you are not overloading the base class method; by redefining method f, you are hiding the base class method. You can prevent this by including it explicitly into the child class scope the following:

```<code>class B : public A {
    public:
        using A::f;
        void f(float a, int b){ }
};
</code>```

ContentLicense: CC BY-SA 3.0

Title: overloaded method not seen in subclass

Body:
Possible Duplicates:

  C++ overload resolution

  Why does an overridden function in the derived class hide other overloads of the base class?

Why the following example:

class A {
    public:
        void f(int x){ }
};

class B : public A {
    public:
        void f(float a, int b){ }
};

int main(){
    B *b = new B;
    b->f(1);
};

causes:

test.cpp: In function ‘int main()’:
test.cpp:13: error: no matching function for call to ‘B::f(int)’
test.cpp:8: note: candidates are: void B::f(float, int)

f(int) and f(float, int) have different signatures. Why is it causing an error?

EDIT

I understand it's hiding. I am asking why is this happening?

Body:
Essentially, you are not overloading the base class method; by redefining method f, you are hiding the base class method. You can prevent this by including it explicitly into the child class scope the following:

class B : public A {
    public:
        using A::f;
        void f(float a, int b){ }
};


问:
How to copy jenkins users to another server
i want to copy my existing windows jenkins users to linux jenkins server. How to do that?

i have copied users directory to my current server after restarted the service still not working.

答:
I believe that's happening because Jenkins encrypts passwords, so a new instance would not work unless you had the same key as before in the new instance.

So on top of copying over the users directory, you'll want to copy over the secrets directory as well as the secret.key file, which can all be found in your $JENKINS_HOME directory:

$JENKINS_HOME/secret.key

$JENKINS_HOME/secrets

$JENKINS-HOME/users

Copying over all of those should address your issue


问:
Take elements until a certain character and group them with RxJava
I have a simple setup to a problem but the solution seems to be more complicated.

Setup: I have a hot observable which originates from a scanner that will emit every number as a different element and an R when a code is complete.

Problem: From this I want a hot observable that emits every full code as 1 element.

I tried playing around with different flatMap, takeUntil and groupByoperators but haven't been able to come to a solution.

答:
You can use the buffer operator.

```<code>PublishSubject<Token<Integer>> s = PublishSubject.create();

Observable<Token<Integer>> markers = s.filter(x->x.isMarker());

s.buffer(markers).subscribe(
    v->{
        Optional<Integer> reduce = v.stream()
            .filter(t->!t.isMarker())
            .map(t->(ValueToken<Integer>)t)
            .map(ValueToken::get)
            .reduce((a,b)->a+b);
        reduce.ifPresent(System.out::println);
    }
);

s.onNext(value(12));
s.onNext(value(13));
s.onNext(marker()); // will emit 25

s.onNext(value(10));
s.onNext(value(7));
s.onNext(marker()); // will emit 17

s.onNext(value(10));
s.onNext(value(7)); // Not emitting yet
</code>```

I made a class to wrap both values and markers in the flow.

```<code>public abstract class Token<T> {
    private static final MarkerToken MARKER = new MarkerToken<>();

    public boolean isMarker() {
        return false;
    }

    public static <T> MarkerToken<T> marker() {
        return MARKER;
    }

    public static <T> ValueToken<T> value(T o) {
        return new ValueToken<>(o);
    }

    public static class ValueToken<T> extends Token<T> {
        T value;

        public ValueToken(T value) {
            this.value = value;
        }

        public T get() {
            return value;
        }
    }

    public static class MarkerToken<T> extends Token<T> {
        public boolean isMarker() {
            return true;
        }
    }

}
</code>```

update (using scan)

The previous method would emit also on the closing of the stream, with this solution you can emit only complete buffers.

The message class function as an accumulator, it will accumulate tokens until closing marker is accumulated.

When this happens the next message will start from scratch.

The presence of the closing mark as last element marks the message as complete.

```<code>public static class Message<T> {
    List<Token<T>> tokens = new ArrayList<>();

    public Message<T> append(Token<T> t) {

        Message<T> mx = new Message<T>();
        if(!isComplete()) {
            mx.tokens.addAll(tokens);
        }
        mx.tokens.add(t);
        return mx;
    }

    public boolean isComplete() {
        int n = tokens.size();
        return n>0 && tokens.get(n-1).isMarker();
    }

    public Optional<List<Token<T>>> fullMessage(){
        return isComplete() ? Optional.of(tokens):Optional.empty();
    }
}
</code>```

Scanning the source you emit a message for each token emitted, then you filter out incomplete message and emit just the one marked as complete.

```<code>    s.scan(new Message<Integer>(), (a, b) -> a.append(b))
        .filter(Message::isComplete)
        .map(Message::fullMessage)
        .map(Optional::get).subscribe(v -> {
            System.out.println(v);
        });

    s.onNext(value(12));
    s.onNext(value(13));
    s.onNext(marker());// [V(12), V(13), MARKER]

    s.onNext(value(10));
    s.onNext(value(7));
    s.onNext(marker()); // [V(10), V(7), MARKER]

    s.onNext(value(10));
    s.onNext(value(127));

    s.onComplete(); // Not emitting incomplete messages on the closing of the subject.
</code>```

Body:
You can use the buffer operator.

PublishSubject<Token<Integer>> s = PublishSubject.create();

Observable<Token<Integer>> markers = s.filter(x->x.isMarker());

s.buffer(markers).subscribe(
    v->{
        Optional<Integer> reduce = v.stream()
            .filter(t->!t.isMarker())
            .map(t->(ValueToken<Integer>)t)
            .map(ValueToken::get)
            .reduce((a,b)->a+b);
        reduce.ifPresent(System.out::println);
    }
);

s.onNext(value(12));
s.onNext(value(13));
s.onNext(marker()); // will emit 25

s.onNext(value(10));
s.onNext(value(7));
s.onNext(marker()); // will emit 17

s.onNext(value(10));
s.onNext(value(7)); // Not emitting yet

I made a class to wrap both values and markers in the flow.

public abstract class Token<T> {
    private static final MarkerToken MARKER = new MarkerToken<>();

    public boolean isMarker() {
        return false;
    }

    public static <T> MarkerToken<T> marker() {
        return MARKER;
    }

    public static <T> ValueToken<T> value(T o) {
        return new ValueToken<>(o);
    }

    public static class ValueToken<T> extends Token<T> {
        T value;

        public ValueToken(T value) {
            this.value = value;
        }

        public T get() {
            return value;
        }
    }

    public static class MarkerToken<T> extends Token<T> {
        public boolean isMarker() {
            return true;
        }
    }

}

update (using scan)

The previous method would emit also on the closing of the stream, with this solution you can emit only complete buffers.

The message class function as an accumulator, it will accumulate tokens until closing marker is accumulated.

When this happens the next message will start from scratch.

The presence of the closing mark as last element marks the message as complete.

public static class Message<T> {
    List<Token<T>> tokens = new ArrayList<>();

    public Message<T> append(Token<T> t) {

        Message<T> mx = new Message<T>();
        if(!isComplete()) {
            mx.tokens.addAll(tokens);
        }
        mx.tokens.add(t);
        return mx;
    }

    public boolean isComplete() {
        int n = tokens.size();
        return n>0 && tokens.get(n-1).isMarker();
    }

    public Optional<List<Token<T>>> fullMessage(){
        return isComplete() ? Optional.of(tokens):Optional.empty();
    }
}

Scanning the source you emit a message for each token emitted, then you filter out incomplete message and emit just the one marked as complete.

    s.scan(new Message<Integer>(), (a, b) -> a.append(b))
        .filter(Message::isComplete)
        .map(Message::fullMessage)
        .map(Optional::get).subscribe(v -> {
            System.out.println(v);
        });

    s.onNext(value(12));
    s.onNext(value(13));
    s.onNext(marker());// [V(12), V(13), MARKER]

    s.onNext(value(10));
    s.onNext(value(7));
    s.onNext(marker()); // [V(10), V(7), MARKER]

    s.onNext(value(10));
    s.onNext(value(127));

    s.onComplete(); // Not emitting incomplete messages on the closing of the subject.


问:
php-cgi.exe quits after exactly 500 hits
For the life of me, I can't figure this out.

This is my development machine setup:

Windows 7 Home Premium 64 bit,

Webserver: NGINX 1.3.6 c:\users\user_name\devel\nginx

PHP: 5.4.7 c:\users\user_name\devel\nginx\php5

Everything works fine except that after exactly 500 hits, my php-cgi.exe quits unexpectedly.  No error logs, no events, nothing.  It just dies after 500 hits...EVERY SINGLE TIME.  I haven't found a single source of information online to help me on this. All the configuration seems valid and good.  This is happening on two different machines (my development desktop and my notebook).  I've tried different nginx.conf and php.ini files...still the same.

I just need to get a better idea on how to go about debugging this.  Any suggestions?

答:
If you add

```<code>SET PHP_FCGI_CHILDREN=1
</code>```

to the command file that launches the php-cgi.exe, it fixed it.

You can add more children if you want, it depends of your need.

Body:
If you add

SET PHP_FCGI_CHILDREN=1

to the command file that launches the php-cgi.exe, it fixed it.

You can add more children if you want, it depends of your need.


问:
Solving system of quadratic equations
Can anyone see a way to solve the system below? I tried Reduce but evaluation takes a while so I'm not sure it would work

```<code>terms = {{g^2, g h, h^2, -o^2, -o p, -p^2}, {g^2, g k,
    k^2, -o^2, -o q, -q^2}, {g^2, g m, m^2, -o^2, -o r, -r^2}, {g^2,
    g n, n^2, -o^2, -o s, -s^2}, {h^2, h k,
    k^2, -p^2, -p q, -q^2}, {h^2, h m, m^2, -p^2, -p r, -r^2}, {h^2,
    h n, n^2, -p^2, -p s, -s^2}, {k^2, k m,
    m^2, -q^2, -q r, -r^2}, {k^2, k n, n^2, -q^2, -q s, -s^2}, {m^2,
    m n, n^2, -r^2, -r s, -s^2}};
vars = Variables@Flatten@terms;
coefs = Array[c, Dimensions[terms]];
eqs = MapThread[#1.#2 == 0 &, {terms, coefs}];
Reduce[eqs, vars, Reals]
</code>```

答:
You can approach your problem from the optimization perspective, building the sum of squares of the r.h.s. of your equations.

Define your matrix:

```<code>mat[{g_, h_, k_, m_, n_, o_, p_, q_, r_, s_}] := {{g^2, g h,
    h^2, -o^2, -o p, -p^2}, {g^2, g k, k^2, -o^2, -o q, -q^2}, {g^2,
    g m, m^2, -o^2, -o r, -r^2}, {g^2, g n,
    n^2, -o^2, -o s, -s^2}, {h^2, h k, k^2, -p^2, -p q, -q^2}, {h^2,
    h m, m^2, -p^2, -p r, -r^2}, {h^2, h n,
    n^2, -p^2, -p s, -s^2}, {k^2, k m, m^2, -q^2, -q r, -r^2}, {k^2,
    k n, n^2, -q^2, -q s, -s^2}, {m^2, m n, n^2, -r^2, -r s, -s^2}};
</code>```

Now define the code that solve the algebraic equation as a constrained optimization:

```<code>Clear[SolveAlgebraic];
SolveAlgebraic[
  coefs_ /; Dimensions[coefs] == {10, 6} && MatrixQ[coefs, NumberQ],
  opts : OptionsPattern[NMinimize]] :=
 Module[{g, h, k, m, n, o, p, q, r, s, eqs, vars, val, sol},
  eqs = MapThread[#1.#2 &, {mat[
      vars = {g, h, k, m, n, o, p, q, r, s}], coefs}];
  {val, sol} =
   NMinimize[{Total[eqs^2],
     vars.vars > 1 && Apply[And, Thread[vars >= 0]]}, vars, opts];
  {val, vars /. sol}
  ]
</code>```

Now define a function that constructs a set of c[,] with a given solution:

```<code>CoefficientWithSolution[sol_ /; Length[sol] == 10] :=
 Block[{cc,
   v}, ((Array[
       cc, {10, 6}]) /. (First[
        Quiet@Solve[(MapThread[
              Dot, {mat[Array[v, 10]], Array[cc, {10, 6}]}] == 0 //
            Thread), Array[cc, {10, 6}] // Flatten]] /.
       Thread[Array[v, 10] -> (sol)]) /. _cc :> 1)]
</code>```

Generate a matrix:

```<code>In[188]:= coefs =
 CoefficientWithSolution[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]

Out[188]= {{1, 1, 1, 1, 1, -(71/49)}, {1, 1, 1, 1, 1, -(71/64)}, {1,
  1, 1, 1, 1, -(23/27)}, {1, 1, 1, 1, 1, -(13/20)}, {1, 1, 1, 1,
  1, -(43/32)}, {1, 1, 1, 1, 1, -(28/27)}, {1, 1, 1, 1,
  1, -(4/5)}, {1, 1, 1, 1, 1, -(11/9)}, {1, 1, 1, 1, 1, -(19/20)}, {1,
   1, 1, 1, 1, -(11/10)}}
</code>```

Solve equations with higher working precision, and coerce to machine numbers:

```<code>In[196]:= SolveAlgebraic[coefs, WorkingPrecision -> 30] // N

Out[196]= {1.41177*10^-28, {0.052633, 0.105266, 0.157899, 0.210532,
  0.263165, 0.315798, 0.368431, 0.421064, 0.473697, 0.52633}}
</code>```

Verify that the expected solution is found:

```<code>In[197]:= Rest[Last[%]]/First[Last[%]]

Out[197]= {2., 3., 4., 5., 6., 7., 8., 9., 10.}
</code>```

Hope this helps.

Title: Solving system of quadratic equations

Body:
Can anyone see a way to solve the system below? I tried Reduce but evaluation takes a while so I'm not sure it would work

terms = {{g^2, g h, h^2, -o^2, -o p, -p^2}, {g^2, g k,
    k^2, -o^2, -o q, -q^2}, {g^2, g m, m^2, -o^2, -o r, -r^2}, {g^2,
    g n, n^2, -o^2, -o s, -s^2}, {h^2, h k,
    k^2, -p^2, -p q, -q^2}, {h^2, h m, m^2, -p^2, -p r, -r^2}, {h^2,
    h n, n^2, -p^2, -p s, -s^2}, {k^2, k m,
    m^2, -q^2, -q r, -r^2}, {k^2, k n, n^2, -q^2, -q s, -s^2}, {m^2,
    m n, n^2, -r^2, -r s, -s^2}};
vars = Variables@Flatten@terms;
coefs = Array[c, Dimensions[terms]];
eqs = MapThread[#1.#2 == 0 &, {terms, coefs}];
Reduce[eqs, vars, Reals]

Body:
You can approach your problem from the optimization perspective, building the sum of squares of the r.h.s. of your equations.

Define your matrix:

mat[{g_, h_, k_, m_, n_, o_, p_, q_, r_, s_}] := {{g^2, g h,
    h^2, -o^2, -o p, -p^2}, {g^2, g k, k^2, -o^2, -o q, -q^2}, {g^2,
    g m, m^2, -o^2, -o r, -r^2}, {g^2, g n,
    n^2, -o^2, -o s, -s^2}, {h^2, h k, k^2, -p^2, -p q, -q^2}, {h^2,
    h m, m^2, -p^2, -p r, -r^2}, {h^2, h n,
    n^2, -p^2, -p s, -s^2}, {k^2, k m, m^2, -q^2, -q r, -r^2}, {k^2,
    k n, n^2, -q^2, -q s, -s^2}, {m^2, m n, n^2, -r^2, -r s, -s^2}};

Now define the code that solve the algebraic equation as a constrained optimization:

Clear[SolveAlgebraic];
SolveAlgebraic[
  coefs_ /; Dimensions[coefs] == {10, 6} && MatrixQ[coefs, NumberQ],
  opts : OptionsPattern[NMinimize]] :=
 Module[{g, h, k, m, n, o, p, q, r, s, eqs, vars, val, sol},
  eqs = MapThread[#1.#2 &, {mat[
      vars = {g, h, k, m, n, o, p, q, r, s}], coefs}];
  {val, sol} =
   NMinimize[{Total[eqs^2],
     vars.vars > 1 && Apply[And, Thread[vars >= 0]]}, vars, opts];
  {val, vars /. sol}
  ]

Now define a function that constructs a set of c[,] with a given solution:

CoefficientWithSolution[sol_ /; Length[sol] == 10] :=
 Block[{cc,
   v}, ((Array[
       cc, {10, 6}]) /. (First[
        Quiet@Solve[(MapThread[
              Dot, {mat[Array[v, 10]], Array[cc, {10, 6}]}] == 0 //
            Thread), Array[cc, {10, 6}] // Flatten]] /.
       Thread[Array[v, 10] -> (sol)]) /. _cc :> 1)]

Generate a matrix:

In[188]:= coefs =
 CoefficientWithSolution[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]

Out[188]= {{1, 1, 1, 1, 1, -(71/49)}, {1, 1, 1, 1, 1, -(71/64)}, {1,
  1, 1, 1, 1, -(23/27)}, {1, 1, 1, 1, 1, -(13/20)}, {1, 1, 1, 1,
  1, -(43/32)}, {1, 1, 1, 1, 1, -(28/27)}, {1, 1, 1, 1,
  1, -(4/5)}, {1, 1, 1, 1, 1, -(11/9)}, {1, 1, 1, 1, 1, -(19/20)}, {1,
   1, 1, 1, 1, -(11/10)}}

Solve equations with higher working precision, and coerce to machine numbers:

In[196]:= SolveAlgebraic[coefs, WorkingPrecision -> 30] // N

Out[196]= {1.41177*10^-28, {0.052633, 0.105266, 0.157899, 0.210532,
  0.263165, 0.315798, 0.368431, 0.421064, 0.473697, 0.52633}}

Verify that the expected solution is found:

In[197]:= Rest[Last[%]]/First[Last[%]]

Out[197]= {2., 3., 4., 5., 6., 7., 8., 9., 10.}

Hope this helps.


问:
When I store several dataframes in a list of dataframes and I recall one of them, is there a way to format the column header of the output?
I am new to Python and Stackoverflow, so please bear with me. I have a large datafile of roughly 140k rows stored as a csv. The file is split up into sections based on age groups, ie. 16-24, 24-50 etc. At every break there are information lines about the age and etnicity of the subjects. After loading the csv into pandas, I tried to break up the dataframe into several smaller ones by dividing on the information lines of the age groups using iloc. Now I have a list of dataframes. I can access each dataframe in the list, no problem, however (I guess due to the information lines) pandas displays all information in one column. Is there a way to format the output and make pandas display the column headers and put the information lines into the header above the column headers? I'm sorry if this is not very clear, please feel free to suggest any edits.

The data in the csv looks something like this:

```<code>0 Some information
1 Some information
2 Some information
3
4
5 a | b | c | d |
6 a | 1 | 1 | 1 |
7 a | 1 | 1 | 1 |
8 a | 1 | 1 | 1 |
9
10 Some information
11 Some information
12 Some information
13
14
15 a | b | c | d |
16 a | 1 | 1 | 1 |
17 a | 1 | 1 | 1 |
18 a | 1 | 1 | 1 |
</code>```

I used iloc to break this up on the information lines by row index.

```<code>         36065,43278,50491,57704,
         64917,72130,79343,86556,
         93769,100982,108195,115408,
         122621,129834,137047]
    l_mod = [0] + l + [max(l)+1]

    list_of_dfs = [mydata_df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]
</code>```

when accessing I used: df1_df=list_of_dfs[1]

The output is currently as follows:

```<code>                  0
--------------------
1 a,b,c
2 a,1,1,
</code>```

I hope this makes sense, please suggest edits and I'll do my best to explain.

答: You can try df[0].str.split(',', expand=True), which expands your dataframe based on every split on a comma. Then you can assign the new column names to it, since it will give column names [0, 1, 2, 3.. etc]

Body:
I am new to Python and Stackoverflow, so please bear with me. I have a large datafile of roughly 140k rows stored as a csv. The file is split up into sections based on age groups, ie. 16-24, 24-50 etc. At every break there are information lines about the age and etnicity of the subjects. After loading the csv into pandas, I tried to break up the dataframe into several smaller ones by dividing on the information lines of the age groups using iloc. Now I have a list of dataframes. I can access each dataframe in the list, no problem, however (I guess due to the information lines) pandas displays all information in one column. Is there a way to format the output and make pandas display the column headers and put the information lines into the header above the column headers? I'm sorry if this is not very clear, please feel free to suggest any edits.

The data in the csv looks something like this:

0 Some information
1 Some information
2 Some information
3
4
5 a | b | c | d |
6 a | 1 | 1 | 1 |
7 a | 1 | 1 | 1 |
8 a | 1 | 1 | 1 |
9
10 Some information
11 Some information
12 Some information
13
14
15 a | b | c | d |
16 a | 1 | 1 | 1 |
17 a | 1 | 1 | 1 |
18 a | 1 | 1 | 1 |

I used iloc to break this up on the information lines by row index.

         36065,43278,50491,57704,
         64917,72130,79343,86556,
         93769,100982,108195,115408,
         122621,129834,137047]
    l_mod = [0] + l + [max(l)+1]

    list_of_dfs = [mydata_df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]

when accessing I used: df1_df=list_of_dfs[1]

The output is currently as follows:

                  0
--------------------
1 a,b,c
2 a,1,1,

I hope this makes sense, please suggest edits and I'll do my best to explain.


问:
How to response different data that was inserted by create method (ModelViewSet)
I'm implementing a stock shoes manager with REST architecture using Django + Django rest.

Im using a custom Router inherited from DefaultRouter to serve my endpoints.

In the /resources/id endpoint Ive added one more verb, POST that is called  by custom_create method.

Here you can see this custom_create method:

viewsets.py

```<code>
class ShoeViewSet(viewsets.ModelViewSet):

    queryset = Shoe.objects.all()
    filter_class = ShoeFilter

    def get_serializer_class(self):
        if self.action == 'custom_create':
            return StockPostSerializer
        else:
            return ShoeSerializer

    def custom_create(self, request, *args, **kwargs):
        data = {}

        data['shoe'] = kwargs['pk']
        data['size'] = request.data.get('size')
        data['amount'] = request.data.get('amount')

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

</code>```

I needed to do this because I have two models, below you can see my 3 Serializers:

serializers.py

```<code>class StockSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['size', 'amount']

class ShoeSerializer(serializers.ModelSerializer):
    stock = StockSerializer(many=True, read_only=True)

    class Meta:
        model = Shoe
        fields = ['description', 'provider', 'type', 'cost_price','sale_price','total_amount', 'stock']

class StockPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['shoe','size', 'amount']
</code>```

The retrieve (GET verb) method of this endpoint expects data serialized by ShoeSerializer, but the custom_create method insert data using the StockPostSerializer. How can I return a response with a different data that was inserted ?

When I try to insert with this endpoint I recieve this error message, but when I refresh the page I realize that the content was inserted (If i use postman instead of de DRF frontend I dont get any error message, works fine).

How can my custom_create method Responses correctly ?

You can check my github, the names will be a bit different because I translated it here so that it is easier for you to understand.

PS: As you may have noticed I am not a native speaker of the English language, so it is very difficult to express myself here but I am trying my best, and learning more and more. If my question contains grammar / concordance errors please correct them but you do not have to refuse me so I'm trying to learn!

答:
I finally managed to sort this out, and in a much more elegant way than I had been trying beforehand.

What I need to do is: add new stock instances, for this I had created a new route for POST in the endpoint resources/id.

So I was able to reuse the Default Router, delete the custom_create method, and just modified the serializers.py file.
It looks like this:

serializers.py

```<code>class StockSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['size', 'amount']

class ShoeSerializer(serializers.ModelSerializer):

    stock = StockSerializer(many=True)

    def update(self, instance, validated_data):
        instance.description   = validated_data.get(
            'description', instance.description)
        instance.provider  = validated_data.get(
            'provider', instance.provider)
        instance.type        = validated_data.get('type', instance.type)
        instance.cost_price = validated_data.get(
            'cost_price', instance.cost_price)
        instance.salve_price = validated_data.get(
            'sale_price', instance.sale_price)

        stock      = instance.stock.all()
        stock_data = validated_data.get('stock', [])

        for item_data in stock_data:
            item_id = item_data.get('size', None)
            if item_id is not None:
                item_db            = stock.get(size=item_id)
                item_db.size    = item_data.get('size', item_db.size)
                item_db.amount = item_data.get('amount',item_db.amount)
                item_db.save()
            else:
                Estoque.objects.create(
                    shoe = instance,
                    size    = item_data['size'],
                    amount = item_data['amount']
                )
        instance.save()
        return instance

    class Meta:
        model = Shoe
        fields = ['_id','description', 'provider', 'type', 'cost_price','sale_price','total_amount', 'stock']

</code>```

Now, via PATCH verb I can add new Stock instances and alter existing stock instances. Thank you for the support!

Body:
I'm implementing a stock shoes manager with REST architecture using Django + Django rest.

Im using a custom Router inherited from DefaultRouter to serve my endpoints.

In the /resources/id endpoint Ive added one more verb, POST that is called  by custom_create method.

Here you can see this custom_create method:

viewsets.py

class ShoeViewSet(viewsets.ModelViewSet):

    queryset = Shoe.objects.all()
    filter_class = ShoeFilter

    def get_serializer_class(self):
        if self.action == 'custom_create':
            return StockPostSerializer
        else:
            return ShoeSerializer

    def custom_create(self, request, *args, **kwargs):
        data = {}

        data['shoe'] = kwargs['pk']
        data['size'] = request.data.get('size')
        data['amount'] = request.data.get('amount')

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

I needed to do this because I have two models, below you can see my 3 Serializers:

serializers.py

class StockSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['size', 'amount']

class ShoeSerializer(serializers.ModelSerializer):
    stock = StockSerializer(many=True, read_only=True)

    class Meta:
        model = Shoe
        fields = ['description', 'provider', 'type', 'cost_price','sale_price','total_amount', 'stock']

class StockPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['shoe','size', 'amount']

The retrieve (GET verb) method of this endpoint expects data serialized by ShoeSerializer, but the custom_create method insert data using the StockPostSerializer. How can I return a response with a different data that was inserted ?

When I try to insert with this endpoint I recieve this error message, but when I refresh the page I realize that the content was inserted (If i use postman instead of de DRF frontend I dont get any error message, works fine).

How can my custom_create method Responses correctly ?

You can check my github, the names will be a bit different because I translated it here so that it is easier for you to understand.

PS: As you may have noticed I am not a native speaker of the English language, so it is very difficult to express myself here but I am trying my best, and learning more and more. If my question contains grammar / concordance errors please correct them but you do not have to refuse me so I'm trying to learn!

Body:
I finally managed to sort this out, and in a much more elegant way than I had been trying beforehand.

What I need to do is: add new stock instances, for this I had created a new route for POST in the endpoint resources/id.

So I was able to reuse the Default Router, delete the custom_create method, and just modified the serializers.py file.
It looks like this:

serializers.py

class StockSerializer(serializers.ModelSerializer):

    class Meta:
        model = Stock
        fields = ['size', 'amount']

class ShoeSerializer(serializers.ModelSerializer):

    stock = StockSerializer(many=True)

    def update(self, instance, validated_data):
        instance.description   = validated_data.get(
            'description', instance.description)
        instance.provider  = validated_data.get(
            'provider', instance.provider)
        instance.type        = validated_data.get('type', instance.type)
        instance.cost_price = validated_data.get(
            'cost_price', instance.cost_price)
        instance.salve_price = validated_data.get(
            'sale_price', instance.sale_price)

        stock      = instance.stock.all()
        stock_data = validated_data.get('stock', [])

        for item_data in stock_data:
            item_id = item_data.get('size', None)
            if item_id is not None:
                item_db            = stock.get(size=item_id)
                item_db.size    = item_data.get('size', item_db.size)
                item_db.amount = item_data.get('amount',item_db.amount)
                item_db.save()
            else:
                Estoque.objects.create(
                    shoe = instance,
                    size    = item_data['size'],
                    amount = item_data['amount']
                )
        instance.save()
        return instance

    class Meta:
        model = Shoe
        fields = ['_id','description', 'provider', 'type', 'cost_price','sale_price','total_amount', 'stock']

Now, via PATCH verb I can add new Stock instances and alter existing stock instances. Thank you for the support!


问:
Why datalist does not work when I make it dynamic (Angular 7)?
I created a function in my .ts file that allows to update a array (empty by default) that I use to create the options of my datalist.

When I inspect the HTML code I see the options in the datalist but they do not show in the GUI

<input list='id-RPG' type="text" pInputText class="inputTextStyle" [(ngModel)]="MyModal" (input)="searchList($event.target.value)"/>
<datalist id='id-RPG'>
 <option *ngFor="let element of array" [(value)]="element ">{{element }}</option>
</datalist>
```

```ngOnInit(){
this.array = [];
}

searchList(){
//Rest Here
this.array = ["aaa","aab","aac","aad"]
}
```

No error message is displayed

答:
You've writen [(value)] what don't work. You should write (value)

```<code><option *ngFor="let element of array" (value)="element ">
</code>```

And you don't need to initialize array in ngOnInit

```<code>ngOnInit(){
  this.array = [];
}
</code>```

Just write it as a global variable

```<code>array: Array<string> = [];
ngOnInit(){}
</code>```

Body:
I created a function in my .ts file that allows to update a array (empty by default) that I use to create the options of my datalist.

When I inspect the HTML code I see the options in the datalist but they do not show in the GUI

<input list='id-RPG' type="text" pInputText class="inputTextStyle" [(ngModel)]="MyModal" (input)="searchList($event.target.value)"/>
<datalist id='id-RPG'>
 <option *ngFor="let element of array" [(value)]="element ">{{element }}</option>
</datalist>

ngOnInit(){
this.array = [];
}

searchList(){
//Rest Here
this.array = ["aaa","aab","aac","aad"]
}

No error message is displayed

Body:
You've writen [(value)] what don't work. You should write (value)

<option *ngFor="let element of array" (value)="element ">

And you don't need to initialize array in ngOnInit

ngOnInit(){
  this.array = [];
}

Just write it as a global variable

array: Array<string> = [];
ngOnInit(){}


问:
How do you write a non-dymanic SQLQuery to only return records that fulfill multiple EXISTS clauses?
Here's the problem I'm running into. I have a query (that works) and what I want it to do is return only records where a user has records for each EXISTS clause. Like this:

```<code>select * from Users
WHERE EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 1)
        AND EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 2)
        AND EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 3)
</code>```

So in the case specifically, I only want users that have a session Id of 1 AND and session id of 2 AND and session id of 3. This query works but the session id's change and could be 1 or 20 different id's.

Right now I'm dynamically assembling the query as needed (in my server-side app) based on what session id's I need but I'm wondering if there's a way to write this query so I can just pass in the id's and not manually assemble it. Kinda like an IN clause but one that'll only return the records where a user appears in all numbers in the IN clause.

Every solution I run into seems to be a different version of this current query where I'm having to dynamically assemble the query depending on the session ids needed. Is there any way to make this not so dynamic?

答:
It seems like a reasonable assumption that the keys are unique in a junction/association table such as UserSessions.

You can simplify the logic to:

```<code>select u.*
from Users u join
     (select us.UserId
      from UserSessions us
      where SessionId in (1, 2, 3)   -- your list here
      group by us.UserId
      having count(*) = 3            -- size of the list
     ) us
     on us.UserId = u.Id;
</code>```

You can further parameterize this, depending on how you want to pass in your list.  One method would be parsing a string:

```<code>with input_sessions as (
      select value as SessionId
      from string_split(@sessions_list, ',')
     )
    select u.*
    from Users u join
         (select us.UserId
          from UserSessions us
          where SessionId in (select sessionId from input_sessions)
          group by us.UserId
          having count(*) = (select count*) from input_sessions)
         ) us
         on us.UserId = u.Id;
</code>```

If the keys are not unique, the queries can be tweaked to take this into account.

Body:
Here's the problem I'm running into. I have a query (that works) and what I want it to do is return only records where a user has records for each EXISTS clause. Like this:

select * from Users
WHERE EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 1)
        AND EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 2)
        AND EXISTS (SELECT *
                FROM UserSessions
                WHERE UserSessions.UserId = Users.Id
                AND SessionId = 3)

So in the case specifically, I only want users that have a session Id of 1 AND and session id of 2 AND and session id of 3. This query works but the session id's change and could be 1 or 20 different id's.

Right now I'm dynamically assembling the query as needed (in my server-side app) based on what session id's I need but I'm wondering if there's a way to write this query so I can just pass in the id's and not manually assemble it. Kinda like an IN clause but one that'll only return the records where a user appears in all numbers in the IN clause.

Every solution I run into seems to be a different version of this current query where I'm having to dynamically assemble the query depending on the session ids needed. Is there any way to make this not so dynamic?

Body:
It seems like a reasonable assumption that the keys are unique in a junction/association table such as UserSessions.

You can simplify the logic to:

select u.*
from Users u join
     (select us.UserId
      from UserSessions us
      where SessionId in (1, 2, 3)   -- your list here
      group by us.UserId
      having count(*) = 3            -- size of the list
     ) us
     on us.UserId = u.Id;

You can further parameterize this, depending on how you want to pass in your list.  One method would be parsing a string:

with input_sessions as (
      select value as SessionId
      from string_split(@sessions_list, ',')
     )
    select u.*
    from Users u join
         (select us.UserId
          from UserSessions us
          where SessionId in (select sessionId from input_sessions)
          group by us.UserId
          having count(*) = (select count*) from input_sessions)
         ) us
         on us.UserId = u.Id;

If the keys are not unique, the queries can be tweaked to take this into account.


问:
Having some delays using python and tkinter for a real time GUI
So I have a program in matlab that is sending numbers from 1 to 7 in random order, my python code has to light the respective word when receives the number (each word as a specific number related to it). This has to be as fast as it can, since this is a brain computer interface and the timings are extremly important.

What is happening is: when I'm simply printing the values I'm receiving from matlab no delays occur, I receive like this:

```<code>b'1\n'
b'7\n'
b'4\n'
b'2\n'
b'6\n'
b'3\n'
b'1\n'
b'5\n'
etc..
</code>```

But when I include the GUI (i used Tkinter) part and print the values, it gives me:

```<code>b'1\n'
1
b'7\n'
7
b'4\n'
4
b'2\n'
2
b'6\n'
6
b'3\n'
3
b'1\n5\n1\n'
1
5
1
b'4\n3\n7\n'
4
3
7
b'6\n2\n5\n7\n2\n'
6
2
5
etc...
</code>```

So when it starts receiving multiple numbers at a time it slows a lot the program.
It seems to me that either the tkinter is to slow or the loop is not right, but it is strange since it is only a few lines of code:

```<code>from tkinter import *
import time
import winsound
import socket
import sys

sounds = ["sim_esquerda_elev0_azim100.wav","nao_direita_elev0_azim100.wav",\
          "fome_esquerda_elev30_azim120.wav", "sede_direita_elev-40_azim148.wav",\
          "urinar_esquerda_elev-40_azim32.wav","ar_frente_elev0_azim0.wav",\
          "posicao_direita_elev30_azim60.wav"]

# TCP connection
try:
    so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print ("socket creation failed with error %s" %(err))

#default port for socket
port = 2000

# default time out
#so.settimeout(1000000)

try:
    host_ip = socket.gethostbyname('localhost')
except socket.gaierror:
    # this means could not resolve the host
    print ("there was an error resolving the host")
    sys.exit()

# connecting to the server
so.connect((host_ip,port))

# MATLAB INFORMATION FOR OFFLINE EXPERIMENT
Nepoch = 10  #nr de epochs por trial
Nwords = 7   #nr de palavras (SIM, NAO, FOME, SEDE, URINAR, AR, POSICAO)
SeqTrain = [1, 3, 5, 7, 2, 4, 6, 1, 3, 5, 7, 2, 4, 6] #sequencia offline de treino

# read the TCP sequence received
def sequencia():
    num = 0
    for i in range(0,999):
        s = so.recv(port) #+ b'\n' #since the sequence received is : 1\n 2\n 5\n etc
        print(s)
        for c in s.split():
            y = int(c)
            #print(c)
            #feedbak offline (for the user to know which are the words)
            if (num in (0, Nepoch*Nwords+1, Nepoch*Nwords*2+2, Nepoch*Nwords*3+3, Nepoch*Nwords*4+4, Nepoch*Nwords*5+5,\
                    Nepoch*Nwords*6+6)):
                labels1[y-1].configure(foreground="white")
                root.update()
            elif (num in (Nepoch*Nwords*7+7, Nepoch*Nwords*8+8, Nepoch*Nwords*9+9, Nepoch*Nwords*10+10,\
                     Nepoch*Nwords*11+11, Nepoch*Nwords*12+12, Nepoch*Nwords*13+13)):
                labels2[y-1].configure(foreground="white")
                root.update()
            else:
                labels[y-1].configure(background="green",foreground="red")
                root.update()
                winsound.PlaySound(sounds[y-1], winsound.SND_FILENAME)
                labels[y-1].configure(background="gray",foreground="white")
                root.update()
            num = num + 1
#window
root = Tk()
root.title("Sequencia")
#root.attributes('-fullscreen', True)  #for fullscreen
#root.bind('<Escape>',lambda e: root.destroy()) #to get out of the full screen
root.state('zoomed')  #just zoomed not fullscreen
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
fm = Frame(root, width=w, height=h, bg="black")

#draw center lines
#wi = Canvas(fm, width=20, height=20, bg ="green", selectborderwidth=0)
#wi.create_line(0, 200, 150, 150, width=10, fill="blue")

#~~~~~~~~~~~~~LABELS FOR THE OFFLINE TEST TO SHOW UP IN THE SCREEN~~~~~~~~~~~~~
label_sim1 = Label(fm, width=10, height=1, bg="black", text = "SIM",  font = ('TkDefaultFont',15), fg="black")
label_nao1 = Label(fm, width=10, height=1, bg="black", text = "NÃO", font = ('TkDefaultFont',15), fg="black")
label_fome1 = Label(fm, width=10, height=1, bg="black", text = "FOME", font = ('TkDefaultFont',15), fg="black")
label_sede1 = Label(fm, width=10, height=1, bg="black", text = "SEDE", font = ('TkDefaultFont',15), fg="black")
label_urinar1 = Label(fm, width=10, height=1, bg="black", text = "URINAR", font = ('TkDefaultFont',15), fg="black")
label_ar1 = Label(fm, width=10, height=1, bg="black", text = "AR", font = ('TkDefaultFont',15), fg="black")
label_posicao1 = Label(fm, width=10, height=1, bg="black", text = "POSIÇÃO", font = ('TkDefaultFont',15), fg="black")

labels1 = [label_sim1,label_nao1,label_fome1,label_sede1,label_urinar1,label_ar1,label_posicao1]

label_sim2 = Label(fm, width=10, height=1, bg="black", text = "SIM",  font = ('TkDefaultFont',15), fg="black")
label_nao2 = Label(fm, width=10, height=1, bg="black", text = "NÃO", font = ('TkDefaultFont',15), fg="black")
label_fome2 = Label(fm, width=10, height=1, bg="black", text = "FOME", font = ('TkDefaultFont',15), fg="black")
label_sede2 = Label(fm, width=10, height=1, bg="black", text = "SEDE", font = ('TkDefaultFont',15), fg="black")
label_urinar2 = Label(fm, width=10, height=1, bg="black", text = "URINAR", font = ('TkDefaultFont',15), fg="black")
label_ar2 = Label(fm, width=10, height=1, bg="black", text = "AR", font = ('TkDefaultFont',15), fg="black")
label_posicao2 = Label(fm, width=10, height=1, bg="black", text = "POSIÇÃO", font = ('TkDefaultFont',15), fg="black")

labels2 = [label_sim2,label_nao2,label_fome2,label_sede2,label_urinar2,label_ar2,label_posicao2]

#posicionamento das palavras: [1, 3, 5, 7, 2, 4, 6, 1, 3, 5, 7, 2, 4, 6] sim, fome, urinar, posição, nao, sede, ar, sim, fome, urinar, posição, nao, sede, ar
fm.pack()
label_sim1.place(relx=0.09, rely=0.07, anchor=CENTER)
label_fome1.place(relx=0.14, rely=0.07, anchor=CENTER)
label_urinar1.place(relx=0.2, rely=0.07, anchor=CENTER)
label_posicao1.place(relx=0.27, rely=0.07, anchor=CENTER)
label_nao1.place(relx=0.32, rely=0.07, anchor=CENTER)
label_sede1.place(relx=0.37, rely=0.07, anchor=CENTER)
label_ar1.place(relx=0.42, rely=0.07, anchor=CENTER)

label_sim2.place(relx=0.46, rely=0.07, anchor=CENTER)
label_fome2.place(relx=0.515, rely=0.07, anchor=CENTER)
label_urinar2.place(relx=0.575, rely=0.07, anchor=CENTER)
label_posicao2.place(relx=0.645, rely=0.07, anchor=CENTER)
label_nao2.place(relx=0.695, rely=0.07, anchor=CENTER)
label_sede2.place(relx=0.745, rely=0.07, anchor=CENTER)
label_ar2.place(relx=0.80, rely=0.07, anchor=CENTER)

#~~~~~~~~~~LABELS OF THE PARADIGM~~~~~~~~~~
label_sim = Label(fm, width=10, height=1, bg="gray", text = "SIM",  font = ('TkDefaultFont',28), fg="white")
label_nao = Label(fm, width=10, height=1, bg="gray", text = "NÃO", font = ('TkDefaultFont',28), fg="white")
label_fome = Label(fm, width=10, height=1, bg="gray", text = "FOME", font = ('TkDefaultFont',28), fg="white")
label_sede = Label(fm, width=10, height=1, bg="gray", text = "SEDE", font = ('TkDefaultFont',28), fg="white")
label_urinar = Label(fm, width=10, height=1, bg="gray", text = "URINAR", font = ('TkDefaultFont',28), fg="white")
label_ar = Label(fm, width=10, height=1, bg="gray", text = "AR", font = ('TkDefaultFont',28), fg="white")
label_posicao = Label(fm, width=10, height=1, bg="gray", text = "POSIÇÃO", font = ('TkDefaultFont',28), fg="white")

labels = [label_sim,label_nao,label_fome,label_sede,label_urinar,label_ar,label_posicao]

#ordem de sequencia (1 2 3 4 5 6 7): (SIM, NAO, FOME, SEDE, URINAR, AR, POSICAO)
#posicionamento das palavras:
fm.pack()
label_ar.place(relx=0.5, rely=0.15, anchor=CENTER)
label_posicao.place(relx=0.70, rely=0.3, anchor=CENTER)
label_urinar.place(relx=0.3, rely=0.3, anchor=CENTER)
label_nao.place(relx=0.72, rely=0.55, anchor=CENTER)
label_sim.place(relx=0.28, rely=0.55, anchor=CENTER)
label_sede.place(relx=0.60, rely=0.77, anchor=CENTER)
label_fome.place(relx=0.4, rely=0.77, anchor=CENTER)

root.update()
sequencia()

</code>```

Do you have any ideas on why this is happening? or advices to improve? I already tried separating the code with threads and it didn't work. Is it Tkinter a bad option? Or even python?
 Many thanks

答:
The calls to update is probably the main thing slowing down the loop. Each time you call it, it will attempt to service all pending events. You should consider calling it only once every few hundred milliseconds.

Also, playing a sound is going to be very slow, since you have to wait for the sound to play before the loop can continue.

Body:
So I have a program in matlab that is sending numbers from 1 to 7 in random order, my python code has to light the respective word when receives the number (each word as a specific number related to it). This has to be as fast as it can, since this is a brain computer interface and the timings are extremly important.

What is happening is: when I'm simply printing the values I'm receiving from matlab no delays occur, I receive like this:

b'1\n'
b'7\n'
b'4\n'
b'2\n'
b'6\n'
b'3\n'
b'1\n'
b'5\n'
etc..

But when I include the GUI (i used Tkinter) part and print the values, it gives me:

b'1\n'
1
b'7\n'
7
b'4\n'
4
b'2\n'
2
b'6\n'
6
b'3\n'
3
b'1\n5\n1\n'
1
5
1
b'4\n3\n7\n'
4
3
7
b'6\n2\n5\n7\n2\n'
6
2
5
etc...

So when it starts receiving multiple numbers at a time it slows a lot the program.
It seems to me that either the tkinter is to slow or the loop is not right, but it is strange since it is only a few lines of code:

from tkinter import *
import time
import winsound
import socket
import sys

sounds = ["sim_esquerda_elev0_azim100.wav","nao_direita_elev0_azim100.wav",\
          "fome_esquerda_elev30_azim120.wav", "sede_direita_elev-40_azim148.wav",\
          "urinar_esquerda_elev-40_azim32.wav","ar_frente_elev0_azim0.wav",\
          "posicao_direita_elev30_azim60.wav"]

# TCP connection
try:
    so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print ("socket creation failed with error %s" %(err))

#default port for socket
port = 2000

# default time out
#so.settimeout(1000000)

try:
    host_ip = socket.gethostbyname('localhost')
except socket.gaierror:
    # this means could not resolve the host
    print ("there was an error resolving the host")
    sys.exit()

# connecting to the server
so.connect((host_ip,port))

# MATLAB INFORMATION FOR OFFLINE EXPERIMENT
Nepoch = 10  #nr de epochs por trial
Nwords = 7   #nr de palavras (SIM, NAO, FOME, SEDE, URINAR, AR, POSICAO)
SeqTrain = [1, 3, 5, 7, 2, 4, 6, 1, 3, 5, 7, 2, 4, 6] #sequencia offline de treino

# read the TCP sequence received
def sequencia():
    num = 0
    for i in range(0,999):
        s = so.recv(port) #+ b'\n' #since the sequence received is : 1\n 2\n 5\n etc
        print(s)
        for c in s.split():
            y = int(c)
            #print(c)
            #feedbak offline (for the user to know which are the words)
            if (num in (0, Nepoch*Nwords+1, Nepoch*Nwords*2+2, Nepoch*Nwords*3+3, Nepoch*Nwords*4+4, Nepoch*Nwords*5+5,\
                    Nepoch*Nwords*6+6)):
                labels1[y-1].configure(foreground="white")
                root.update()
            elif (num in (Nepoch*Nwords*7+7, Nepoch*Nwords*8+8, Nepoch*Nwords*9+9, Nepoch*Nwords*10+10,\
                     Nepoch*Nwords*11+11, Nepoch*Nwords*12+12, Nepoch*Nwords*13+13)):
                labels2[y-1].configure(foreground="white")
                root.update()
            else:
                labels[y-1].configure(background="green",foreground="red")
                root.update()
                winsound.PlaySound(sounds[y-1], winsound.SND_FILENAME)
                labels[y-1].configure(background="gray",foreground="white")
                root.update()
            num = num + 1
#window
root = Tk()
root.title("Sequencia")
#root.attributes('-fullscreen', True)  #for fullscreen
#root.bind('<Escape>',lambda e: root.destroy()) #to get out of the full screen
root.state('zoomed')  #just zoomed not fullscreen
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
fm = Frame(root, width=w, height=h, bg="black")

#draw center lines
#wi = Canvas(fm, width=20, height=20, bg ="green", selectborderwidth=0)
#wi.create_line(0, 200, 150, 150, width=10, fill="blue")

#~~~~~~~~~~~~~LABELS FOR THE OFFLINE TEST TO SHOW UP IN THE SCREEN~~~~~~~~~~~~~
label_sim1 = Label(fm, width=10, height=1, bg="black", text = "SIM",  font = ('TkDefaultFont',15), fg="black")
label_nao1 = Label(fm, width=10, height=1, bg="black", text = "NÃO", font = ('TkDefaultFont',15), fg="black")
label_fome1 = Label(fm, width=10, height=1, bg="black", text = "FOME", font = ('TkDefaultFont',15), fg="black")
label_sede1 = Label(fm, width=10, height=1, bg="black", text = "SEDE", font = ('TkDefaultFont',15), fg="black")
label_urinar1 = Label(fm, width=10, height=1, bg="black", text = "URINAR", font = ('TkDefaultFont',15), fg="black")
label_ar1 = Label(fm, width=10, height=1, bg="black", text = "AR", font = ('TkDefaultFont',15), fg="black")
label_posicao1 = Label(fm, width=10, height=1, bg="black", text = "POSIÇÃO", font = ('TkDefaultFont',15), fg="black")

labels1 = [label_sim1,label_nao1,label_fome1,label_sede1,label_urinar1,label_ar1,label_posicao1]

label_sim2 = Label(fm, width=10, height=1, bg="black", text = "SIM",  font = ('TkDefaultFont',15), fg="black")
label_nao2 = Label(fm, width=10, height=1, bg="black", text = "NÃO", font = ('TkDefaultFont',15), fg="black")
label_fome2 = Label(fm, width=10, height=1, bg="black", text = "FOME", font = ('TkDefaultFont',15), fg="black")
label_sede2 = Label(fm, width=10, height=1, bg="black", text = "SEDE", font = ('TkDefaultFont',15), fg="black")
label_urinar2 = Label(fm, width=10, height=1, bg="black", text = "URINAR", font = ('TkDefaultFont',15), fg="black")
label_ar2 = Label(fm, width=10, height=1, bg="black", text = "AR", font = ('TkDefaultFont',15), fg="black")
label_posicao2 = Label(fm, width=10, height=1, bg="black", text = "POSIÇÃO", font = ('TkDefaultFont',15), fg="black")

labels2 = [label_sim2,label_nao2,label_fome2,label_sede2,label_urinar2,label_ar2,label_posicao2]

#posicionamento das palavras: [1, 3, 5, 7, 2, 4, 6, 1, 3, 5, 7, 2, 4, 6] sim, fome, urinar, posição, nao, sede, ar, sim, fome, urinar, posição, nao, sede, ar
fm.pack()
label_sim1.place(relx=0.09, rely=0.07, anchor=CENTER)
label_fome1.place(relx=0.14, rely=0.07, anchor=CENTER)
label_urinar1.place(relx=0.2, rely=0.07, anchor=CENTER)
label_posicao1.place(relx=0.27, rely=0.07, anchor=CENTER)
label_nao1.place(relx=0.32, rely=0.07, anchor=CENTER)
label_sede1.place(relx=0.37, rely=0.07, anchor=CENTER)
label_ar1.place(relx=0.42, rely=0.07, anchor=CENTER)

label_sim2.place(relx=0.46, rely=0.07, anchor=CENTER)
label_fome2.place(relx=0.515, rely=0.07, anchor=CENTER)
label_urinar2.place(relx=0.575, rely=0.07, anchor=CENTER)
label_posicao2.place(relx=0.645, rely=0.07, anchor=CENTER)
label_nao2.place(relx=0.695, rely=0.07, anchor=CENTER)
label_sede2.place(relx=0.745, rely=0.07, anchor=CENTER)
label_ar2.place(relx=0.80, rely=0.07, anchor=CENTER)

#~~~~~~~~~~LABELS OF THE PARADIGM~~~~~~~~~~
label_sim = Label(fm, width=10, height=1, bg="gray", text = "SIM",  font = ('TkDefaultFont',28), fg="white")
label_nao = Label(fm, width=10, height=1, bg="gray", text = "NÃO", font = ('TkDefaultFont',28), fg="white")
label_fome = Label(fm, width=10, height=1, bg="gray", text = "FOME", font = ('TkDefaultFont',28), fg="white")
label_sede = Label(fm, width=10, height=1, bg="gray", text = "SEDE", font = ('TkDefaultFont',28), fg="white")
label_urinar = Label(fm, width=10, height=1, bg="gray", text = "URINAR", font = ('TkDefaultFont',28), fg="white")
label_ar = Label(fm, width=10, height=1, bg="gray", text = "AR", font = ('TkDefaultFont',28), fg="white")
label_posicao = Label(fm, width=10, height=1, bg="gray", text = "POSIÇÃO", font = ('TkDefaultFont',28), fg="white")

labels = [label_sim,label_nao,label_fome,label_sede,label_urinar,label_ar,label_posicao]

#ordem de sequencia (1 2 3 4 5 6 7): (SIM, NAO, FOME, SEDE, URINAR, AR, POSICAO)
#posicionamento das palavras:
fm.pack()
label_ar.place(relx=0.5, rely=0.15, anchor=CENTER)
label_posicao.place(relx=0.70, rely=0.3, anchor=CENTER)
label_urinar.place(relx=0.3, rely=0.3, anchor=CENTER)
label_nao.place(relx=0.72, rely=0.55, anchor=CENTER)
label_sim.place(relx=0.28, rely=0.55, anchor=CENTER)
label_sede.place(relx=0.60, rely=0.77, anchor=CENTER)
label_fome.place(relx=0.4, rely=0.77, anchor=CENTER)

root.update()
sequencia()

Do you have any ideas on why this is happening? or advices to improve? I already tried separating the code with threads and it didn't work. Is it Tkinter a bad option? Or even python?
 Many thanks


问:
Using OAuth2 how do I pull the access token into a variable?
I am trying to make a call to an authorization endpoint using OAuth2 with grant type Client Credentials - my call is successful - that is not an issue.  However, I, now, want to take the access token that is returned and put it in a variable so I may use it in subsequent calls without having to manually cut-and-paste to my other calls.

When the call returns I see the token I desire to copy in the Access Token field at the bottom of the OAuth2 window (the one shown below that says expires in 42 minutes) AND I see it in the Authorization field on the Timeline tab of the results.  I just can't figure out how to get access to it so I may dump it into  variable.

答:
If you want to save a token that is returned in a response into an environment variable, you can use request chaining in your environment variable. Take a look at this url for more details on that https://support.insomnia.rest/article/43-chaining-requests...

Here is what you could do (what I did)

Create an environment variable

For the value of the variable, use the Response => Body Attribute and under Filter (JSONPath or XPath), choose the attribute of the token in your response body (if it is "token" then put $.token).

After that just put the token environment variable wherever you need it in the following requests.


问:
How to set local model repository - Tensorrt inference server with Minio
Hi I want to setup Kubeflow - NVIDIA TensorRT inference server with repository located in MinIO.

I don't how to change gs://inference-server-model-store/tf_model_store to connect Minio.

```<code>ks init my-inference-server
cd my-inference-server
ks registry add kubeflow https://github.com/kubeflow/kubeflow/tree/master/kubeflow
ks pkg install kubeflow/nvidia-inference-server
ks generate nvidia-inference-server iscomp --name=inference-server --image=nvcr.io/nvidia/tensorrtserver:19.04-py3 --modelRepositoryPath=gs://inference-server-model-store/tf_model_store
</code>```

答:
Looks like NVIDIA TensorRT inference documentation on Kubeflow is not updated yet.

Ksonnet is being deprecated after Heptio acquisition. Hence Kubeflow is
moving to Kustomize.

If you consider using Kustomize, you can configure S3 API with Kubeflow as described here. You should be able to use s3://bucket/object for models.

Body:
Hi I want to setup Kubeflow - NVIDIA TensorRT inference server with repository located in MinIO.

I don't how to change gs://inference-server-model-store/tf_model_store to connect Minio.

ks init my-inference-server
cd my-inference-server
ks registry add kubeflow https://github.com/kubeflow/kubeflow/tree/master/kubeflow
ks pkg install kubeflow/nvidia-inference-server
ks generate nvidia-inference-server iscomp --name=inference-server --image=nvcr.io/nvidia/tensorrtserver:19.04-py3 --modelRepositoryPath=gs://inference-server-model-store/tf_model_store


问:
How to access a variable across all connected tcp clients in go?
I'm setting up a tcp server in a pet project I'm writing in go. I want to be able to maintain a slice of all connected clients, and then modify it whenever a new client connects or disconnects from my server.

My main mental obstacle right now is whether I should be declaring a package level slice, or just passing a slice into my handler.

My first thought was to declare my ClientList slice (I'm aware that a slice might not be my best option here, but I've decided to leave it as is for now) as a package level variable. While I think this would work, I've seen a number of posts discouraging the use of them.

My other thought was to declare ClientList as a slice in my main function, and then I pass ClientList to my HandleClient function, so whenever a client connects/disconnects I can call AddClient or RemoveClient and pass this slice in and add/remove the appropriate client.

This implementation is seen below. There are definitely other issues with the code, but I'm stuck trying to wrap my head around something that seems like it should be very simple.

```<code>type Client struct {
    Name string
    Conn net.Conn
}

type ClientList []*Client

// Identify is used to set the name of the client
func (cl *Client) Identify() error {
// code here to set the client's name in the based on input from client
}

// This is not a threadsafe way to do this - need to use mutex/channels
func (cList *ClientList) AddClient(cl *Client) {
    *cList = append(*cList, cl)
}
</code>```

```<code>func (cl *Client) HandleClient(cList *ClientList) {
    defer cl.Conn.Close()
    cList.AddClient(cl)
    err := cl.Identify()
    if err != nil {
        log.Println(err)
        return
    }
    for {
        err := cl.Conn.SetDeadline(time.Now().Add(20 * time.Second))
        if err != nil {
            log.Println(err)
            return
        }
        cl.Conn.Write([]byte("What command would you like to perform?\n"))
        netData, err := bufio.NewReader(cl.Conn).ReadString('\n')
        if err != nil {
            log.Println(err)
            return
        }
        cmd := strings.TrimSpace(string(netData))
        if cmd == "Ping" {
            cl.Ping() //sends a pong msg back to client
        } else {
            cl.Conn.Write([]byte("Unsupported command at this time\n"))
        }

    }
}
</code>```

```<code>func main() {
    arguments := os.Args

    PORT := ":" + arguments[1]
    l, err := net.Listen("tcp4", PORT)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer l.Close()
    fmt.Println("Listening...")

    // Create a new slice to store pointers to clients
    var cList ClientList

    for {
        c, err := l.Accept()
        if err != nil {
            log.Println(err)
            return
        }
        // Create client cl1
        cl1 := Client{Conn: c}

        // Go and handle the client
        go cl1.HandleClient(&cList)
    }
}
</code>```

From my initial testing, this appears to work. I am able to print out my client list and I can see that new clients are being added, and their name is being added after Identify() is called as well.

When I run it with the -race flag, I do get data race warnings, so I know I will need a threadsafe way to handle adding clients. The same goes for removing clients when I add that in.

Are there any other issues I might be missing by passing my ClientList  into HandleClient, or any benefits I would gain from declaring ClientList as a package level variable instead?

答:
Several problems with this approach.

First, your code contains a data race: each TCP connection is served by a separate goroutine, and they all attempt to modify the slice concurrently.

You might try building your code with go build -race (or go install -race — whatever you're using), and see it crash by the enabled runtime checks.

This one is easy to fix. The most straightforward approach is to add a mutex variable into the ClientList type:

type ClientList struct {
  mu      sync.Mutex
  clients []*Client
}
```

<p>…and make the type's methods hold the mutex while they're mutating the <code>clients</code> field, like this:</p>

<pre class="lang-golang prettyprint-override"><code>func (cList *ClientList) AddClient(cl *Client) {
  cList.mu.Lock()
  defer cList.mu.Unlock()

  cList.clients = append(cList.clients, o)
}
</code>```

(If you will ever encounter the typical usage pattern of your ClientList type is to frequently call methods which only read the contained list, you may start using the sync.RWLock type instead, which allows multiple concurrent readers.)

Second, I'd split the part which "identifies" a client out of the handler function.
As of now, in the handler, if the identification fails, the handler exits but the client is not delisted.

I'd say it would be better to identify it up front and only run the handler once the client is beleived to be okay.

Also it supposedly worth adding a deferred call to something like RemoveClient at the top of the handler's body so that the client is properly delisted when the handler is done with it.

IOW, I'd expect to see something like this:

func (cl *Client) HandleClient(cList *ClientList) {
    defer cl.Conn.Close()

    err := cl.Identify()
    if err != nil {
        log.Println(err)
        return
    }

    cList.AddClient(cl)
    defer cList.RemoveClient(cl)

    // ... the rest of the code
}
```

Body:
I'm setting up a tcp server in a pet project I'm writing in go. I want to be able to maintain a slice of all connected clients, and then modify it whenever a new client connects or disconnects from my server.

My main mental obstacle right now is whether I should be declaring a package level slice, or just passing a slice into my handler.

My first thought was to declare my ClientList slice (I'm aware that a slice might not be my best option here, but I've decided to leave it as is for now) as a package level variable. While I think this would work, I've seen a number of posts discouraging the use of them.

My other thought was to declare ClientList as a slice in my main function, and then I pass ClientList to my HandleClient function, so whenever a client connects/disconnects I can call AddClient or RemoveClient and pass this slice in and add/remove the appropriate client.

This implementation is seen below. There are definitely other issues with the code, but I'm stuck trying to wrap my head around something that seems like it should be very simple.

type Client struct {
    Name string
    Conn net.Conn
}

type ClientList []*Client

// Identify is used to set the name of the client
func (cl *Client) Identify() error {
// code here to set the client's name in the based on input from client
}

// This is not a threadsafe way to do this - need to use mutex/channels
func (cList *ClientList) AddClient(cl *Client) {
    *cList = append(*cList, cl)
}

func (cl *Client) HandleClient(cList *ClientList) {
    defer cl.Conn.Close()
    cList.AddClient(cl)
    err := cl.Identify()
    if err != nil {
        log.Println(err)
        return
    }
    for {
        err := cl.Conn.SetDeadline(time.Now().Add(20 * time.Second))
        if err != nil {
            log.Println(err)
            return
        }
        cl.Conn.Write([]byte("What command would you like to perform?\n"))
        netData, err := bufio.NewReader(cl.Conn).ReadString('\n')
        if err != nil {
            log.Println(err)
            return
        }
        cmd := strings.TrimSpace(string(netData))
        if cmd == "Ping" {
            cl.Ping() //sends a pong msg back to client
        } else {
            cl.Conn.Write([]byte("Unsupported command at this time\n"))
        }

    }
}

func main() {
    arguments := os.Args

    PORT := ":" + arguments[1]
    l, err := net.Listen("tcp4", PORT)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer l.Close()
    fmt.Println("Listening...")

    // Create a new slice to store pointers to clients
    var cList ClientList

    for {
        c, err := l.Accept()
        if err != nil {
            log.Println(err)
            return
        }
        // Create client cl1
        cl1 := Client{Conn: c}

        // Go and handle the client
        go cl1.HandleClient(&cList)
    }
}

From my initial testing, this appears to work. I am able to print out my client list and I can see that new clients are being added, and their name is being added after Identify() is called as well.

When I run it with the -race flag, I do get data race warnings, so I know I will need a threadsafe way to handle adding clients. The same goes for removing clients when I add that in.

Are there any other issues I might be missing by passing my ClientList  into HandleClient, or any benefits I would gain from declaring ClientList as a package level variable instead?

Body:
Several problems with this approach.

First, your code contains a data race: each TCP connection is served by a separate goroutine, and they all attempt to modify the slice concurrently.

You might try building your code with go build -race (or go install -race — whatever you're using), and see it crash by the enabled runtime checks.

This one is easy to fix. The most straightforward approach is to add a mutex variable into the ClientList type:

type ClientList struct {
  mu      sync.Mutex
  clients []*Client
}

…and make the type's methods hold the mutex while they're mutating the clients field, like this:

func (cList *ClientList) AddClient(cl *Client) {
  cList.mu.Lock()
  defer cList.mu.Unlock()

  cList.clients = append(cList.clients, o)
}

(If you will ever encounter the typical usage pattern of your ClientList type is to frequently call methods which only read the contained list, you may start using the sync.RWLock type instead, which allows multiple concurrent readers.)

Second, I'd split the part which "identifies" a client out of the handler function.
As of now, in the handler, if the identification fails, the handler exits but the client is not delisted.

I'd say it would be better to identify it up front and only run the handler once the client is beleived to be okay.

Also it supposedly worth adding a deferred call to something like RemoveClient at the top of the handler's body so that the client is properly delisted when the handler is done with it.

IOW, I'd expect to see something like this:

func (cl *Client) HandleClient(cList *ClientList) {
    defer cl.Conn.Close()

    err := cl.Identify()
    if err != nil {
        log.Println(err)
        return
    }

    cList.AddClient(cl)
    defer cList.RemoveClient(cl)

    // ... the rest of the code
}


问:
java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
Below is the error I am getting while migrating yo Java 8 with API Level 24
Looks like it's from lombok pre-processor. Any help appreciated
   Error:/MyApp.native.android/AndroidApp/src/main/java/com/cba/MyApp/android/view/fragment/ProfileDetails/tabs/Profile.java:21: The import lombok cannot be resolved</p>

```<code>FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':AndroidApp:compileMyAppDebugJavaWithJack'.
> java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':AndroidApp:compileMyAppDebugJavaWithJack'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
at org.gradle.execution.taskgraph.ParallelTaskPlanExecutor.process(ParallelTaskPlanExecutor.java:47)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:154)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:52)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:151)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:99)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:93)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:62)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:93)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:82)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:94)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:43)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:78)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:48)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:52)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: java.lang.RuntimeException: java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
at com.android.builder.tasks.Job.awaitRethrowExceptions(Job.java:79)
at com.android.build.gradle.tasks.JackTask.compile(JackTask.java:133)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:227)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:220)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:209)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:585)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:568)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
... 68 more
Caused by: java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
at com.android.build.gradle.tasks.JackTask$1.run(JackTask.java:120)
at com.android.builder.tasks.Job.runTask(Job.java:51)
at com.android.build.gradle.tasks.SimpleWorkQueue$EmptyThreadContext.runTask(SimpleWorkQueue.java:41)
at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:223)
Caused by: com.android.jack.api.v01.CompilationException: Failed to compile
at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:109)
at com.android.builder.core.AndroidBuilder.convertByteCodeUsingJackApis(AndroidBuilder.java:1931)
at com.android.build.gradle.tasks.JackTask.doMinification(JackTask.java:148)
at com.android.build.gradle.tasks.JackTask.access$000(JackTask.java:73)
at com.android.build.gradle.tasks.JackTask$1.run(JackTask.java:112)
... 3 more
Caused by: com.android.jack.frontend.FrontendCompilationException: Failed to compile
at com.android.jack.Jack.buildSession(Jack.java:978)
at com.android.jack.Jack.run(Jack.java:496)
at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:102)
... 7 more

BUILD FAILED
com.android.jack.api.v01.CompilationException: Failed to compile
at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:109)
at com.android.builder.core.AndroidBuilder.convertByteCodeUsingJackApis(AndroidBuilder.java:1931)
at com.android.build.gradle.tasks.JackTask.doMinification(JackTask.java:148)
at com.android.build.gradle.tasks.JackTask.access$000(JackTask.java:73)
at com.android.build.gradle.tasks.JackTask$1.run(JackTask.java:112)
at com.android.builder.tasks.Job.runTask(Job.java:51)
at com.android.build.gradle.tasks.SimpleWorkQueue$EmptyThreadContext.runTask(SimpleWorkQueue.java:41)
at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:223)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.android.jack.frontend.FrontendCompilationException: Failed to compile
at com.android.jack.Jack.buildSession(Jack.java:978)
at com.android.jack.Jack.run(Jack.java:496)
at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:102)
... 8 more
Warning: Exception while processing task java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
:AndroidApp:compileMyAppDebugJavaWithJack FAILED
</code>```

答:
The Jack toolchain is deprecated as per this blog post.
You can look at the migration guide to R8/D8/Java8 here</p>

Body:
Below is the error I am getting while migrating yo Java 8 with API Level 24
Looks like it's from lombok pre-processor. Any help appreciated
   Error:/MyApp.native.android/AndroidApp/src/main/java/com/cba/MyApp/android/view/fragment/ProfileDetails/tabs/Profile.java:21: The import lombok cannot be resolved

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':AndroidApp:compileMyAppDebugJavaWithJack'.
> java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':AndroidApp:compileMyAppDebugJavaWithJack'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
at org.gradle.execution.taskgraph.ParallelTaskPlanExecutor.process(ParallelTaskPlanExecutor.java:47)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:154)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:52)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:151)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:99)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:93)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:62)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:93)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:82)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:94)
at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:43)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:78)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:48)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:52)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: java.lang.RuntimeException: java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
at com.android.builder.tasks.Job.awaitRethrowExceptions(Job.java:79)
at com.android.build.gradle.tasks.JackTask.compile(JackTask.java:133)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:227)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:220)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:209)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:585)
at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:568)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
... 68 more
Caused by: java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
at com.android.build.gradle.tasks.JackTask$1.run(JackTask.java:120)
at com.android.builder.tasks.Job.runTask(Job.java:51)
at com.android.build.gradle.tasks.SimpleWorkQueue$EmptyThreadContext.runTask(SimpleWorkQueue.java:41)
at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:223)
Caused by: com.android.jack.api.v01.CompilationException: Failed to compile
at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:109)
at com.android.builder.core.AndroidBuilder.convertByteCodeUsingJackApis(AndroidBuilder.java:1931)
at com.android.build.gradle.tasks.JackTask.doMinification(JackTask.java:148)
at com.android.build.gradle.tasks.JackTask.access$000(JackTask.java:73)
at com.android.build.gradle.tasks.JackTask$1.run(JackTask.java:112)
... 3 more
Caused by: com.android.jack.frontend.FrontendCompilationException: Failed to compile
at com.android.jack.Jack.buildSession(Jack.java:978)
at com.android.jack.Jack.run(Jack.java:496)
at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:102)
... 7 more

BUILD FAILED
com.android.jack.api.v01.CompilationException: Failed to compile
at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:109)
at com.android.builder.core.AndroidBuilder.convertByteCodeUsingJackApis(AndroidBuilder.java:1931)
at com.android.build.gradle.tasks.JackTask.doMinification(JackTask.java:148)
at com.android.build.gradle.tasks.JackTask.access$000(JackTask.java:73)
at com.android.build.gradle.tasks.JackTask$1.run(JackTask.java:112)
at com.android.builder.tasks.Job.runTask(Job.java:51)
at com.android.build.gradle.tasks.SimpleWorkQueue$EmptyThreadContext.runTask(SimpleWorkQueue.java:41)
at com.android.builder.tasks.WorkQueue.run(WorkQueue.java:223)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.android.jack.frontend.FrontendCompilationException: Failed to compile
at com.android.jack.Jack.buildSession(Jack.java:978)
at com.android.jack.Jack.run(Jack.java:496)
at com.android.jack.api.v01.impl.Api01ConfigImpl$Api01CompilationTaskImpl.run(Api01ConfigImpl.java:102)
... 8 more
Warning: Exception while processing task java.io.IOException: com.android.jack.api.v01.CompilationException: Failed to compile
:AndroidApp:compileMyAppDebugJavaWithJack FAILED


问:
How to send pdf file from Kuzzle plugin response?
I'm using Kuzzle as a backend for all my business logic for a mobile application and multiple websites.
On one website, I need to download a PDF containing multiple reports. To stay in the same architecture, I want to achieve this in a custom Kuzzle plugin.

The default response of a plugin is wrapped in a default HTML response , how ca I precise custom headers to send a file ?

答:
You can use the Request.setResult method to specify that your a returning a raw payload and to modify response headers.

Then simply return a Buffer containing the file content.

```<code>async sendPdf (request) {
  const file = fs.readFileSync('./file.pdf');
  request.setResult(null, {
    // Tell Kuzzle that this result will contain a raw payload
    raw: true,
    headers: {
      // Set HTTP response headers
      'Content-Length': file.length.toString(),
      'Content-Type': 'application/pdf',
      'Content-Disposition': `attachment; filename="file.pdf"`,
      'Cache-Control': 'no-cache'
    }
  );
  return file;
}
</code>```

Of course this will only work with the HTTP or WebSocket protocol.

Body:
You can use the Request.setResult method to specify that your a returning a raw payload and to modify response headers.

Then simply return a Buffer containing the file content.

async sendPdf (request) {
  const file = fs.readFileSync('./file.pdf');
  request.setResult(null, {
    // Tell Kuzzle that this result will contain a raw payload
    raw: true,
    headers: {
      // Set HTTP response headers
      'Content-Length': file.length.toString(),
      'Content-Type': 'application/pdf',
      'Content-Disposition': `attachment; filename="file.pdf"`,
      'Cache-Control': 'no-cache'
    }
  );
  return file;
}

Of course this will only work with the HTTP or WebSocket protocol.


问:
KStream with multiple nodes
Building stream application using kafka stream. I have topic with 8 partition, where application keep posting/publishing the message to topic and created a Kstream on top of this topic. so far good with creating stream as i started only one instance(JVM), as per the documentation, stream create in local JVM, but my problem is if if move code into QA or production,  I will have 8 JVM runs parallel, hence 8 streams getting created per JVM...

Now, my real time service(micro service) code tries to read the data from stream(ip address are behind netscaler), how will it behave because of stream is in location .. all my 8 instance will be having same copy of the data or else wil be partial ?

答:
TL;DR:   It will be "partial".

In a Kafka Streams application with a basic topology with one input topic only, assuming one thread per application instance (num.stream.threads), if you launch several application instances with the same application name, they will share the partitions that you have in your input topic.

For example, if you have 8 partitions and you launch 8 KafkaStreams instances like this, each will manage one partition (this distribution happens automatically).
It will also be fault tolerant: if any of the 8 applications die - then the extra partition will be managed by one of the other 7 remaining tasks. Also, if you add one extra task (to have 9 over 8 partitions), one of them will remain idle, and will pick up only in case of failure of any of the other instances.

Title: KStream with multiple nodes