问:
What does the following mean?
can someone explain what does the below statement does ? </p>

```<code>def commit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
</code>```

答:
Invokes the 'shell' to execute git rev-parse on HEAD this gets the SHA1 of the revision.
So the commit variable is the SHA1 of the commit on HEAD.

Title: What does the following mean?

Body:
can someone explain what does the below statement does ?

def commit = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()


来源: stackexchange

问:
How to create a ServiceMonitor for prometheus-operator?
Recently, prometheus-operator has been promoted to stable helm chart (https://github.com/helm/charts/tree/master/stable/prometheus-operator).

I'd like to understand how to add a custom application to monitoring by prometheus-operator in a k8s cluster. An example for say gitlab runner which by default provides metrics on 9252 would be appreciated (https://docs.gitlab.com/runner/monitoring/#configuration-of-the-metrics-http-server).

I have a rudimentary yaml that obviously doesn't work but also not provides any feedback on what isn't working:

```<code>apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: gitlab-monitor
  # Change this to the namespace the Prometheus instance is running in
  namespace: default
  labels:
    app: gitlab-runner-gitlab-runner
    release: prometheus
spec:
  selector:
    matchLabels:
      app: gitlab-runner-gitlab-runner
  namespaceSelector:
    # matchNames:
    # - default
    any: true
  endpoints:
  - port: http-metrics
    interval: 15s
</code>```

This is the prometheus configuration:

```<code>> kubectl get prometheus -o yaml

...
serviceMonitorNamespaceSelector: {}
serviceMonitorSelector:
  matchLabels:
    release: prometheus
...
</code>```

So the selectors should match. By "not working" I mean that the endpoints do not appear in the prometheus UI.

答:
I know this question is already answered. But I had a similar problem when Prometheus deployed in Kubernetes with Helm's stable/prometheus-operator chart couldn't find any active targets for my ServiceMonitor.
It turned out that my Service exposed a port that I didn't explicitly named:

```<code>  - protocol: TCP
    port: 8080
    targetPort: uwsgi
</code>```

I could use it in Ingress by targeting uwsgi port. But it seems that ServiceMonitor needs an explicitly named port in Service even if it has the same name as its own tagetPort:

```<code>  - name: uwsgi
    protocol: TCP
    port: 8080
    targetPort: uwsgi
</code>```

I have written a blog post about this problem here

ContentLicense: CC BY-SA 4.0

Body:
Recently, prometheus-operator has been promoted to stable helm chart (https://github.com/helm/charts/tree/master/stable/prometheus-operator).

I'd like to understand how to add a custom application to monitoring by prometheus-operator in a k8s cluster. An example for say gitlab runner which by default provides metrics on 9252 would be appreciated (https://docs.gitlab.com/runner/monitoring/#configuration-of-the-metrics-http-server).

I have a rudimentary yaml that obviously doesn't work but also not provides any feedback on what isn't working:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: gitlab-monitor
  # Change this to the namespace the Prometheus instance is running in
  namespace: default
  labels:
    app: gitlab-runner-gitlab-runner
    release: prometheus
spec:
  selector:
    matchLabels:
      app: gitlab-runner-gitlab-runner
  namespaceSelector:
    # matchNames:
    # - default
    any: true
  endpoints:
  - port: http-metrics
    interval: 15s

This is the prometheus configuration:

> kubectl get prometheus -o yaml

...
serviceMonitorNamespaceSelector: {}
serviceMonitorSelector:
  matchLabels:
    release: prometheus
...

So the selectors should match. By "not working" I mean that the endpoints do not appear in the prometheus UI.

Body:
I know this question is already answered. But I had a similar problem when Prometheus deployed in Kubernetes with Helm's stable/prometheus-operator chart couldn't find any active targets for my ServiceMonitor.
It turned out that my Service exposed a port that I didn't explicitly named:

  - protocol: TCP
    port: 8080
    targetPort: uwsgi

I could use it in Ingress by targeting uwsgi port. But it seems that ServiceMonitor needs an explicitly named port in Service even if it has the same name as its own tagetPort:

  - name: uwsgi
    protocol: TCP
    port: 8080
    targetPort: uwsgi

I have written a blog post about this problem here


问:
Using the number of statements in a function as a constant for memory allocation
I have a function which executes a bunch of tests. Whenever a new test is created, the function gets one or two more lines. And - the result is pushed back into an array. So it goes something like this (simplified):

```<code>void foo(int *results) {
    auto index { 0 };

    results[i++] = test_1(some, args, here);
    results[i++] = test_1(some, other_args, here);

    results[i++] = test_2(some, args, here);

    results[i++] = test_3(some, args, here);

    // etc. etc.
}

void bar() {
    auto results = new int/* magic */];
    foo(results);
}
</code>```

I want to use the number of statements in this function to allocate space for the results (the line in bar()). I cannot use a dynamically-reallocated structure like an std::vector or a list etc. - since I am precluded from allocating any memory due to hardware restrictions.

Now, I could just manually count the lines - and this would work. But then whenever I add another test I would have to remember to update the magical constant.

Is there some way to do the counting with the result usable for the "magic" expression?

Note: Since I'm a scrupulous man with no dignity, I am willing to stoop to the use of macros.

答:
Speaking of macro hackery:

```<code>#include <iostream>

#define ADD_TEST(X) do { results[i++] = (X); (void)__COUNTER__; } while (0)

const int foo_start = __COUNTER__;
void foo(int *results) {
    int i = 0;
    ADD_TEST(100);
    ADD_TEST(200);
    ADD_TEST(300);
}
const int foo_end = __COUNTER__;

int main() {
    int results[foo_end - foo_start - 1];
    foo(results);
    for (int i : results) {
        std::cout << i << '\n';
    }
}
</code>```

It's slightly awful and __COUNTER__ is a non-standard extension in GCC and other compilers, but hey, it works.

The advantage is that it doesn't use any fancy C++ features, so in principle it should be compatible with older compilers and even C.

Body:
I have a function which executes a bunch of tests. Whenever a new test is created, the function gets one or two more lines. And - the result is pushed back into an array. So it goes something like this (simplified):

void foo(int *results) {
    auto index { 0 };

    results[i++] = test_1(some, args, here);
    results[i++] = test_1(some, other_args, here);

    results[i++] = test_2(some, args, here);

    results[i++] = test_3(some, args, here);

    // etc. etc.
}

void bar() {
    auto results = new int/* magic */];
    foo(results);
}

I want to use the number of statements in this function to allocate space for the results (the line in bar()). I cannot use a dynamically-reallocated structure like an std::vector or a list etc. - since I am precluded from allocating any memory due to hardware restrictions.

Now, I could just manually count the lines - and this would work. But then whenever I add another test I would have to remember to update the magical constant.

Is there some way to do the counting with the result usable for the "magic" expression?

Note: Since I'm a scrupulous man with no dignity, I am willing to stoop to the use of macros.

Body:
Speaking of macro hackery:

#include <iostream>

#define ADD_TEST(X) do { results[i++] = (X); (void)__COUNTER__; } while (0)

const int foo_start = __COUNTER__;
void foo(int *results) {
    int i = 0;
    ADD_TEST(100);
    ADD_TEST(200);
    ADD_TEST(300);
}
const int foo_end = __COUNTER__;

int main() {
    int results[foo_end - foo_start - 1];
    foo(results);
    for (int i : results) {
        std::cout << i << '\n';
    }
}

It's slightly awful and __COUNTER__ is a non-standard extension in GCC and other compilers, but hey, it works.

The advantage is that it doesn't use any fancy C++ features, so in principle it should be compatible with older compilers and even C.


问:
FireFox problem on draggable div with non-draggable children image
I have set up a horizontal draggable div using the script below. In chrome everything works fine and children images are not darggable as I set draggable='false'.

As I read here the attribute draggable='false' is not enough in FireFox. I have tried both old and updated answer on the above question (ondragstart="return false")and both of them work on a simple image in the screen but in my case I think somewhere it is being overriden by the drag-handlig script on the parent div. I can not find where the conflict occures whether in the CSS or SCRIPT.

note: As you see in the script I assume the movement smaller than 8px as click event and the problem starts after 8px of movement. Actually in the Firefox after 8px of movement, The images are being cut from the parent and you can drag it everywhere in the window.

function handle_mousedown(e){

    window.my_dragging = {};
    my_dragging.pageX0 = e.pageX;
    my_dragging.pageY0 = e.pageY;
    my_dragging.elem = this;
    my_dragging.offset0 = $(this).scrollLeft();

    $(".catHolder").on("click",function(e){return true;});

    function handle_dragging(e){
     var amount=e.pageX - my_dragging.pageX0;
        var left = my_dragging.offset0 - amount;

        if (Math.abs(amount)>8){
         $(".catHolder").one("click",function(e){return false;});
        }
        $(my_dragging.elem).scrollLeft(left);
    }

    function handle_mouseup(e){
     $(".catHolder").on("click",function(e){return true;});
        $(window).off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
    }

    $(window).on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
}

$(document).ready(function(){$(".catHolder").mousedown(handle_mousedown);})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.catHolder{
  width:400px;
  max-width:100%;
  border:5px solid #ff8800;
  -webkit-overflow-scrolling: touch;
  white-space:nowrap;
  overflow-x:auto;
  overflow-y:hidden;
}

.noselect{
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.catSquare{
  display:inline-block;
}</code>```

text

text

text

text

```

答:
As the images are the children of  tag, I had to add  ondragstart="return false" on  tag too. In fact the  tag receives the mousdown event first and the images was being darrged with their parent anchor.

function handle_mousedown(e){

    window.my_dragging = {};
    my_dragging.pageX0 = e.pageX;
    my_dragging.pageY0 = e.pageY;
    my_dragging.elem = this;
    my_dragging.offset0 = $(this).scrollLeft();

    $(".catHolder").on("click",function(e){return true;});

    function handle_dragging(e){
     var amount=e.pageX - my_dragging.pageX0;
        var left = my_dragging.offset0 - amount;

        if (Math.abs(amount)>8){
         $(".catHolder").one("click",function(e){return false;});
        }
        $(my_dragging.elem).scrollLeft(left);
    }

    function handle_mouseup(e){
     $(".catHolder").on("click",function(e){return true;});
        $(window).off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
    }

    $(window).on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
}

$(document).ready(function(){$(".catHolder").mousedown(handle_mousedown);})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.catHolder{
  width:400px;
  max-width:100%;
  border:5px solid #ff8800;
  -webkit-overflow-scrolling: touch;
  white-space:nowrap;
  overflow-x:auto;
  overflow-y:hidden;
}

.noselect{
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.catSquare{
  display:inline-block;
}</code>```

text

text

text

text

```

Body:
I have set up a horizontal draggable div using the script below. In chrome everything works fine and children images are not darggable as I set draggable='false'.

As I read here the attribute draggable='false' is not enough in FireFox. I have tried both old and updated answer on the above question (ondragstart="return false")and both of them work on a simple image in the screen but in my case I think somewhere it is being overriden by the drag-handlig script on the parent div. I can not find where the conflict occures whether in the CSS or SCRIPT.

note: As you see in the script I assume the movement smaller than 8px as click event and the problem starts after 8px of movement. Actually in the Firefox after 8px of movement, The images are being cut from the parent and you can drag it everywhere in the window.

function handle_mousedown(e){

    window.my_dragging = {};
    my_dragging.pageX0 = e.pageX;
    my_dragging.pageY0 = e.pageY;
    my_dragging.elem = this;
    my_dragging.offset0 = $(this).scrollLeft();

    $(".catHolder").on("click",function(e){return true;});

    function handle_dragging(e){
     var amount=e.pageX - my_dragging.pageX0;
        var left = my_dragging.offset0 - amount;

        if (Math.abs(amount)>8){
         $(".catHolder").one("click",function(e){return false;});
        }
        $(my_dragging.elem).scrollLeft(left);
    }

    function handle_mouseup(e){
     $(".catHolder").on("click",function(e){return true;});
        $(window).off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
    }

    $(window).on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
}

$(document).ready(function(){$(".catHolder").mousedown(handle_mousedown);})

.catHolder{
  width:400px;
  max-width:100%;
  border:5px solid #ff8800;
  -webkit-overflow-scrolling: touch;
  white-space:nowrap;
  overflow-x:auto;
  overflow-y:hidden;
}

.noselect{
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.catSquare{
  display:inline-block;
}

text

text

text

text

Body:
As the images are the children of <a> tag, I had to add  ondragstart="return false" on <a> tag too. In fact the <a> tag receives the mousdown event first and the images was being darrged with their parent anchor.

function handle_mousedown(e){

    window.my_dragging = {};
    my_dragging.pageX0 = e.pageX;
    my_dragging.pageY0 = e.pageY;
    my_dragging.elem = this;
    my_dragging.offset0 = $(this).scrollLeft();

    $(".catHolder").on("click",function(e){return true;});

    function handle_dragging(e){
     var amount=e.pageX - my_dragging.pageX0;
        var left = my_dragging.offset0 - amount;

        if (Math.abs(amount)>8){
         $(".catHolder").one("click",function(e){return false;});
        }
        $(my_dragging.elem).scrollLeft(left);
    }

    function handle_mouseup(e){
     $(".catHolder").on("click",function(e){return true;});
        $(window).off('mousemove', handle_dragging).off('mouseup', handle_mouseup);
    }

    $(window).on('mouseup', handle_mouseup).on('mousemove', handle_dragging);
}

$(document).ready(function(){$(".catHolder").mousedown(handle_mousedown);})

.catHolder{
  width:400px;
  max-width:100%;
  border:5px solid #ff8800;
  -webkit-overflow-scrolling: touch;
  white-space:nowrap;
  overflow-x:auto;
  overflow-y:hidden;
}

.noselect{
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.catSquare{
  display:inline-block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="catHolder">

    <div class="catSquare noselect">
      <a href="#" draggable="false" ondragstart="return false">
        <table>
          <tr><td><img ondragstart="return false" draggable="false" src="https://www.codesd.com/static/img/logo.jpg"></td></tr>
          <tr><td>text</td></tr>
        </table>
      </a>
    </div>

    <div class="catSquare">
      <a href="#" draggable="false" ondragstart="return false">
        <table>
          <tr><td><img  ondragstart="return false" draggable="false" src="https://www.codesd.com/static/img/logo.jpg"></td></tr>
          <tr><td>text</td></tr>
        </table>
      </a>
    </div>

    <div class="catSquare">
      <a href="#" draggable="false" ondragstart="return false">
        <table>
          <tr><td><img  ondragstart="return false" draggable="false" src="https://www.codesd.com/static/img/logo.jpg"></td></tr>
          <tr><td>text</td></tr>
        </table>
      </a>
    </div>

    <div class="catSquare">
      <a href="#" draggable="false" ondragstart="return false">
        <table>
          <tr><td><img  ondragstart="return false" draggable="false" src="https://www.codesd.com/static/img/logo.jpg"></td></tr>
          <tr><td>text</td></tr>
        </table>
      </a>
    </div>

    <div style="clear:both"></div>
</div>


答:
First thing need to understand is

what is sh function?

You need to understand what is returnStdout?

You need to know what is git rev-parse HEAD?

for git rev-parse you need to read this git-rev-parse

If you want to get the stdout just use returnStdout as true

Actually it try to extract commit information

Title: What does the following mean?


问:
SAP Function Module to SQL Server stored procedure
I am trying to convert a SAP ETL process (implemented by BODS) to SQL Server (SSIS).

The process is for delta changes (every 15 minutes) and the object is called “0FI_AP_4” in SAP. I want to implement an SSIS package (SQL Server stored procedure) doing the same thing.

The person who implemented this package in BODS is gone and I have no knowledge of SAP ABAP or BODS.

I can see that the Data Source Name for this package is “BWFID_GET_FIAP_ITEM” which is a function module.

I need to know which SAP tables are being populated by this package or by function module “BWFID_GET_FIAP_ITEM”.

How can I find out the process implemented by this package?

Or how can I find out the source tables and target tables of this function module?

Can I call this function module using openquery or opensql in SQL Server, and access the results from a SAP table?

答:
Assuming your retired colleague specified RFC FM as a source of BODS job

you need to do two things

Analyze what is done in the FM, what is put as input and what is returned. For this use SE37 tcode in SAP, it is is quite easy and self-explanatory

Analyze what is done in BODS job itself, how data returned from RFC is mapped to resulting SQL Server table(s) and whether any transformations are conducted

The task of moving all FM logic to SQL procedure can be huge depending on the implementation of FM, so to minimize your effort you can implement in SQL only BODS mappings/code and all remaining FM logic just call directly. Here is the sample of VBScript code you can use

```<code>Function Connect_RFC ()
  dim retcd

  Set funcControl = CreateObject ("SAP.Functions")
  set objconnection=funcControl.connection

  objconnection.ApplicationServer = "sap.bods.server.com"
  objconnection.System="B06"
  objconnection.Client="403"
  objconnection.User="boqas"
  objconnection.Password="x3x33"
  objconnection.Language"'PT"
  objconnection.tracelevel=6
  objconnection.SystemNumber="01"

  retcd = objconnection.Logon(0, True)    ' Calling logon method

  if retcd = False Then
    msgbox "retcd = FALSE"
  end if

  set tab_handle = funcControl.Add( "BWFID_GET_FIAP_ITEM" )
  tab_handle.call
  set TDATA = tab_handle.tables ("T_INPUT")   ' input table parameter for FM

  if retcd = True then
    Connect_RFC = True
  else
    Connect_RFC = False
  end if
End Function
</code>```

Also look at the SAP BW Source component of Microsoft Connector for SAP BW, it supposedly has the ability to call RFC modules from SSIS Designer.
This simple guide digging into SAP BODS architecture will also help you to find the solution.

Body:
Assuming your retired colleague specified RFC FM as a source of BODS job

you need to do two things

Analyze what is done in the FM, what is put as input and what is returned. For this use SE37 tcode in SAP, it is is quite easy and self-explanatory

Analyze what is done in BODS job itself, how data returned from RFC is mapped to resulting SQL Server table(s) and whether any transformations are conducted

The task of moving all FM logic to SQL procedure can be huge depending on the implementation of FM, so to minimize your effort you can implement in SQL only BODS mappings/code and all remaining FM logic just call directly. Here is the sample of VBScript code you can use

Function Connect_RFC ()
  dim retcd

  Set funcControl = CreateObject ("SAP.Functions")
  set objconnection=funcControl.connection

  objconnection.ApplicationServer = "sap.bods.server.com"
  objconnection.System="B06"
  objconnection.Client="403"
  objconnection.User="boqas"
  objconnection.Password="x3x33"
  objconnection.Language"'PT"
  objconnection.tracelevel=6
  objconnection.SystemNumber="01"

  retcd = objconnection.Logon(0, True)    ' Calling logon method

  if retcd = False Then
    msgbox "retcd = FALSE"
  end if

  set tab_handle = funcControl.Add( "BWFID_GET_FIAP_ITEM" )
  tab_handle.call
  set TDATA = tab_handle.tables ("T_INPUT")   ' input table parameter for FM

  if retcd = True then
    Connect_RFC = True
  else
    Connect_RFC = False
  end if
End Function

Also look at the SAP BW Source component of Microsoft Connector for SAP BW, it supposedly has the ability to call RFC modules from SSIS Designer.
This simple guide digging into SAP BODS architecture will also help you to find the solution.


问:
Getting multiple data from single cell in database
I need to take the data ( image URLs ) that stored in a single cell on my database. Then display it in a while loop.

I've tried the get the data with json_decode but unfortunately, I didn't succeed.

My code is something like this:

```<code><?php
    $i = 0;

    $query = "SELECT * FROM portfolio ";
    $select_all_portfolio_thumbnails = mysqli_query( $connection, $query );

    while( $row = mysqli_fetch_assoc( $select_all_portfolio_thumbnails ) ) {
        $portfolio_thumbnails = $row['portfolio_thumbnails'];
?>

<div class="nv-portfolio-item-box nv-portfolio-items-hidden" id="nv-portfolio-item-box--<?php echo ++$i ?>" >
    <div class="nv-portfolio-item-thumbnails">
        <img class="nv-portfolio-item" style="background-image: url( 'assets/img/portfolio/<?php echo $portfolio_thumbnails[$i] ?>' );">
    </div>
</div>

<?php } ?>
</code>```

The data on my cell is something like this: 1.jpg,2.jpg,3.jpg

On this example, I would like to create 3 image tag with the containing the image URLs in order.

Thanks much.
~
Nathan.

答:
Here You have split that string to array then you have to loop that in foreach like below </p>

```<code>$portfolio_thumbnails = '1.jpg,2.jpg,3.jpg';
$imageArray = explode(',',$portfolio_thumbnails);
foreach ($imageArray as $key => $value) {?>
    <div class="nv-portfolio-item-box nv-portfolio-items-hidden" id="nv-portfolio-item-box--<?php echo ++$i ?>" >
    <div class="nv-portfolio-item-thumbnails">
        <img class="nv-portfolio-item" style="background-image: url( 'assets/img/portfolio/<?php echo $value ?>' );">
    </div>
</div>
<?php
}
</code>```

Body:
I need to take the data ( image URLs ) that stored in a single cell on my database. Then display it in a while loop.

I've tried the get the data with json_decode but unfortunately, I didn't succeed.

My code is something like this:

<?php
    $i = 0;

    $query = "SELECT * FROM portfolio ";
    $select_all_portfolio_thumbnails = mysqli_query( $connection, $query );

    while( $row = mysqli_fetch_assoc( $select_all_portfolio_thumbnails ) ) {
        $portfolio_thumbnails = $row['portfolio_thumbnails'];
?>

<div class="nv-portfolio-item-box nv-portfolio-items-hidden" id="nv-portfolio-item-box--<?php echo ++$i ?>" >

        <img class="nv-portfolio-item" style="background-image: url( 'assets/img/portfolio/<?php echo $portfolio_thumbnails[$i] ?>' );">

<?php } ?>

The data on my cell is something like this: 1.jpg,2.jpg,3.jpg

On this example, I would like to create 3 image tag with the containing the image URLs in order.

Thanks much.
~
Nathan.

Body:
Here You have split that string to array then you have to loop that in foreach like below

$portfolio_thumbnails = '1.jpg,2.jpg,3.jpg';
$imageArray = explode(',',$portfolio_thumbnails);
foreach ($imageArray as $key => $value) {?>
    <div class="nv-portfolio-item-box nv-portfolio-items-hidden" id="nv-portfolio-item-box--<?php echo ++$i ?>" >
    <div class="nv-portfolio-item-thumbnails">
        <img class="nv-portfolio-item" style="background-image: url( 'assets/img/portfolio/<?php echo $value ?>' );">
    </div>
</div>
<?php
}


问:
Android SurfaceView not showing onDraw
For simpleness of the question, I'm drawing an integer on a SurfaceView which increases by 1 every draw.
The increasing actually happens, as I can see on the System.out.
The text on the screen stays on '0'.
Who can tell me what I'm doing wrong?

SurfaceViewTest.java

```<code>package com.niek.surfaceviewtest;

import android.app.Activity;
import android.os.Bundle;

public class SurfaceViewTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
</code>```

StatusView.java

```<code>package com.niek.surfaceviewtest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class StatusView extends SurfaceView implements SurfaceHolder.Callback {

    private int tmp;
    private DrawThread drawThread;

    public StatusView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
        setFocusable(true);
        drawThread = new DrawThread(getHolder());
    }

    @Override
    public void onDraw(Canvas c) {
            c.drawColor(Color.BLACK);
        Paint p = new Paint();
        p.setColor(Color.RED);
        c.drawText(tmp + "", 10, 10, p);
        tmp++;

        System.out.println(tmp);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        drawThread.setRunning(true);
        drawThread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // we have to tell thread to shut down & wait for it to finish, or else
        // it might touch the Surface after we return and explode
        boolean retry = true;
        drawThread.setRunning(false);
        while (retry) {
            try {
                drawThread.join();
                retry = false;
            } catch (InterruptedException e) {
                // we will try it again and again...
            }
        }
    }

    protected class DrawThread extends Thread {
        private SurfaceHolder surfaceHolder;
        private boolean isRunning;

        public DrawThread(SurfaceHolder surfaceHolder) {
            this.surfaceHolder = surfaceHolder;
            isRunning = false;
        }

        public void setRunning(boolean run) {
            isRunning = run;
        }

        public void run() {
            Canvas c;
            while (isRunning) {
                c = null;
                try {
                    c = surfaceHolder.lockCanvas(null);
                    synchronized (surfaceHolder) {
                        onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}
</code>```

main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">

    <com.niek.surfaceviewtest.StatusView
        android:id="@+id/statusview1"
        android:layout_width="fill_parent"
        android:layout_height="30dip"
        android:background="#000000"
 />
</LinearLayout>
</code>```

答:
My only guess is that painting isn't being done on the surface because the view isn't invalidated. You're supposed to call invalidate() in order to draw, and then let the framework call onDraw(). Maybe that's why tmp is being incremented, but the paint operation only reaches the surface the first time.

It might be worth experimenting: maybe make Canvas c a member of StatusView, and then replace

```<code>synchronized (surfaceHolder) {
  onDraw(c);
}
</code>```

with

```<code>synchronized (surfaceHolder) {
  invalidate();
}
</code>```

Does that work?

ContentLicense: CC BY-SA 3.0

Title: Android SurfaceView not showing onDraw

Body:
For simpleness of the question, I'm drawing an integer on a SurfaceView which increases by 1 every draw.
The increasing actually happens, as I can see on the System.out.
The text on the screen stays on '0'.
Who can tell me what I'm doing wrong?

SurfaceViewTest.java

package com.niek.surfaceviewtest;

import android.app.Activity;
import android.os.Bundle;

public class SurfaceViewTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

StatusView.java

package com.niek.surfaceviewtest;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class StatusView extends SurfaceView implements SurfaceHolder.Callback {

    private int tmp;
    private DrawThread drawThread;

    public StatusView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
        setFocusable(true);
        drawThread = new DrawThread(getHolder());
    }

    @Override
    public void onDraw(Canvas c) {
            c.drawColor(Color.BLACK);
        Paint p = new Paint();
        p.setColor(Color.RED);
        c.drawText(tmp + "", 10, 10, p);
        tmp++;

        System.out.println(tmp);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        drawThread.setRunning(true);
        drawThread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // we have to tell thread to shut down & wait for it to finish, or else
        // it might touch the Surface after we return and explode
        boolean retry = true;
        drawThread.setRunning(false);
        while (retry) {
            try {
                drawThread.join();
                retry = false;
            } catch (InterruptedException e) {
                // we will try it again and again...
            }
        }
    }

    protected class DrawThread extends Thread {
        private SurfaceHolder surfaceHolder;
        private boolean isRunning;

        public DrawThread(SurfaceHolder surfaceHolder) {
            this.surfaceHolder = surfaceHolder;
            isRunning = false;
        }

        public void setRunning(boolean run) {
            isRunning = run;
        }

        public void run() {
            Canvas c;
            while (isRunning) {
                c = null;
                try {
                    c = surfaceHolder.lockCanvas(null);
                    synchronized (surfaceHolder) {
                        onDraw(c);
                    }
                } finally {
                    // do this in a finally so that if an exception is thrown
                    // during the above, we don't leave the Surface in an
                    // inconsistent state
                    if (c != null) {
                        surfaceHolder.unlockCanvasAndPost(c);
                    }
                }
            }
        }
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">

    <com.niek.surfaceviewtest.StatusView
        android:id="@+id/statusview1"
        android:layout_width="fill_parent"
        android:layout_height="30dip"
        android:background="#000000"
 />
</LinearLayout>

Body:
My only guess is that painting isn't being done on the surface because the view isn't invalidated. You're supposed to call invalidate() in order to draw, and then let the framework call onDraw(). Maybe that's why tmp is being incremented, but the paint operation only reaches the surface the first time.

It might be worth experimenting: maybe make Canvas c a member of StatusView, and then replace

synchronized (surfaceHolder) {
  onDraw(c);
}

with

synchronized (surfaceHolder) {
  invalidate();
}

Does that work?


问:
Does Python have a function which computes multinomial coefficients?
I was looking for a Python library function which computes multinomial coefficients.

I could not find any such function in any of the standard libraries.
For binomial coefficients (of which multinomial coefficients are a generalization) there is scipy.special.binom and also scipy.misc.comb. Also, numpy.random.multinomial draws samples from a multinomial distribution, and sympy.ntheory.multinomial.multinomial_coefficients returns a dictionary related to multinomial coefficients.

However, I could not find a multinomial coefficients function proper, which given a,b,...,z returns (a+b+...+z)!/(a! b! ... z!). Did I miss it? Is there a good reason there is none available?

I would be happy to contribute an efficient implementation to SciPy say. (I would have to figure out how to contribute, as I have never done this).

For background, they do come up when expanding (a+b+...+z)^n. Also, they count the ways of depositing a+b+...+z distinct objects into distinct bins such that the first bin contains a objects, etc. I need them occasionally for a Project Euler problem.

BTW, other languages do offer this function: Mathematica, MATLAB, Maple.

答:
Starting Python 3.8,

since the standard library now includes the math.comb function (binomial coefficient)

and since the multinomial coefficient can be computed as a product of binomial coefficients

we can implement it without external libraries:

```<code>import math

def multinomial(*params):
  return math.prod(math.comb(sum(params[:i]), x) for i, x in enumerate(params, 1))

multinomial(10, 20, 30) # 3553261127084984957001360
</code>```

Body:
Starting Python 3.8,

since the standard library now includes the math.comb function (binomial coefficient)

and since the multinomial coefficient can be computed as a product of binomial coefficients

we can implement it without external libraries:

import math

def multinomial(*params):
  return math.prod(math.comb(sum(params[:i]), x) for i, x in enumerate(params, 1))

multinomial(10, 20, 30) # 3553261127084984957001360


问:
grails add validation error to hasErrors
I'd like to know how to add a custom error to the hasErrors method so that the gsp picks up the error. My code thus far.</p>

```<code>def recoverySetup = new RecoverySetup(params)

def onesolOrgkey = OnesolOrgkeyInfo.get(new OnesolOrgkeyInfo(params));

if(onesolOrgkey != null) {
    recoverySetup.setOneSolOrgkey(onesolOrgkey)
} else {
    recoverySetup.errors.reject('orgkey', 'You must provide a valid Org Key')
}

recoverySetup.validate()

if(recoverySetup.hasErrors()) {
    render view: 'create', model: [recoverySetupInstance: recoverySetup]
    return
}
</code>```

答:
Your question I'd like to know how to add a custom error to the hasErrors method so that the gsp picks up the error is a bit closed, in that it specifically mentions the hasErrors as the way you want to do it.

Another, much simpler, approach is to just create a flash message in your controller before you return to the gsp

```<code>flash.error = 'You must provide a valid Org Key'
render view: 'create', model: [recoverySetupInstance: recoverySetup]
return
</code>```

Then in your gsp, a block to show that flash.error ...

```<code><g:if test="${flash.error}">
<div class="errors" role="status">${flash.error}</div>
</g:if>
</code>```

This works nicely for those business rule validations that you don't necessarily want to build into your objects, e.g. I used this when I wanted to prevent users accidentally adding duplicates, to a table that could allow duplicates in other cases.

Body:
I'd like to know how to add a custom error to the hasErrors method so that the gsp picks up the error. My code thus far.

def recoverySetup = new RecoverySetup(params)

def onesolOrgkey = OnesolOrgkeyInfo.get(new OnesolOrgkeyInfo(params));

if(onesolOrgkey != null) {
    recoverySetup.setOneSolOrgkey(onesolOrgkey)
} else {
    recoverySetup.errors.reject('orgkey', 'You must provide a valid Org Key')
}

recoverySetup.validate()

if(recoverySetup.hasErrors()) {
    render view: 'create', model: [recoverySetupInstance: recoverySetup]
    return
}

Body:
Your question I'd like to know how to add a custom error to the hasErrors method so that the gsp picks up the error is a bit closed, in that it specifically mentions the hasErrors as the way you want to do it.

Another, much simpler, approach is to just create a flash message in your controller before you return to the gsp

flash.error = 'You must provide a valid Org Key'
render view: 'create', model: [recoverySetupInstance: recoverySetup]
return

Then in your gsp, a block to show that flash.error ...

<g:if test="${flash.error}">
<div class="errors" role="status">${flash.error}</div>
</g:if>

This works nicely for those business rule validations that you don't necessarily want to build into your objects, e.g. I used this when I wanted to prevent users accidentally adding duplicates, to a table that could allow duplicates in other cases.


问:
How can I save a value from MySQL database into a .txt file when a download button is clicked?
I am just getting started with MySQL and PHP, I created a table "Joke" in my database and I showed the data in my PHP server side with this code:

```<code>$result = mysqli_query($link, 'SELECT joketext FROM joke');

while ($row = mysqli_fetch_array($result))
{
  $jokes[] = $row['joketext'];
}

include 'jokes.html.php';
</code>```

And HTML code:

```<code><p>Here are all the jokes in the database:</p>
    <?php foreach ($jokes as $joke): ?>
      <blockquote><p>
        <?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8'); ?>
      </p></blockquote>
    <?php endforeach; ?>
</code>```

That's worked for me, but now I want to add a button "download" beside each joke to download it in .txt file.

答:
If you modify the HTML/PHP portion of your page to include a simple hyperlink like this:

```<code><p>Here are all the jokes in the database:</p>
<?php foreach ($jokes as $id => $joke): ?>
  <blockquote>
      <p>
        <?php
            echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8');
        ?>
      </p>
      <a class='download' href='#' title='Download the joke'>Download</a>
  </blockquote>
<?php endforeach; ?>
</code>```

Then copy the javascript from below to your page you should find that you are able to download the jokes as desired. If you copy all of the code below you should find that it will run in your browser ok.

```<code><html>
    <head>
        <title>Download a joke</title>
        <script>
            /*
                wait for the DOM to load and then set event listeners
                on the new hyperlinks
            */
            document.addEventListener('DOMContentLoaded', ()=>{
                /*
                    Query the DOM for ALL hyperlinks of class `download`
                    and assign an event handler for click events
                */
                document.querySelectorAll('a.download').forEach( function(a){
                    a.addEventListener( 'click', function( event ){
                        /*
                            prevent the default action for this hyperlink
                        */
                        event.preventDefault();

                        /*
                            The Joke is located in the previous
                            DOM node - P
                        */
                        let p=this.previousElementSibling;

                        /*
                            create a BLOB object to store the joke text
                        */
                        let blob=new Blob([ p.innerText ],{type: 'text/plain'});

                        /*
                            function to send the file - jiggery pokery
                        */
                        const sendfile=function( blob, name ){
                            let url=URL.createObjectURL( blob );
                            let lnk=document.createElement('a');
                            let evt=new MouseEvent('click',{
                                bubbles:true,
                                cancelable:true,
                                view:window
                            });
                            p.appendChild( lnk );
                            lnk.href=url;
                            lnk.download=name;
                            lnk.dispatchEvent( evt );
                            p.removeChild( lnk );
                        }

                        sendfile.call( this, blob, 'joke.txt' );
                    });
                });
            });
        </script>
    </head>
    <body>

        <!-- EXAMPLE DATA -->
        <blockquote>
            <p>
                This is the joke - not very funny though is it?
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>
                This is another joke - or what passes for a joke!
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>
                This is probably not the best joke in the World.
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>
                A woman gets on a bus with her baby. The bus driver says: 'Ugh, that's the ugliest
                baby I've ever seen!' The woman walks to the rear of the bus and sits down, fuming.
                She says to a man next to her: 'The driver just insulted me!' The man says: 'You go
                up there and tell him off. Go on, I'll hold your monkey for you.
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

    </body>
</html>
</code>```

Body:
I am just getting started with MySQL and PHP, I created a table "Joke" in my database and I showed the data in my PHP server side with this code:

$result = mysqli_query($link, 'SELECT joketext FROM joke');

while ($row = mysqli_fetch_array($result))
{
  $jokes[] = $row['joketext'];
}

include 'jokes.html.php';

And HTML code:

Here are all the jokes in the database:

    <?php foreach ($jokes as $joke): ?>

        <?php echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8'); ?>

    <?php endforeach; ?>

That's worked for me, but now I want to add a button "download" beside each joke to download it in .txt file.

Body:
If you modify the HTML/PHP portion of your page to include a simple hyperlink like this:

<p>Here are all the jokes in the database:</p>
<?php foreach ($jokes as $id => $joke): ?>
  <blockquote>
      <p>
        <?php
            echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8');
        ?>
      </p>
      <a class='download' href='#' title='Download the joke'>Download</a>
  </blockquote>
<?php endforeach; ?>

Then copy the javascript from below to your page you should find that you are able to download the jokes as desired. If you copy all of the code below you should find that it will run in your browser ok.

<html>
    <head>
        <title>Download a joke</title>
        <script>
            /*
                wait for the DOM to load and then set event listeners
                on the new hyperlinks
            */
            document.addEventListener('DOMContentLoaded', ()=>{
                /*
                    Query the DOM for ALL hyperlinks of class `download`
                    and assign an event handler for click events
                */
                document.querySelectorAll('a.download').forEach( function(a){
                    a.addEventListener( 'click', function( event ){
                        /*
                            prevent the default action for this hyperlink
                        */
                        event.preventDefault();

                        /*
                            The Joke is located in the previous
                            DOM node - P
                        */
                        let p=this.previousElementSibling;

                        /*
                            create a BLOB object to store the joke text
                        */
                        let blob=new Blob([ p.innerText ],{type: 'text/plain'});

                        /*
                            function to send the file - jiggery pokery
                        */
                        const sendfile=function( blob, name ){
                            let url=URL.createObjectURL( blob );
                            let lnk=document.createElement('a');
                            let evt=new MouseEvent('click',{
                                bubbles:true,
                                cancelable:true,
                                view:window
                            });
                            p.appendChild( lnk );
                            lnk.href=url;
                            lnk.download=name;
                            lnk.dispatchEvent( evt );
                            p.removeChild( lnk );
                        }

                        sendfile.call( this, blob, 'joke.txt' );
                    });
                });
            });
        </script>
    </head>
    <body>

        <!-- EXAMPLE DATA -->
        <blockquote>
            <p>
                This is the joke - not very funny though is it?
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>
                This is another joke - or what passes for a joke!
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>
                This is probably not the best joke in the World.
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

        <blockquote>
            <p>
                A woman gets on a bus with her baby. The bus driver says: 'Ugh, that's the ugliest
                baby I've ever seen!' The woman walks to the rear of the bus and sits down, fuming.
                She says to a man next to her: 'The driver just insulted me!' The man says: 'You go
                up there and tell him off. Go on, I'll hold your monkey for you.
            </p>
            <a class='download' href='#' title='Download the joke'>Download</a>
        </blockquote>

    </body>
</html>


问:
pmvnorm error; sigma not covariance matrix
I have variance-cov matrices made in stata, that i want to use in R in pmvtnorm, for example:

```<code>library(mvtnorm)
library(matrixcalc)

sigma = read.csv(file="c:/Users/../sigma1.csv", header=F, sep=",")
sigma <- as.matrix(sigma)

is.symmetric.matrix(sigma)
is.positive.definite(sigma)

m = nrow(sigma)
Fn = pmvnorm(lower=rep(-Inf, m), upper=rep(0, m), mean=rep(0, m), sigma=sigma)
</code>```

When i run this sequence I get the error message:

```<code>Error in checkmvArgs(lower = lower, upper = upper, mean = mean, corr = corr,  :
  ‘sigma’ is not a covariance matrix
</code>```

Checking for positive definiteness and symmetry both show true, and most of the matrices i import to R i have already used in similar stata commands without a problem... Link for sigma1.csv:

link for sigma1.csv

答:
```<code>sigma <- read.csv(file = "data/sigma.csv", header = F, sep = ",")
mat <- matrix(0, nrow = nrow(sigma), ncol = ncol(sigma))
sigma <- as.matrix(sigma)
attributes(sigma) <- attributes(mat)
# str(sigma)
# is.symmetric.matrix(sigma)
# is.positive.definite(sigma)
m <- nrow(sigma)
Fn <- pmvnorm(
  lower = rep(-Inf, m), upper = rep(0, m),
  mean = rep(0, m), sigma = sigma
)
Fn
</code>```

```<code>[1] 6.747892e-29
attr(,"error")
[1] 2.005038e-31
attr(,"msg")
[1] "Normal Completion"
</code>```

Just make sure sigma is a matrix

Body:
I have variance-cov matrices made in stata, that i want to use in R in pmvtnorm, for example:

library(mvtnorm)
library(matrixcalc)

sigma = read.csv(file="c:/Users/../sigma1.csv", header=F, sep=",")
sigma <- as.matrix(sigma)

is.symmetric.matrix(sigma)
is.positive.definite(sigma)

m = nrow(sigma)
Fn = pmvnorm(lower=rep(-Inf, m), upper=rep(0, m), mean=rep(0, m), sigma=sigma)

When i run this sequence I get the error message:

Error in checkmvArgs(lower = lower, upper = upper, mean = mean, corr = corr,  :
  ‘sigma’ is not a covariance matrix

Checking for positive definiteness and symmetry both show true, and most of the matrices i import to R i have already used in similar stata commands without a problem... Link for sigma1.csv:

link for sigma1.csv

Body:
sigma <- read.csv(file = "data/sigma.csv", header = F, sep = ",")
mat <- matrix(0, nrow = nrow(sigma), ncol = ncol(sigma))
sigma <- as.matrix(sigma)
attributes(sigma) <- attributes(mat)
# str(sigma)
# is.symmetric.matrix(sigma)
# is.positive.definite(sigma)
m <- nrow(sigma)
Fn <- pmvnorm(
  lower = rep(-Inf, m), upper = rep(0, m),
  mean = rep(0, m), sigma = sigma
)
Fn

[1] 6.747892e-29
attr(,"error")
[1] 2.005038e-31
attr(,"msg")
[1] "Normal Completion"

Just make sure sigma is a matrix


问:
Rails 5.2.3 / Heroku - Why is it not possible to run postgres in production mode with squlite3 in development mode?
I'm using Rails 5.2.3 and I'm getting an application error when I try to view my production app on Heroku pipeline & the following errors when:

I run heroku logs I get: heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"

I run heroku run rails console I get: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. (LoadError)

I run heroku run rails db:migrate I get: LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

I want to use sqlite3 for development and postgres for production, so why do I need to make the sqlite3 gemfile available in production mode?

Here's my gemfile:

```<code>group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end
</code>```

Here's my database.yml:

```<code>default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
</code>```

答:
Try your database.yml like this,

```<code>default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  adapter: postgresql
  pool: 5
  timeout: 5000
  database: db/production.sqlite3
</code>```

Body:
I'm using Rails 5.2.3 and I'm getting an application error when I try to view my production app on Heroku pipeline & the following errors when:

I run heroku logs I get: heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"

I run heroku run rails console I get: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile. (LoadError)

I run heroku run rails db:migrate I get: LoadError: Error loading the 'sqlite3' Active Record adapter. Missing a gem it depends on? sqlite3 is not part of the bundle. Add it to your Gemfile.

I want to use sqlite3 for development and postgres for production, so why do I need to make the sqlite3 gemfile available in production mode?

Here's my gemfile:

group :development do
  gem 'sqlite3'
end

group :production do
  gem 'pg'
end

Here's my database.yml:

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3

Body:
Try your database.yml like this,

default: &default
  adapter: sqlite3
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

test:
  <<: *default
  database: db/test.sqlite3

production:
  adapter: postgresql
  pool: 5
  timeout: 5000
  database: db/production.sqlite3


问:
header("Location: ".$_SERVER['HTTP_REFERER']); stooped working when moved to a server
when running the code in xampp this statement works but when i moved the code to the production instance the code stops working.

ps: the way I'm evoking the php file is through a form submission.

```<code>if (!empty($_SERVER['HTTP_REFERER']))
header("Location: ".$_SERVER['HTTP_REFERER']);
else
print "<br> referpage:".$_SERVER['HTTP_REFERER'];
</code>```

when printing header("Location: ".$_SERVER['HTTP_REFERER']); it is returning empty.

答:
Try this</p>

```<code>if(!empty($_SERVER['HTTP_REFERER'])){
$referer = $_SERVER['HTTP_REFERER'];
header("Location: $referer");
}
else
print "<br> referpage:".$_SERVER['HTTP_REFERER'];
</code>```

Body:
when running the code in xampp this statement works but when i moved the code to the production instance the code stops working.

ps: the way I'm evoking the php file is through a form submission.

if (!empty($_SERVER['HTTP_REFERER']))
header("Location: ".$_SERVER['HTTP_REFERER']);
else
print "
 referpage:".$_SERVER['HTTP_REFERER'];

when printing header("Location: ".$_SERVER['HTTP_REFERER']); it is returning empty.

Body:
Try this

if(!empty($_SERVER['HTTP_REFERER'])){
$referer = $_SERVER['HTTP_REFERER'];
header("Location: $referer");
}
else
print "<br> referpage:".$_SERVER['HTTP_REFERER'];


问:
How to get return values from Async/await function when fetching the data from mySQL in Nodejs
I am fetching some exchange data from DB, then extracting the name of distinct exchanges and passing again into MYSQL query to fetch data from a different table.

The problem I am facing is that async await does not return the value rather just return Promise {  }.

Below is the code that I am trying, wondering where I am going wrong.

```<code>//Function that fetches the exchanges from DB

const getExchange = () => {
        return new Promise((resolve, reject) => {
            db.connection.query(`
            SELECT  *
            FROM,
            (
            SELECT
                exchange,
                COUNT(pair) as noOfMarkets
                FROM ticker_data

        ) as t
            `, (err, resp) => {
                if (!err) {
                    resolve(resp)
                } else {
                    reject(err)
                }
            })
        })
    }

// push unique exchanges to an array.
const getExchangesData = async () => {
    const allExchanges = await getExchanges();

    let exchanges = []
    allExchanges.forEach(item => {
        let exchange = {
            exchange: item.exchange
        }
        exchanges.push(exchange)
    })
    return await exchanges
}

// mapping through an array of exchanges and passing to DB query to get data from the DB.

const getSingleExchange = async () => {
    const exchanges = await getExchangesData()
    await Promise.all(exchanges.map(async (item) => {
        db.connection.query(`
        SELECT
       exchange_rank,
       name
       volume24hUSD
       (
            SELECT
            volume24hUSD as tradingVolYesterday
            FROM exchanges
            WHERE name = '${item.exchange}'
            AND createdAt >= now() -interval 1 day
            AND createdAt <  now() -interval 1 day + interval 120 second
            LIMIT 1
       ) volumeDay1
FROM exchanges
WHERE name = '${item.exchange}'
        `, (err, resp) => {
            if (!err) {
                console.log(resp) // getting all the values

                let volData = {
                     name: resp[0].name,
                     exchange_rank: resp[0].exchange_rank,
                     icon: resp[0].icon
                 }
                 return volData
            }
        })
    }))
}

const data = getSingleExchange()
console.log(data) // returning Promise { <pending> }
</code>```

Edit

After making changes suggested in an answer, I still have an issue:

```<code>//Function that fetches the exchanges from DB

const getExchange = () => {
        return new Promise((resolve, reject) => {
            db.connection.query(`
            SELECT  *
            FROM,
            (
            SELECT
                exchange,
                COUNT(pair) as noOfMarkets
                FROM ticker_data

        ) as t
            `, (err, resp) => {
                if (!err) {
                    resolve(resp)
                } else {
                    reject(err)
                }
            })
        })
    }

// push unique exchanges to an array.
const getExchangesData = async () => {
    const allExchanges = await getExchanges();

    let exchanges = []
    allExchanges.forEach(item => {
        let exchange = {
            exchange: item.exchange
        }
        exchanges.push(exchange)
    })
    return await exchanges
}

    // mapping through an array of exchanges and passing to DB query to get data from the DB.

const getSingleExchange = async () => {
    const exchanges = await getExchangesData()
    await Promise.all(exchanges.map((item) => {
        return new Promise((resolve, reject) => {
            db.connection.query(`...`, (err, resp) => {
                if (!err) {
                    resolve(resp)
                } else {
                    reject(err)
                }
            }).then(resp => {
                console.log(resp)
                let volData = {
                    name: resp[0].name,
                    exchange_rank: resp[0].exchange_rank,
                    icon: resp[0].icon
                }
                return volData
            })
        })
    }))

}

getSingleExchange().then(data => {
    console.log(data)
});
</code>```

I now get this error:

(node:30583) UnhandledPromiseRejectionWarning: TypeError: db.connection.query(...).then is not a function

      at Promise (/getExchanges.js:217:16)

      at new Promise ()

      at Promise.all.exchanges.map (/getExchanges.js:145:16)

      at Array.map ()

      at getSingleExchange (/getExchanges.js:144:33)

答:
The main issue is in this part:

```<code>await Promise.all(exchanges.map(async (item) => {
</code>```

That map callback is not returning anything, and it has no await, so using async makes no sense.

Instead remove async:

```<code>await Promise.all(exchanges.map((item) => {
</code>```

... and return a promise in the callback function, much like you had done in the first function:

```<code>    return new Promise((resolve, reject) => {
        db.connection.query(`...`), (err, resp) => {
            if (!err) {
                resolve(resp)
            } else {
                reject(err)
            }
        })
    }).then(resp => {
        console.log(resp)
        let volData = {
             name: resp[0].name,
             exchange_rank: resp[0].exchange_rank,
             icon: resp[0].icon
         }
         return volData
    });
</code>```

You would benefit from writing one generic function that promisifies query, so that you don't have to do that new Promise-thing for every single query you need.

Finally, you cannot expect to get an asynchronous result synchronously: async functions do not return the asynchronous result synchronously, but return a promise for it. So your last lines (main code) should still await. So either do this:

```<code>(async () => {
    const data = await getSingleExchange()
    console.log(data)
})(); // immediately executing (async) function expression
</code>```

Or:

```<code>getSingleExchange().then(data => {
    console.log(data)
});
</code>```

NB: doing return await exchanges in the second function makes no sense (exchanges is not a promise), so you can just do return exchanges.

Body:
I am fetching some exchange data from DB, then extracting the name of distinct exchanges and passing again into MYSQL query to fetch data from a different table.

The problem I am facing is that async await does not return the value rather just return Promise {  }.

Below is the code that I am trying, wondering where I am going wrong.

//Function that fetches the exchanges from DB

const getExchange = () => {
        return new Promise((resolve, reject) => {
            db.connection.query(`
            SELECT  *
            FROM,
            (
            SELECT
                exchange,
                COUNT(pair) as noOfMarkets
                FROM ticker_data

        ) as t
            `, (err, resp) => {
                if (!err) {
                    resolve(resp)
                } else {
                    reject(err)
                }
            })
        })
    }

// push unique exchanges to an array.
const getExchangesData = async () => {
    const allExchanges = await getExchanges();

    let exchanges = []
    allExchanges.forEach(item => {
        let exchange = {
            exchange: item.exchange
        }
        exchanges.push(exchange)
    })
    return await exchanges
}

// mapping through an array of exchanges and passing to DB query to get data from the DB.

const getSingleExchange = async () => {
    const exchanges = await getExchangesData()
    await Promise.all(exchanges.map(async (item) => {
        db.connection.query(`
        SELECT
       exchange_rank,
       name
       volume24hUSD
       (
            SELECT
            volume24hUSD as tradingVolYesterday
            FROM exchanges
            WHERE name = '${item.exchange}'
            AND createdAt >= now() -interval 1 day
            AND createdAt <  now() -interval 1 day + interval 120 second
            LIMIT 1
       ) volumeDay1
FROM exchanges
WHERE name = '${item.exchange}'
        `, (err, resp) => {
            if (!err) {
                console.log(resp) // getting all the values

                let volData = {
                     name: resp[0].name,
                     exchange_rank: resp[0].exchange_rank,
                     icon: resp[0].icon
                 }
                 return volData
            }
        })
    }))
}

const data = getSingleExchange()
console.log(data) // returning Promise { <pending> }

Edit

After making changes suggested in an answer, I still have an issue:

//Function that fetches the exchanges from DB

const getExchange = () => {
        return new Promise((resolve, reject) => {
            db.connection.query(`
            SELECT  *
            FROM,
            (
            SELECT
                exchange,
                COUNT(pair) as noOfMarkets
                FROM ticker_data

        ) as t
            `, (err, resp) => {
                if (!err) {
                    resolve(resp)
                } else {
                    reject(err)
                }
            })
        })
    }

// push unique exchanges to an array.
const getExchangesData = async () => {
    const allExchanges = await getExchanges();

    let exchanges = []
    allExchanges.forEach(item => {
        let exchange = {
            exchange: item.exchange
        }
        exchanges.push(exchange)
    })
    return await exchanges
}

    // mapping through an array of exchanges and passing to DB query to get data from the DB.

const getSingleExchange = async () => {
    const exchanges = await getExchangesData()
    await Promise.all(exchanges.map((item) => {
        return new Promise((resolve, reject) => {
            db.connection.query(`...`, (err, resp) => {
                if (!err) {
                    resolve(resp)
                } else {
                    reject(err)
                }
            }).then(resp => {
                console.log(resp)
                let volData = {
                    name: resp[0].name,
                    exchange_rank: resp[0].exchange_rank,
                    icon: resp[0].icon
                }
                return volData
            })
        })
    }))

}

getSingleExchange().then(data => {
    console.log(data)
});

I now get this error:

(node:30583) UnhandledPromiseRejectionWarning: TypeError: db.connection.query(...).then is not a function

      at Promise (/getExchanges.js:217:16)

      at new Promise ()

      at Promise.all.exchanges.map (/getExchanges.js:145:16)

      at Array.map ()

      at getSingleExchange (/getExchanges.js:144:33)

Body:
The main issue is in this part:

await Promise.all(exchanges.map(async (item) => {

That map callback is not returning anything, and it has no await, so using async makes no sense.

Instead remove async:

await Promise.all(exchanges.map((item) => {

... and return a promise in the callback function, much like you had done in the first function:

    return new Promise((resolve, reject) => {
        db.connection.query(`...`), (err, resp) => {
            if (!err) {
                resolve(resp)
            } else {
                reject(err)
            }
        })
    }).then(resp => {
        console.log(resp)
        let volData = {
             name: resp[0].name,
             exchange_rank: resp[0].exchange_rank,
             icon: resp[0].icon
         }
         return volData
    });

You would benefit from writing one generic function that promisifies query, so that you don't have to do that new Promise-thing for every single query you need.

Finally, you cannot expect to get an asynchronous result synchronously: async functions do not return the asynchronous result synchronously, but return a promise for it. So your last lines (main code) should still await. So either do this:

(async () => {
    const data = await getSingleExchange()
    console.log(data)
})(); // immediately executing (async) function expression

Or:

getSingleExchange().then(data => {
    console.log(data)
});

NB: doing return await exchanges in the second function makes no sense (exchanges is not a promise), so you can just do return exchanges.


问:
The localStorage is not refreshing in Vuex
I write codes with Vuex to login and logout in my Laravel single page application it's working well but when i login to an account the profiles information (name, address, Email, ...)doesn't show in profile but after i reload the page the profile information loads, and when another user try the profile the data of the last person that login shown to him/her

auth.js:

```<code>export function registerUser(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/register', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('Somthing is wrong!!')
        })
    })
}

export function login(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/login', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('The Email or password is incorrect!')
        })
    })
}

export function getLoggedinUser(){
    const userStr = localStorage.getItem('user');

    if(!userStr){
        return null
    }

    return JSON.parse(userStr);
}
</code>```

store.js:

```<code>import {getLoggedinUser} from './partials/auth';
const user = getLoggedinUser();
export default {
    state: {
        currentUser: user,
        isLoggedIn: !!user,
        loading: false,
        auth_error: null,
        reg_error:null,
        registeredUser: null,
    },
    getters: {
        isLoading(state){
            return state.loading;
        },
        isLoggedin(state){
            return state.isLoggedin;
        },
        currentUser(state){
            return state.currentUser;
        },
        authError(state){
            return state.auth_error;
        },
        regError(state){
            return state.reg_error;
        },
        registeredUser(state){
            return state.registeredUser;
        },

    },
    mutations: {
        login(state){
            state.loading = true;
            state.auth_error = null;
        },
        loginSuccess(state, payload){
            state.auth_error = null;
            state.isLoggedin = true;
            state.loading = false;
            state.currentUser = Object.assign({}, payload.user, {token: payload.access_token});

            localStorage.setItem("user", JSON.stringify(state.currentUser));
        },
        loginFailed(state, payload){
            state.loading = false;
            state.auth_error = payload.error;
        },
        logout(state){
            localStorage.removeItem("user");
            state.isLoggedin = false;
            state.currentUser = null;
        },
        registerSuccess(state, payload){
            state.reg_error = null;
            state.registeredUser = payload.user;
        },
        registerFailed(state, payload){
            state.reg_error = payload.error;
        },
    },
    actions: {
        login(context){
            context.commit("login");
        },
    }
};
</code>```

general.js:

```<code>export function initialize(store, router) {
    router.beforeEach((to, from, next) => {
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        const currentUser = store.state.currentUser;

        if(requiresAuth && !currentUser) {
            next('/login');
        } else if(to.path == '/login' && currentUser) {
            next('/');
        } else {
            next();
        }

        if(to.path == '/register' && currentUser) {
            next('/');
        }

    });

    axios.interceptors.response.use(null, (error) => {
        if (error.resposne.status == 401) {
            store.commit('logout');
            router.push('/login');
        }

        return Promise.reject(error);
    });

    if (store.getters.currentUser) {
        setAuthorization(store.getters.currentUser.token);
    }
}

export function setAuthorization(token) {
    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
}
</code>```

I think that this issue is relate to my localstorage, how can i fix this?
I'm novice at the Vue and don't have any idea what is the problem.

Login Component:

```<code><template>
<main>
    <form @submit.prevent="authenticate">
    <div class="grid-x grid-padding-x">

        <div class="small-10 small-offset-2 cell" v-if="registeredUser">
            <p class="alert success">Welcome {{registeredUser.name}}</p>
        </div>
        <div class="small-10 small-offset-2 cell" v-if="authError">
            <p class="alert error">
                {{authError}}
            </p>
        </div>

        <div class="small-2 cell">
            <label for="email" class="text-right middle">Email:</label>
        </div>
        <div class="small-10 cell">
             <input type="email" v-model="formLogin.email" placeholder="Email address">
        </div>

        <div class="small-2 cell">
            <label for="password" class="text-right middle">Password:</label>
        </div>
        <div class="small-10 cell">
             <input type="password" v-model="formLogin.password" placeholder="Enter password">
        </div>

        <div class="small-10 small-offset-2 cell">
            <div class="gap"></div>
            <input type="submit" value="Login" class="button success expanded">
        </div>
    </div>

    </form>

</main>

</template>

<script>
import {login} from '../../partials/auth';
export default {
    data(){
        return {
            formLogin: {
            email: '',
            password: ''
        },
        error: null
        }
    },
    methods:{
        authenticate(){
            this.$store.dispatch('login');

        login(this.$data.formLogin)
            .then(res => {
                this.$store.commit("loginSuccess", res);
                this.$router.push({path: '/profile'});
            })
            .catch(error => {
                this.$store.commit("loginFailed", {error});
            })
        }
    },
    computed:{
        authError(){
            return this.$store.getters.authError
        },
        registeredUser(){
            return this.$store.getters.registeredUser
        }
    }
}
</script>
</code>```

答:
I solved the problem.I have this code in my EditProfile component.

```<code>methods: {
            getAuthUser () {
                axios.get(`./api/auth/me`)
                .then(response => {
                    this.user = response.data
                })
            },
}
</code>```

this.user = response.data is wrong, I changed to this:

```<code>getAuthUser () {
    this.user = this.$store.getters.currentUser
},
</code>```

Body:
I write codes with Vuex to login and logout in my Laravel single page application it's working well but when i login to an account the profiles information (name, address, Email, ...)doesn't show in profile but after i reload the page the profile information loads, and when another user try the profile the data of the last person that login shown to him/her

auth.js:

export function registerUser(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/register', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('Somthing is wrong!!')
        })
    })
}

export function login(credentials){
    return new Promise((res,rej)=>{
        axios.post('./api/auth/login', credentials)
        .then(response => {
            res(response.data);
        })
        .catch(err => {
            rej('The Email or password is incorrect!')
        })
    })
}

export function getLoggedinUser(){
    const userStr = localStorage.getItem('user');

    if(!userStr){
        return null
    }

    return JSON.parse(userStr);
}

store.js:

import {getLoggedinUser} from './partials/auth';
const user = getLoggedinUser();
export default {
    state: {
        currentUser: user,
        isLoggedIn: !!user,
        loading: false,
        auth_error: null,
        reg_error:null,
        registeredUser: null,
    },
    getters: {
        isLoading(state){
            return state.loading;
        },
        isLoggedin(state){
            return state.isLoggedin;
        },
        currentUser(state){
            return state.currentUser;
        },
        authError(state){
            return state.auth_error;
        },
        regError(state){
            return state.reg_error;
        },
        registeredUser(state){
            return state.registeredUser;
        },

    },
    mutations: {
        login(state){
            state.loading = true;
            state.auth_error = null;
        },
        loginSuccess(state, payload){
            state.auth_error = null;
            state.isLoggedin = true;
            state.loading = false;
            state.currentUser = Object.assign({}, payload.user, {token: payload.access_token});

            localStorage.setItem("user", JSON.stringify(state.currentUser));
        },
        loginFailed(state, payload){
            state.loading = false;
            state.auth_error = payload.error;
        },
        logout(state){
            localStorage.removeItem("user");
            state.isLoggedin = false;
            state.currentUser = null;
        },
        registerSuccess(state, payload){
            state.reg_error = null;
            state.registeredUser = payload.user;
        },
        registerFailed(state, payload){
            state.reg_error = payload.error;
        },
    },
    actions: {
        login(context){
            context.commit("login");
        },
    }
};

general.js:

export function initialize(store, router) {
    router.beforeEach((to, from, next) => {
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        const currentUser = store.state.currentUser;

        if(requiresAuth && !currentUser) {
            next('/login');
        } else if(to.path == '/login' && currentUser) {
            next('/');
        } else {
            next();
        }

        if(to.path == '/register' && currentUser) {
            next('/');
        }

    });

    axios.interceptors.response.use(null, (error) => {
        if (error.resposne.status == 401) {
            store.commit('logout');
            router.push('/login');
        }

        return Promise.reject(error);
    });

    if (store.getters.currentUser) {
        setAuthorization(store.getters.currentUser.token);
    }
}

export function setAuthorization(token) {
    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
}

I think that this issue is relate to my localstorage, how can i fix this?
I'm novice at the Vue and don't have any idea what is the problem.

Login Component:

<template>

    <form @submit.prevent="authenticate">

Welcome {{registeredUser.name}}

                {{authError}}

            Email:

             <input type="email" v-model="formLogin.email" placeholder="Email address">

            Password:

             <input type="password" v-model="formLogin.password" placeholder="Enter password">

            <input type="submit" value="Login" class="button success expanded">

    </form>

</template>

Body:
I solved the problem.I have this code in my EditProfile component.

methods: {
            getAuthUser () {
                axios.get(`./api/auth/me`)
                .then(response => {
                    this.user = response.data
                })
            },
}

this.user = response.data is wrong, I changed to this:

getAuthUser () {
    this.user = this.$store.getters.currentUser
},


问:
How to return Complex types from a WCF Data Service?
Is it possible to return a complex type from a WCF data service that is made of collections of entity types ?

for example :

```<code> //the complex type to return
 class Entities
 {
    ICollection<Contract> Contracts;
    ...

 }

 //configuration
 public partial class MyContext: DbContext
 {
    public MyContext()
        : base("name=DBEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.ComplexType<Entities>();
        modelBuilder.Entity<Contract>().HasKey(c=>c.Id);
        ...
    }
    ...
  }

 //the WCF Data Service
 public class PricingDataService : DataService<ObjectContext>, IDisposable
 {
     [WebGet]
     public Entities GetEntities()
     {
         return new Entities();
     }
  }
</code>```

When I try the above configuration, I get an exception :

```<code>" The exception message is 'One or more validation errors
were detected during model     generation: System.Data.Edm.EdmEntityType: Name:
Each type name in a schema must be unique. Type name 'Contract' was already
defined."
</code>```

答: No this is not possible because if you define this, it means that complex type has navigation property to contracts. This is not allowed in whole entity framework. The error probably comes from some infering where Contract is already defined as entity but complext type is trying to map it as something else - but this is just guess.

Body:
Is it possible to return a complex type from a WCF data service that is made of collections of entity types ?

for example :

 //the complex type to return
 class Entities
 {
    ICollection<Contract> Contracts;
    ...

 }

 //configuration
 public partial class MyContext: DbContext
 {
    public MyContext()
        : base("name=DBEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.ComplexType<Entities>();
        modelBuilder.Entity<Contract>().HasKey(c=>c.Id);
        ...
    }
    ...
  }

 //the WCF Data Service
 public class PricingDataService : DataService<ObjectContext>, IDisposable
 {
     [WebGet]
     public Entities GetEntities()
     {
         return new Entities();
     }
  }

When I try the above configuration, I get an exception :

" The exception message is 'One or more validation errors
were detected during model     generation: System.Data.Edm.EdmEntityType: Name:
Each type name in a schema must be unique. Type name 'Contract' was already
defined."


问:
Can't adjust line height of list items in a mat-tree
I’m working with a mat-tree in my Angular 7 application. It looks like this:

```<code><mat-tree [dataSource]="nestedDataSource" [treeControl]="nestedTreeControl" class="example-tree">

<mat-tree-node *matTreeNodeDef="let node">
  <li>
    <span *ngFor="let item of getArrayForIndenting(node)">    </span>
    <button mat-icon-button disabled></button>
    {{ node.name }}: {{ node.value }}
  </li>
</mat-tree-node>

<mat-nested-tree-node *matTreeNodeDef="let node; when: hasNestedChild">
  <div>
    <span *ngFor="let item of getArrayForIndenting(node)">    </span>
    <button mat-icon-button matTreeNodeToggle>
      <mat-icon class="mat-icon-rtl-mirror">
        {{ nestedTreeControl.isExpanded(node) ? 'expand_more' : 'chevron_right' }}
      </mat-icon>
    </button>
    {{ node.name }}
  </div>
  <ul [class.example-tree-invisible]="!nestedTreeControl.isExpanded(node)">
    <ng-container matTreeNodeOutlet></ng-container>
  </ul>
</mat-nested-tree-node>
</code>```

Notice that each node is spaced really far apart vertically. This is what I’m trying to adjust.

I’ve tried everything. I’ve tried styling the height of various elements in the above markup, the line-height, the margins, the padding, etc., but nothing works.

According to this site:

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_ul_compact_css

I should be able to set the line-height on the ul element, but I tried that and it doesn’t work.

Can anyone tell what I’m supposed to do? Thanks.

EDIT: Here's the CSS:

```<code>.example-tree-invisible {
  display: none;
}

.example-tree li,
.example-tree ul {
  list-style-type: none;
}
</code>```

Note that I removed the "mat-tree-node" class 'cause it didn't exist.

There's also a reference to fonts.googleapis.com in my index.html file:

```<code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</code>```

...which is probably what mat-icon-rtl-mirror comes from.

Hope that helps

答:
just use .css to override min-height, e.g.</p>

```<code>.mat-tree-node {
    min-height:1.6rem; //min-heigth:0 if you want the min heigth possible
}
</code>```

Body:
I’m working with a mat-tree in my Angular 7 application. It looks like this:

<mat-tree [dataSource]="nestedDataSource" [treeControl]="nestedTreeControl" class="example-tree">

<mat-tree-node *matTreeNodeDef="let node">

    <button mat-icon-button disabled></button>
    {{ node.name }}: {{ node.value }}

</mat-tree-node>

<mat-nested-tree-node *matTreeNodeDef="let node; when: hasNestedChild">

    <button mat-icon-button matTreeNodeToggle>
      <mat-icon class="mat-icon-rtl-mirror">
        {{ nestedTreeControl.isExpanded(node) ? 'expand_more' : 'chevron_right' }}
      </mat-icon>
    </button>
    {{ node.name }}

    <ng-container matTreeNodeOutlet></ng-container>

</mat-nested-tree-node>

Notice that each node is spaced really far apart vertically. This is what I’m trying to adjust.

I’ve tried everything. I’ve tried styling the height of various elements in the above markup, the line-height, the margins, the padding, etc., but nothing works.

According to this site:

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_ul_compact_css

I should be able to set the line-height on the ul element, but I tried that and it doesn’t work.

Can anyone tell what I’m supposed to do? Thanks.

EDIT: Here's the CSS:

.example-tree-invisible {
  display: none;
}

.example-tree li,
.example-tree ul {
  list-style-type: none;
}

Note that I removed the "mat-tree-node" class 'cause it didn't exist.

There's also a reference to fonts.googleapis.com in my index.html file:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

...which is probably what mat-icon-rtl-mirror comes from.

Hope that helps

Body:
just use .css to override min-height, e.g.

.mat-tree-node {
    min-height:1.6rem; //min-heigth:0 if you want the min heigth possible
}


问:
Creating a dataframe from dictionary with arbitrary length values (using recycled keys as column value)
I am struggling with converting a dictionary into a dataframe.

There are already a lot of answers showing how to do it in the "wide format" like https://stackoverflow.com/a/52819186/6912069 but I would like to do something different, preferably not using loops.

Consider the following example:

I have a dictionary like this one

```<code>d_test = {'A': [1, 2], 'B': [3]}
</code>```

and I'd like to get a dataframe like

```<code>index id    values
0     A     1
1     A     2
2     B     3
</code>```

The index can be a normal consecutive integer column. By recycling I mean turning 'A'=[1, 2] into two rows having A in the id column and the values in the values column. This way I would have a "long format" dataframe of the dictionary items.

It seems to be a very basic thing to do, but I was wondering if there is an elegant pythonic way to achieve this. Many thanks for your help.

答:
I would create 2 lists. One from the keys, and other one from the values of the dictionary. As you defined the lists you can pass the lists into the DataFrame.</p>

```<code>import pandas as pd
dic = {'A': [1, 2], 'B': [3], 'D': [4, 5, 6]}

keys = []
values = []

for key, value in dic.items():
    for v in value:
        keys.append(key)
        values.append(v)

df = pd.DataFrame(
    {'id': keys,
     'values': values,
    })
print(df)
</code>```

Body:
I am struggling with converting a dictionary into a dataframe.

There are already a lot of answers showing how to do it in the "wide format" like https://stackoverflow.com/a/52819186/6912069 but I would like to do something different, preferably not using loops.

Consider the following example:

I have a dictionary like this one

d_test = {'A': [1, 2], 'B': [3]}

and I'd like to get a dataframe like

index id    values
0     A     1
1     A     2
2     B     3

The index can be a normal consecutive integer column. By recycling I mean turning 'A'=[1, 2] into two rows having A in the id column and the values in the values column. This way I would have a "long format" dataframe of the dictionary items.

It seems to be a very basic thing to do, but I was wondering if there is an elegant pythonic way to achieve this. Many thanks for your help.

Body:
I would create 2 lists. One from the keys, and other one from the values of the dictionary. As you defined the lists you can pass the lists into the DataFrame.

import pandas as pd
dic = {'A': [1, 2], 'B': [3], 'D': [4, 5, 6]}

keys = []
values = []

for key, value in dic.items():
    for v in value:
        keys.append(key)
        values.append(v)

df = pd.DataFrame(
    {'id': keys,
     'values': values,
    })
print(df)


问:
Maintain Values for both axis while smoothing with scipy
I have pandas series of type int. I am trying to get a smooth curve rather than a zig-zag structure.

I saw some previous posta about the same problem but they are smoothing the curve with ( x vs y ) plot whereas in my case I have only a pandas series i.e X axis.

I need a curvy smooth plot.

This is the post which I am referring to.

答:
You have exp in y-axis. You can simply generate another series of 1,2,... for x-axis.

```<code>l=[i fo i in range(exp.shape[0])]
series_for_x_axis=pd.Series(l)
</code>```

There you have values for both x and y axis.

Body:
You have exp in y-axis. You can simply generate another series of 1,2,... for x-axis.

l=[i fo i in range(exp.shape[0])]
series_for_x_axis=pd.Series(l)

There you have values for both x and y axis.


问:
Click event on a slider goes at the end of the array
I am trying to create a simple slider using javascript.
So far, here is my code :

html:

```<code>  <div class="carousel-container">

    <div class="slides-container">
      <div class="slide">
        <img src="assets/images/image-1.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-3.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-2.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-3.jpg" alt="">
      </div>
    </div>

  </div>

  <div class="carousel-nav">
    <button class="button-previous">Previous</button>
    <button class="button-next">Next</button>
  </div>
</code>```

Js :

```<code>    const slides = document.querySelectorAll('.slide')
    const slidesContainer = document.querySelector('.slides-container')
    const slidesCount = slides.length
    const slideWidth = slides[0].clientWidth

    const prevButton = document.querySelector('.button-previous')
    const nextButton = document.querySelector('.button-next')

    function nextSlide(slide) {
      for (slide = 0; slide < slidesCount; slide++) {
        slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)'
      }
    }

    nextButton.addEventListener('click', function() {
      nextSlide()
    })
</code>```

The issue I have is that when I click on the next button, the slider goes all the way at the end of my array, thus skipping all the images in between.

What would be the best way to have my for loop stop at each image and go again when the button is clicked?

答:
```<code>let current = 0;

function nextSlide(slide) {
      if (current < slidesCount) {
        slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)';
        current++;
      }
}
</code>```

Body:
I am trying to create a simple slider using javascript.
So far, here is my code :

html:

    <button class="button-previous">Previous</button>
    <button class="button-next">Next</button>

Js :

    const slides = document.querySelectorAll('.slide')
    const slidesContainer = document.querySelector('.slides-container')
    const slidesCount = slides.length
    const slideWidth = slides[0].clientWidth

    const prevButton = document.querySelector('.button-previous')
    const nextButton = document.querySelector('.button-next')

    function nextSlide(slide) {
      for (slide = 0; slide < slidesCount; slide++) {
        slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)'
      }
    }

    nextButton.addEventListener('click', function() {
      nextSlide()
    })

The issue I have is that when I click on the next button, the slider goes all the way at the end of my array, thus skipping all the images in between.

What would be the best way to have my for loop stop at each image and go again when the button is clicked?


问:
Sqlite query to get next avaiable character of search text which contains in firstname or lastname
How to query sqlite database to get list of next available characters after the search keyword in two columns. for example, if the search keyword is ’and’
and let the columns be firstname and lastname :

```<code>And[y] Xyz
And[r]ew And[z]
Xyz And[o]n
Mirand[a] Lorand[e]
</code>```

then i should get the characters [y,r,z,o,a,e].

I tried with substr and instr, but i couldn't write a query that looks in both first and last name and return next character in  both of them.

答:
With UNION ALL for the values from the 2 columns and by using rowid to get the correct order:

```<code>select nextchar from (
  select
    1 col,
    rowid,
    substr(firstname, instr(lower(firstname), 'and') + 3, 1) nextchar
  from names
  where firstname like '%and%'
  union all
  select
    2,
    rowid,
    substr(lastname, instr(lower(lastname), 'and') + 3, 1)
  from names
  where lastname like '%and%'
) t
order by t.rowid, t.col
</code>```

See the demo.

Results:

```<code>| nextchar |
| -------- |
| y        |
| r        |
| z        |
| o        |
| a        |
| e        |
</code>```

If you want the result as a comma separated string, use group_concat():

```<code>select group_concat(nextchar) chars from (
  select nextchar from (
    select
      1 col,
      rowid,
      substr(firstname, instr(lower(firstname), 'and') + 3, 1) nextchar
    from names
    where firstname like '%and%'
    union all
    select
      2,
      rowid,
      substr(lastname, instr(lower(lastname), 'and') + 3, 1)
    from names
    where lastname like '%and%'
  ) t
  order by t.rowid, t.col
)
</code>```

See the demo.

Result:

```<code>| chars       |
| ----------- |
| y,r,z,o,a,e |
</code>```

Body:
How to query sqlite database to get list of next available characters after the search keyword in two columns. for example, if the search keyword is ’and’
and let the columns be firstname and lastname :

And[y] Xyz
And[r]ew And[z]
Xyz And[o]n
Mirand[a] Lorand[e]

then i should get the characters [y,r,z,o,a,e].

I tried with substr and instr, but i couldn't write a query that looks in both first and last name and return next character in  both of them.

Body:
With UNION ALL for the values from the 2 columns and by using rowid to get the correct order:

select nextchar from (
  select
    1 col,
    rowid,
    substr(firstname, instr(lower(firstname), 'and') + 3, 1) nextchar
  from names
  where firstname like '%and%'
  union all
  select
    2,
    rowid,
    substr(lastname, instr(lower(lastname), 'and') + 3, 1)
  from names
  where lastname like '%and%'
) t
order by t.rowid, t.col

See the demo.

Results:

| nextchar |
| -------- |
| y        |
| r        |
| z        |
| o        |
| a        |
| e        |

If you want the result as a comma separated string, use group_concat():

select group_concat(nextchar) chars from (
  select nextchar from (
    select
      1 col,
      rowid,
      substr(firstname, instr(lower(firstname), 'and') + 3, 1) nextchar
    from names
    where firstname like '%and%'
    union all
    select
      2,
      rowid,
      substr(lastname, instr(lower(lastname), 'and') + 3, 1)
    from names
    where lastname like '%and%'
  ) t
  order by t.rowid, t.col
)

See the demo.

Result:

| chars       |
| ----------- |
| y,r,z,o,a,e |