问:
Cannot extract data from post request in node
I am sending a post request using axios in react to a nodejs backend and mysql database.

At the server side when I log req.body, it is undefined
and this is the params and query part when I log the request on server side:

```<code>params: {},
query: {},
</code>```

This is inside the handlelogin method in react:

```<code> handleLogin=(event)=>
    {event.preventDefault();
        let formfields={...this.state.formfields};
        axios.post('http://localhost:7000/api/login',{formfields
        })
        .then(res=>
            {
                    console.log("response receieved");
                })
        .catch(err=>
        {
            console.log(err);
        });
    };
</code>```

This is the node script( inside routes):

```<code>const express = require('express');
const exp = express();
const bodyParser = require('body-parser');
exp.use(bodyParser.urlencoded({extended:false}));
exp.use(bodyParser.json());
const router = express.Router();

router.post('/api/login',(req,res,next)=>{
    console.log('Inside login-serverside');
    console.log(req);
});

module.exports = router;
</code>```

I want to submit forms and pdf files(later) but I cannot access them on the server side.I can acces request.parameters when I make a get request.What is the issue here?

What are body,params and query used for, respectively and what is the difference?

答:
I had not included body parser in my main server.js file

```<code>const bodyParser = require('body-parser');
exp.use(bodyParser.urlencoded({extended:false}));
</code>```

After including this, it's working. I can now successfully use request.body and access the parameters passed in axios.post .

Though I am still confused about the use of params,query,data and body respectively.

Body:
I am sending a post request using axios in react to a nodejs backend and mysql database.

At the server side when I log req.body, it is undefined
and this is the params and query part when I log the request on server side:

params: {},
query: {},

This is inside the handlelogin method in react:

 handleLogin=(event)=>
    {event.preventDefault();
        let formfields={...this.state.formfields};
        axios.post('http://localhost:7000/api/login',{formfields
        })
        .then(res=>
            {
                    console.log("response receieved");
                })
        .catch(err=>
        {
            console.log(err);
        });
    };

This is the node script( inside routes):

const express = require('express');
const exp = express();
const bodyParser = require('body-parser');
exp.use(bodyParser.urlencoded({extended:false}));
exp.use(bodyParser.json());
const router = express.Router();

router.post('/api/login',(req,res,next)=>{
    console.log('Inside login-serverside');
    console.log(req);
});

module.exports = router;

I want to submit forms and pdf files(later) but I cannot access them on the server side.I can acces request.parameters when I make a get request.What is the issue here?

What are body,params and query used for, respectively and what is the difference?

Body:
I had not included body parser in my main server.js file

const bodyParser = require('body-parser');
exp.use(bodyParser.urlencoded({extended:false}));

After including this, it's working. I can now successfully use request.body and access the parameters passed in axios.post .

Though I am still confused about the use of params,query,data and body respectively.


来源: stackexchange

问:
Flexbox stretching image horizontally
I'm running into a weird inconsistency with an image on my website. It's structured like this:

Some text

More text

```

<pre class="lang-css prettyprint-override"><code>.intro {
    display: flex;
    align-items: center;
}

.intro>img {
    width: 11rem;
    height: 11rem;
    border-radius: 6rem;
    margin: 1rem 0;
    align-self: center;
}

.intro>div {
    padding-right: 1rem;
}
</code>```

After a hard reload in Chrome 74, it renders like this (wrong):

But then if I inspect element and toggle any of the img's properties off and on again, it renders like this (correct):

I've come across this question, which suggested adding align-self: center; to the img, but that hasn't helped.

You can see the issue live here: https://leonoverweel.com/. Any idea what the problem is?

答: Adding flex-shrink: 0 to .intro>img seems to fix this, as per Piotr's comment.

ContentLicense: CC BY-SA 4.0

Title: Flexbox stretching image horizontally

Body:
I'm running into a weird inconsistency with an image on my website. It's structured like this:

Some text

More text

.intro {
    display: flex;
    align-items: center;
}

.intro>img {
    width: 11rem;
    height: 11rem;
    border-radius: 6rem;
    margin: 1rem 0;
    align-self: center;
}

.intro>div {
    padding-right: 1rem;
}

After a hard reload in Chrome 74, it renders like this (wrong):

But then if I inspect element and toggle any of the img's properties off and on again, it renders like this (correct):

I've come across this question, which suggested adding align-self: center; to the img, but that hasn't helped.

You can see the issue live here: https://leonoverweel.com/. Any idea what the problem is?


问:
c# file move (file is already used by another process)
I am moving files from one folder to another. If I try to move the entire folder to the folder within that particular folder I cannot do that. But if I move it outside it works fine. How can I move my folder to the folder within that folder?

this gives error

```<code>  if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\copypath\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }
</code>```

this works fine

```<code> if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }
</code>```

答: Perhaps you need to move all the files inside the folder, rather than the folder itself?</p>

ContentLicense: CC BY-SA 3.0

Body:
I am moving files from one folder to another. If I try to move the entire folder to the folder within that particular folder I cannot do that. But if I move it outside it works fine. How can I move my folder to the folder within that folder?

this gives error

  if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\copypath\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }

this works fine

 if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }


问:
Drop down menu - data validation - looking for source
I have been wracking my brain and I’ve lost all will to work (yay!) I have a spreadsheet (wow!) with a drop-down menu and want to remove the drop down list – start new/fresh - however in the validation data tab there is no source to “clear all” and I cannot for the life of me find the main cell that’s picking up the list - but the list is there – just no link or there is one but it’s invisible.

I can’t even create a new column to create a new drop-down because for some reason it copies the same cells over into the new column automatically so I’m stuck with the same list without being able to change it.

Am I missing something?? I can’t see any hidden rows or columns.  I also have a drop-down menu where I don’t even know or can’t even see the list. The spreadsheet is not linked to any other worksheet either and it was created a while back by a person who no longer works here, so can't ask them.

Please don’t tell me I have to create a whole new spreadsheet – there is way too much data in there and it’s giving me a headache. Any assistance would be greatly appreciated and would save me from going grey prematurely.

I'm using Windows 10 pro and Excel 2016.

答:
Excel Method:

Data - Data Tools - Data Validation - Settings tab - Clear All.

VBA Method (One sheet):

```<code>Option Explicit

Sub Clear_Validation()

    With ThisWorkbook.Worksheets("Sheet1")

        .Cells.Validation.Delete

    End With

End Sub
</code>```

VBA Method (Loop sheets):

```<code>Option Explicit

Sub Clear_Validation()

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets

        With ws

            .Cells.Validation.Delete

        End With

    Next ws

End Sub
</code>```

Body:
Excel Method:

Data - Data Tools - Data Validation - Settings tab - Clear All.

VBA Method (One sheet):

Option Explicit

Sub Clear_Validation()

    With ThisWorkbook.Worksheets("Sheet1")

        .Cells.Validation.Delete

    End With

End Sub

VBA Method (Loop sheets):

Option Explicit

Sub Clear_Validation()

    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets

        With ws

            .Cells.Validation.Delete

        End With

    Next ws

End Sub


问:
Redirect to submenu and hide menu link in submenus
So I have this code:

```<code>add_action('admin_menu', function() {

    add_menu_page(
        'Theme options',
        'Theme options',
        'manage_options',
        'ef-theme-options',
        'ef_theme_options_display',
        'dashicons-admin-site'
    );

    add_submenu_page(
        'ef-theme-options',
        'E-shop options',
        'E-shop options',
        'manage_options',
        'ef-eshop-options',
        'ef_eshop_options_display'
    );
});
</code>```

This results in:

```<code>Theme options
- Theme options
- E-shop options
</code>```

Is there easy way to redirect to first submenu if menu is clicked, and hide repeating submenu? Is there wordpress functionality that allows for this kind of manipulations?

答:
```<code>add_submenu_page(
        null,//give that parent slug to null then it will hide from sidebar
        'E-shop options',
        'E-shop options',
        'manage_options',
        'ef-eshop-options',
        'ef_eshop_options_display'
    );
</code>```

Body:
So I have this code:

add_action('admin_menu', function() {

    add_menu_page(
        'Theme options',
        'Theme options',
        'manage_options',
        'ef-theme-options',
        'ef_theme_options_display',
        'dashicons-admin-site'
    );

    add_submenu_page(
        'ef-theme-options',
        'E-shop options',
        'E-shop options',
        'manage_options',
        'ef-eshop-options',
        'ef_eshop_options_display'
    );
});

This results in:

Theme options
- Theme options
- E-shop options

Is there easy way to redirect to first submenu if menu is clicked, and hide repeating submenu? Is there wordpress functionality that allows for this kind of manipulations?


问:
tkinter addition/subtraction calculator problem
I attempted to build a simple calculator that displays the current sum as a label that changes when numbers are added or subtracted via the "ADD" and "SUBTRACT" buttons through the entry window. The widget is functional only visually but cannot calculate the values I want.

I attempted to add a currentsum value set to 0

```<code>from tkinter import*

def addition():
    currentsum=float(e1.get())
    e1.insert(INSERT,str(currentsum))

def subtraction():
    currentsum=currentsum-float(e1.get())
    e1.insert(INSERT,str(currentsum))

def reset():
    currentsum=0
    e1.insert(INSERT,str(currentsum))
window=Tk()

currentsum=0

l1=Label(window,text="current sum:")
l1.grid(row=0, column=0)
l2=Label(window,text=str(currentsum))
l2.grid(row=0,column=1)

e1=Entry(window)
e1.grid(row=1,column=0)

b1=Button(window,text="ADD(+)",command=addition)
b2=Button(window,text="SUBTRACT(-)",command=subtraction)
b3=Button(window,text="RESET",command=reset)
b1.grid(row=2,column=0)
b2.grid(row=2,column=1)
b3.grid(row=2,column=2)

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

Here is the error message:

```<code>Exception in Tkinter callback
Traceback (most recent call last):

  File "C:\Users\Administrator\Downloads\sdfgasgasg.py", line 8, in subtraction
    currentsum=currentsum-float(e1.getenter code here())
UnboundLocalError: local variable 'currentsum' referenced before assignment
</code>```

答:
You are attempting to use currentsum in your methods in a global context but the variable isn't handled properly in a local context in your methods.  The reason why is because currentsum is defined after your methods.  Move that so it's defined before the methods.  Also, if you want to ensure that the variable maintains its changes when each method is called, the "easiest" way to do this is to insert global currentsum in all of your methods so that you're able to access currentsum and modify it

In addition, I would suggest replacing the text that displays the current sum with the running total and not showing this by inserting this into the text field.  Inserting will append what's currently in the text field with currentsum which is probably not what you intended.  Also, there's a bug in your addition method where you should accumulate the value read in from the text field, not replacing it.

Therefore:

```<code>from tkinter import*

currentsum=0

def addition():
   global currentsum # New
   currentsum+=float(e1.get()) # Fix
   #e1.insert(INSERT,str(currentsum))
   l2['text'] = str(currentsum) # Change

def subtraction():
   global currentsum # New
   currentsum=currentsum-float(e1.get())
   #e1.insert(INSERT,str(currentsum))
   l2['text'] = str(currentsum) # Change

def reset():
   global currentsum # New
   currentsum=0
   #e1.insert(INSERT,str(currentsum))
   l2['text'] = str(currentsum) # Change
window=Tk()

l1=Label(window,text="current sum:")
l1.grid(row=0, column=0)
l2=Label(window,text=str(currentsum))
l2.grid(row=0,column=1)

e1=Entry(window)
e1.grid(row=1,column=0)

b1=Button(window,text="ADD(+)",command=addition)
b2=Button(window,text="SUBTRACT(-)",command=subtraction)
b3=Button(window,text="RESET",command=reset)
b1.grid(row=2,column=0)
b2.grid(row=2,column=1)
b3.grid(row=2,column=2)

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

Body:
I attempted to build a simple calculator that displays the current sum as a label that changes when numbers are added or subtracted via the "ADD" and "SUBTRACT" buttons through the entry window. The widget is functional only visually but cannot calculate the values I want.

I attempted to add a currentsum value set to 0

from tkinter import*

def addition():
    currentsum=float(e1.get())
    e1.insert(INSERT,str(currentsum))

def subtraction():
    currentsum=currentsum-float(e1.get())
    e1.insert(INSERT,str(currentsum))

def reset():
    currentsum=0
    e1.insert(INSERT,str(currentsum))
window=Tk()

currentsum=0

l1=Label(window,text="current sum:")
l1.grid(row=0, column=0)
l2=Label(window,text=str(currentsum))
l2.grid(row=0,column=1)

e1=Entry(window)
e1.grid(row=1,column=0)

b1=Button(window,text="ADD(+)",command=addition)
b2=Button(window,text="SUBTRACT(-)",command=subtraction)
b3=Button(window,text="RESET",command=reset)
b1.grid(row=2,column=0)
b2.grid(row=2,column=1)
b3.grid(row=2,column=2)

window.mainloop()

Here is the error message:

Exception in Tkinter callback
Traceback (most recent call last):

  File "C:\Users\Administrator\Downloads\sdfgasgasg.py", line 8, in subtraction
    currentsum=currentsum-float(e1.getenter code here())
UnboundLocalError: local variable 'currentsum' referenced before assignment

Body:
You are attempting to use currentsum in your methods in a global context but the variable isn't handled properly in a local context in your methods.  The reason why is because currentsum is defined after your methods.  Move that so it's defined before the methods.  Also, if you want to ensure that the variable maintains its changes when each method is called, the "easiest" way to do this is to insert global currentsum in all of your methods so that you're able to access currentsum and modify it

In addition, I would suggest replacing the text that displays the current sum with the running total and not showing this by inserting this into the text field.  Inserting will append what's currently in the text field with currentsum which is probably not what you intended.  Also, there's a bug in your addition method where you should accumulate the value read in from the text field, not replacing it.

Therefore:

from tkinter import*

currentsum=0

def addition():
   global currentsum # New
   currentsum+=float(e1.get()) # Fix
   #e1.insert(INSERT,str(currentsum))
   l2['text'] = str(currentsum) # Change

def subtraction():
   global currentsum # New
   currentsum=currentsum-float(e1.get())
   #e1.insert(INSERT,str(currentsum))
   l2['text'] = str(currentsum) # Change

def reset():
   global currentsum # New
   currentsum=0
   #e1.insert(INSERT,str(currentsum))
   l2['text'] = str(currentsum) # Change
window=Tk()

l1=Label(window,text="current sum:")
l1.grid(row=0, column=0)
l2=Label(window,text=str(currentsum))
l2.grid(row=0,column=1)

e1=Entry(window)
e1.grid(row=1,column=0)

b1=Button(window,text="ADD(+)",command=addition)
b2=Button(window,text="SUBTRACT(-)",command=subtraction)
b3=Button(window,text="RESET",command=reset)
b1.grid(row=2,column=0)
b2.grid(row=2,column=1)
b3.grid(row=2,column=2)

window.mainloop()


问:
Mulesoft - How to set Content-Encoding as gzip in order to compress my payload in http API call
I am using Mule 3.8. How do I set Content-Encoding: gzip in order to compress my payload, External_API accepts gzip compressed payload as input??

I am using until-successful in order to retry my http API call. I am not getting right documentation how to set gzip in http request so that payload will be compressed.

```<code>    <flow name="Ingestion_with_retries_Flow" >
    <until-successful objectStore-ref="objectStore" maxRetries="${max.retries}" deadLetterQueue-ref="Queue_Failed_Payload_To_ErrorDir_And_Notify"
                      failureExpression="#[(exception != null) and (exception.causedBy(java.net.ConnectException) || exception.causedBy(java.net.SocketTimeoutException) || exception.causedBy(java.net.SocketException) || exception.causedBy(java.io.IOException))]"
                      doc:name="Until Successful" millisBetweenRetries="${millis.between.retries}">
        <processor-chain doc:name="Processor Chain">
            <http:request config-ref="HTTPS_Ingestion_Service_External_API" path="/delivery" method="POST" doc:name="External API Data Delivery Post">
                <http:request-builder>
                    <http:header headerName="Accept" value="${http.by.interface.version}"/>

                </http:request-builder>
                <http:success-status-code-validator values="200"/>
            </http:request>

            <json:xml-to-json-transformer doc:name="XML to JSON"/>
            <flow-ref name="Subflow_Extract_Ingestion_Response" doc:name="Extract Ingestion Response"/>
        </processor-chain>
    </until-successful>
</flow>
</code>```

答:
Just use the compression module's Compress element to compress the input payload.

You can then set the input listener's response header to Content-Encoding=gzip. This lets the caller/browser know that the response payload is gzip encoded.

Body:
I am using Mule 3.8. How do I set Content-Encoding: gzip in order to compress my payload, External_API accepts gzip compressed payload as input??

I am using until-successful in order to retry my http API call. I am not getting right documentation how to set gzip in http request so that payload will be compressed.

    <flow name="Ingestion_with_retries_Flow" >
    <until-successful objectStore-ref="objectStore" maxRetries="${max.retries}" deadLetterQueue-ref="Queue_Failed_Payload_To_ErrorDir_And_Notify"
                      failureExpression="#[(exception != null) and (exception.causedBy(java.net.ConnectException) || exception.causedBy(java.net.SocketTimeoutException) || exception.causedBy(java.net.SocketException) || exception.causedBy(java.io.IOException))]"
                      doc:name="Until Successful" millisBetweenRetries="${millis.between.retries}">
        <processor-chain doc:name="Processor Chain">
            <http:request config-ref="HTTPS_Ingestion_Service_External_API" path="/delivery" method="POST" doc:name="External API Data Delivery Post">
                <http:request-builder>
                    <http:header headerName="Accept" value="${http.by.interface.version}"/>

                </http:request-builder>
                <http:success-status-code-validator values="200"/>
            </http:request>

            <json:xml-to-json-transformer doc:name="XML to JSON"/>
            <flow-ref name="Subflow_Extract_Ingestion_Response" doc:name="Extract Ingestion Response"/>
        </processor-chain>
    </until-successful>
</flow>


问:
How can I disable all contraints in my postgresql?
I have a PostgreSQL database with tables that have more than 500 billions rows. I'm trying to delete around 6 millions row but it's takes more than 4 minutes. I need to optimize those delete operation to make an useful system.

I think a good idea could be to disable constraints and triggers and then enable it back, so my questions are:

How can I disable all constraints?
And, is it possible to disable relations between tables?

Right now, I just disable the triggers using this:

```<code>Alter table "table_name" disable all
</code>```

And enable it back using this:

```<code>Alter table "table_name" enable all
</code>```

Edit

This is the query result with triggers enabled.

```<code>  Delete on "ParameterValues"  (cost=0.00..1015910.71 rows=47196359 width=6) (actual time=296995.938..296995.938 rows=0 loops=1)
  Buffers: shared hit=6000000 read=420811 dirtied=93346 written=51646
  ->  Seq Scan on "ParameterValues"  (cost=0.00..1015910.71 rows=47196359 width=6) (actual time=7977.126..19798.361 rows=6000000 loops=1)
        Filter: ("Id" < 23000000)
        Rows Removed by Filter: 34218414
        Buffers: shared read=420811 dirtied=49228 written=51646
Planning Time: 304.085 ms
Execution Time: 296995.963 ms
</code>```

Disabling all triggers I improve the performance reducing the execution time from 5 minutes to 3 minutes.

```<code>Alter table "table_name" disable trigger all
</code>```

However, I need to improve more delete operations. Any idea?

答:
If you want a pure pl/pgsql solution. you may use an anonymous block like this( or even a function with table name and schema as arguments).</p>

```<code>DO $$
DECLARE
l_tab_name    TEXT := 'yourtablename';
l_schema_name TEXT := 'public';
rec record;

BEGIN
for rec IN
(
SELECT rel.relname as table_name ,con.conname as constraint_name
       FROM pg_catalog.pg_constraint con
            INNER JOIN pg_catalog.pg_class rel
                       ON rel.oid = con.conrelid
            INNER JOIN pg_catalog.pg_namespace nsp
                       ON nsp.oid = connamespace
       WHERE nsp.nspname     = l_schema_name
             AND rel.relname = l_tab_name
)
  LOOP

       EXECUTE format ('ALTER TABLE %I
                        DROP CONSTRAINT %I',rec.table_name,rec.constraint_name );

  END LOOP;
END $$;
</code>```

Body:
I have a PostgreSQL database with tables that have more than 500 billions rows. I'm trying to delete around 6 millions row but it's takes more than 4 minutes. I need to optimize those delete operation to make an useful system.

I think a good idea could be to disable constraints and triggers and then enable it back, so my questions are:

How can I disable all constraints?
And, is it possible to disable relations between tables?

Right now, I just disable the triggers using this:

Alter table "table_name" disable all

And enable it back using this:

Alter table "table_name" enable all

Edit

This is the query result with triggers enabled.

  Delete on "ParameterValues"  (cost=0.00..1015910.71 rows=47196359 width=6) (actual time=296995.938..296995.938 rows=0 loops=1)
  Buffers: shared hit=6000000 read=420811 dirtied=93346 written=51646
  ->  Seq Scan on "ParameterValues"  (cost=0.00..1015910.71 rows=47196359 width=6) (actual time=7977.126..19798.361 rows=6000000 loops=1)
        Filter: ("Id" < 23000000)
        Rows Removed by Filter: 34218414
        Buffers: shared read=420811 dirtied=49228 written=51646
Planning Time: 304.085 ms
Execution Time: 296995.963 ms

Disabling all triggers I improve the performance reducing the execution time from 5 minutes to 3 minutes.

Alter table "table_name" disable trigger all

However, I need to improve more delete operations. Any idea?

Body:
If you want a pure pl/pgsql solution. you may use an anonymous block like this( or even a function with table name and schema as arguments).

DO $$
DECLARE
l_tab_name    TEXT := 'yourtablename';
l_schema_name TEXT := 'public';
rec record;

BEGIN
for rec IN
(
SELECT rel.relname as table_name ,con.conname as constraint_name
       FROM pg_catalog.pg_constraint con
            INNER JOIN pg_catalog.pg_class rel
                       ON rel.oid = con.conrelid
            INNER JOIN pg_catalog.pg_namespace nsp
                       ON nsp.oid = connamespace
       WHERE nsp.nspname     = l_schema_name
             AND rel.relname = l_tab_name
)
  LOOP

       EXECUTE format ('ALTER TABLE %I
                        DROP CONSTRAINT %I',rec.table_name,rec.constraint_name );

  END LOOP;
END $$;


问:
When does create-react-app obfuscate or minify code?
I have kind of a basic question about webpack and react that I can use help with (around code obfuscation/uglification).

I am using create-react-app for my application and it appears to create a bundled build for production (after running yarn build).

And in that file it seems that everything is put into a main.JS file and main.CSS file Etc. I push this live using "firebase deploy" (in my case). I would like my code to be uglified and not be completely readable by any developer out there.

But when I go to look at my apps in Chrome it doesn't show main.JS or any other of the bundles files. It just shows every single individual file and exactly the code that I've written. Any idea why this is? Why doesn't it show the uglified combined main.js file under the 'sources' tab in chrome? Is this to do with the source map?

答:
Try this:

```<code>{
  …
  "scripts": {
    "build": "set GENERATE_SOURCEMAP=false && react-scripts build"
  }
}
</code>```

it worked for me and didn't show the .map file anymore in production, but it still shows  every single individual file and exactly the code that we've written, plus the node_modules folder.

maybe it's a firebase thing, cause we are using the free version of firebase or other free deployment services like Now, surge, netlify, or whatever? I am not sure either.

Body:
Try this:

{
  …
  "scripts": {
    "build": "set GENERATE_SOURCEMAP=false && react-scripts build"
  }
}

it worked for me and didn't show the .map file anymore in production, but it still shows  every single individual file and exactly the code that we've written, plus the node_modules folder.

maybe it's a firebase thing, cause we are using the free version of firebase or other free deployment services like Now, surge, netlify, or whatever? I am not sure either.


问:
Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery
I am having trouble with the onmouseout function in an absolute positoned div. When the mouse hits a child element in the div, the mouseout event fires, but I do not want it to fire until the mouse is out of the parent, absolute div.

How can I prevent the mouseout event from firing when it hits a child element WITHOUT jquery.

I know this has something to do with event bubbling, but I am having no luck on finding out how to work this out.

I found a similar post  here: How to disable mouseout events triggered by child elements?

However that solution uses jQuery.

答:
instead of onmouseout use onmouseleave.

You haven't showed to us your specific code so I cannot show you on your specific example how to do it.

But it is very simple: just replace onmouseout with onmouseleave.

That's all :) So, simple :)

If not sure how to do it, see explanation on:

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove_leave_out

Peace of cake :) Enjoy it :)


问:
Big data analysis in web applications
Let's say I have very large time series data. I store that very big data for example in a storage like Google BigTable. I can query and get the data very fast out of the storage. So I can handle the storage problem. Up to here the process is very efficient.

Now I have a web application. I want to analyze a big time series stored in BigTable and visualize the result. I want to do a statistical evaluation of that time series with over a million points in there. So I have a solution to store the time series, I can get the right time series out of the storage, but I don't know how to handle the time series when I get them out oif the storage.

Which server side tools do I have to use to handle the big data? Which methods are there to do that? Parallelization in backend and an aggregated visualization at the web front end? It is useless to be efficient in storing the data, when I can't use the big data in a same effective way.

答: For analysis and visualization of time series data, there is a pretty good solution called 'Metatron Discovery'. It provides most of the answers to the problems you are having. Check it out!</p>

Title: Big data analysis in web applications


问:
I don't know what the problem is getting items using WISQL from Azure Devops
I tired with the code below but somehow I don't get any data returned.
When I debug it with Power shell SE, I don't think I can see if the personal token is accessible or not.
What am I doing wrong?</p>

```<code>$url="https://dev.azure.com/MYproject"
$personalAccessToken="fdsafasdfdsafasd"
$project = "TEST"

GetWorkItems

function GetWorkItems
{
    # using env vars passed from VSTS build
    $collectionuri = $Env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI
    $token = $Env:SYSTEM_ACCESSTOKEN # need to configure build to allow passing OAuth tokens

    $basicAuth = "{0}:{1}" -f "", $personalAccessToken
    $basicAuth = [System.Text.Encoding]::UTF8.GetBytes($basicAuth)
    $basicAuth = [System.Convert]::ToBase64String($basicAuth)
    $headers = @{Authorization=("Basic {0}"-f $basicAuth)}

    $WorkItemType = 'Recently updated'

    $url = $collectionuri + 'DefaultCollection/_apis/wit/wiql?api-version=5.0'

    $WIQL_query = "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.IterationPath] Under 'Sprint number two' AND [State] = 'Active' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc"
    $body = @{ query = $WIQL_query }
    $bodyJson=@($body) | ConvertTo-Json

    $response = Invoke-RestMethod -Uri $url -headers $headers -Method Post -ContentType "application/json" -Body $bodyJson

    $workitems = $response.workItems

    Write-Host "Found" $workitems.Count "work items of type:" $WorkItemType
}

</code>```

答:
Please try to define the parameters and modify the <code>$url</code> as the follows and try again: </p>

```<code>Param(

   [string]$collectionurl = "https://dev.azure.com/MYproject",

   [string]$project = "TEST",

   [string]$personalAccessToken="fdsafasdfdsafasd"

)

 $url = "$collectionuri/$project/{team}/_apis/wit/wiql?api-version=5.0"
</code>```

Body:
I tired with the code below but somehow I don't get any data returned.
When I debug it with Power shell SE, I don't think I can see if the personal token is accessible or not.
What am I doing wrong?

$url="https://dev.azure.com/MYproject"
$personalAccessToken="fdsafasdfdsafasd"
$project = "TEST"

GetWorkItems

function GetWorkItems
{
    # using env vars passed from VSTS build
    $collectionuri = $Env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI
    $token = $Env:SYSTEM_ACCESSTOKEN # need to configure build to allow passing OAuth tokens

    $basicAuth = "{0}:{1}" -f "", $personalAccessToken
    $basicAuth = [System.Text.Encoding]::UTF8.GetBytes($basicAuth)
    $basicAuth = [System.Convert]::ToBase64String($basicAuth)
    $headers = @{Authorization=("Basic {0}"-f $basicAuth)}

    $WorkItemType = 'Recently updated'

    $url = $collectionuri + 'DefaultCollection/_apis/wit/wiql?api-version=5.0'

    $WIQL_query = "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.IterationPath] Under 'Sprint number two' AND [State] = 'Active' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc"
    $body = @{ query = $WIQL_query }
    $bodyJson=@($body) | ConvertTo-Json

    $response = Invoke-RestMethod -Uri $url -headers $headers -Method Post -ContentType "application/json" -Body $bodyJson

    $workitems = $response.workItems

    Write-Host "Found" $workitems.Count "work items of type:" $WorkItemType
}

Body:
Please try to define the parameters and modify the $url as the follows and try again:

Param(

   [string]$collectionurl = "https://dev.azure.com/MYproject",

   [string]$project = "TEST",

   [string]$personalAccessToken="fdsafasdfdsafasd"

)

 $url = "$collectionuri/$project/{team}/_apis/wit/wiql?api-version=5.0"


问:
Can Webpack build Vue template with coffee-loader?
When i try to run command npm run dev, but crush on npm run build
I think that i need a pass param to uglifyjs or to vue-loader

Set Babel preset to es2015 does not resolve problem

```<code>ERROR in build.js from UglifyJs
Unexpected token: operator (>) [./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/coffee/forms/table_class_selection.vue:28,44][build.js:19990,120]
</code>```

We use config such us

```<code>module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.coffee$/,
        use: {
          loader: 'coffee-loader',
          options: {
            transpile: {
              presets: ['env']
            }
          }
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            'scss': [
              'vue-style-loader',
              'css-loader',
              'sass-loader'
            ],
            'sass': [
              'vue-style-loader',
              'css-loader',
              'sass-loader?indentedSyntax'
            ]
          }
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
      ...
    ]
  }
  ...

}
</code>```

Vue file code is

```<code><template>
...
</template>
<script lang="coffee">
   ...
</script>
</code>```

答:
Resolution is install npm dependencies

```<code>npm i babel-plugin-syntax-jsx babel-plugin-transform-vue-jsx\
  babel-helper-vue-jsx-merge-props -D
</code>```

And add to .babelrc following lines

```<code>{
  "presets": [
    ["env", { "modules": false }],
    "stage-3"
  ],
  "plugins": ["transform-vue-jsx"]
}
</code>```

Body:
When i try to run command npm run dev, but crush on npm run build
I think that i need a pass param to uglifyjs or to vue-loader

Set Babel preset to es2015 does not resolve problem

ERROR in build.js from UglifyJs
Unexpected token: operator (>) [./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/coffee/forms/table_class_selection.vue:28,44][build.js:19990,120]

We use config such us

module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.coffee$/,
        use: {
          loader: 'coffee-loader',
          options: {
            transpile: {
              presets: ['env']
            }
          }
        }
      },
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            'scss': [
              'vue-style-loader',
              'css-loader',
              'sass-loader'
            ],
            'sass': [
              'vue-style-loader',
              'css-loader',
              'sass-loader?indentedSyntax'
            ]
          }
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      }
      ...
    ]
  }
  ...

}

Vue file code is

<template>
...
</template>

Body:
Resolution is install npm dependencies

npm i babel-plugin-syntax-jsx babel-plugin-transform-vue-jsx\
  babel-helper-vue-jsx-merge-props -D

And add to .babelrc following lines

{
  "presets": [
    ["env", { "modules": false }],
    "stage-3"
  ],
  "plugins": ["transform-vue-jsx"]
}


问:
What is the service "DEVICES" in azure services?
I am getting charged for an additional service, namely: DEVICES. I haven`t deployed anything under it on azure portal still getting charged for it along with other services.

```<code>"per_service_bill" : {
        "Compute" : 1127.4031374062,
        "DEVICES" : 1230.28225806452,
        "Network" : 2208.84024295638,
    },
</code>```

Why am I being charged for this and what is it exactly for?

答: Devices refers to the number of hardware devices that is being connected to the azure service that you are using such as IOTHub, EventHub, TimeSeriesInsights etc

Body:
I am getting charged for an additional service, namely: DEVICES. I haven`t deployed anything under it on azure portal still getting charged for it along with other services.

"per_service_bill" : {
        "Compute" : 1127.4031374062,
        "DEVICES" : 1230.28225806452,
        "Network" : 2208.84024295638,
    },

Why am I being charged for this and what is it exactly for?


问:
How to show category subcategory based on array
I have an array that consists of some data to show the category and subcategories.

```<code>{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}
</code>```

I want to sort and show this data something like this :

```<code>> Movie
>> Action
>>>James Bond Series

>Book
>>J.K Rowling
>>>Harry Potter Series
</code>```

答:
Get first a tree and then a flat representation.

function getTree(array, root) {
    var o = {};
    array.forEach(payload => {
        Object.assign(o[payload.id] = o[payload.id] || {}, { payload });
        o[payload.parent_id] = o[payload.parent_id] || {};
        o[payload.parent_id].children = o[payload.parent_id].children || [];
        o[payload.parent_id].children.push(o[payload.id]);
    });
    return o[root].children;
}

function getFlat(array = []) {
    return array.reduce((r, { payload, children }) =>
        r.concat(payload, getFlat(children)), []);
}

var data = [{ id: "5", parent_id: "0", lable: "Movie" }, { id: "20", parent_id: "5", lable: "Action" }, { id: "15", parent_id: "43", lable: "J.K Rowling" }, { id: "43", parent_id: "0", lable: "Book" }, { id: "2", parent_id: "20", lable: "James Bond Series" }, { id: "3", parent_id: "0", lable: "Music" }, { id: "39", parent_id: "15", lable: "Harry Potter Series" }],
    result = getFlat(getTree(data, '0'));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array that consists of some data to show the category and subcategories.

{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}

I want to sort and show this data something like this :

> Movie
>> Action
>>>James Bond Series

>Book
>>J.K Rowling
>>>Harry Potter Series

Body:
Get first a tree and then a flat representation.

function getTree(array, root) {
    var o = {};
    array.forEach(payload => {
        Object.assign(o[payload.id] = o[payload.id] || {}, { payload });
        o[payload.parent_id] = o[payload.parent_id] || {};
        o[payload.parent_id].children = o[payload.parent_id].children || [];
        o[payload.parent_id].children.push(o[payload.id]);
    });
    return o[root].children;
}

function getFlat(array = []) {
    return array.reduce((r, { payload, children }) =>
        r.concat(payload, getFlat(children)), []);
}

var data = [{ id: "5", parent_id: "0", lable: "Movie" }, { id: "20", parent_id: "5", lable: "Action" }, { id: "15", parent_id: "43", lable: "J.K Rowling" }, { id: "43", parent_id: "0", lable: "Book" }, { id: "2", parent_id: "20", lable: "James Bond Series" }, { id: "3", parent_id: "0", lable: "Music" }, { id: "39", parent_id: "15", lable: "Harry Potter Series" }],
    result = getFlat(getTree(data, '0'));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Abstract method, which may be empty
I have an abstract class, which contains an abstract method, which is only required sometimes. A bit simply put, the reason for this is that the class executes some code, which only sometimes results in output (which then needs to be handled). So the implementations of the abstract class, which does get output, needs to implement this method, whereas the implementations with no output actually could do without. The abstract class looks something like this:

```<code>abstract class AbstractWorker
{
    public virtual Execute()
    {
        OutputModel output = await PerformActions();
        await HandleOutput(output);
    }

    protected abstract Task<OutputModel> PerformActions();
    protected abstract Task HandleOutput(OutputModel);
}
</code>```

I cannot implement the the methods PerformActions() and HandleOutput() as they are very individual to the specific implementation of AbstractWorker. And, as I said, there is not always an output to handle, but I need to force the method, in case it does have output. So the implementation wood look something like this:

```<code>public class ConcreteWorker : AbstractWorker
{
    protected override async Task<OutputModel> PerformActions()
    {
        // ...do stuff here, which produces no output
        return null;
    }

    protected override async Task HandleOutput(OutputModel output)
    {
        // Do nothing, since there is no output
        return;
    }
}
</code>```

While the above does work, it seems somewhat silly. But it is required, for the cases where output is generated. Is there some sort of smarter way to do it?

答:
The object oriented way to solve this is to add another abstraction layer.

Have the AbstractWorker class implement an interface (IAbstractWorker) that has only the Execute() method. (well, since it's an async method let's have it return a Task and call it ExecuteAsync to follow best practice)

Have workers that doesn't need to handle the output implement that interface directly,

and workers that need to handle the output use the current abstract class.

Basically something like this:

```<code>interface IAbstractWorker
{
    Task ExecuteAsync();
}

abstract class AbstractSepcializedWorker : IAbstractWorker
{
    public async Task ExecuteAsync()
    {
        OutputModel output = await PerformActions();
        await HandleOutput(output);
    }

    protected abstract Task<OutputModel> PerformActionsAsync();
    protected abstract Task HandleOutputAsync(OutputModel);
}

class Worker : IAbstractWorker
{
    public async Task ExecuteAsync()
    {
        // implementation
    }
}

class SepcializedWorker : AbstractSepcializedWorker
{

    protected override Task<OutputModel> PerformActionsAsync()
    {
        // implementation
    }
    protected override Task HandleOutputAsync(OutputModel)
    {
        // implementation
    }
}
</code>```

Then you have all your worker classes implement the IAbstractWorker interface, and you can easily create new concrete worker classes that either implement the interface directly or inherit the abstract class (and therefor implement it via inheritance).

Title: Abstract method, which may be empty

Body:
I have an abstract class, which contains an abstract method, which is only required sometimes. A bit simply put, the reason for this is that the class executes some code, which only sometimes results in output (which then needs to be handled). So the implementations of the abstract class, which does get output, needs to implement this method, whereas the implementations with no output actually could do without. The abstract class looks something like this:

abstract class AbstractWorker
{
    public virtual Execute()
    {
        OutputModel output = await PerformActions();
        await HandleOutput(output);
    }

    protected abstract Task<OutputModel> PerformActions();
    protected abstract Task HandleOutput(OutputModel);
}

I cannot implement the the methods PerformActions() and HandleOutput() as they are very individual to the specific implementation of AbstractWorker. And, as I said, there is not always an output to handle, but I need to force the method, in case it does have output. So the implementation wood look something like this:

public class ConcreteWorker : AbstractWorker
{
    protected override async Task<OutputModel> PerformActions()
    {
        // ...do stuff here, which produces no output
        return null;
    }

    protected override async Task HandleOutput(OutputModel output)
    {
        // Do nothing, since there is no output
        return;
    }
}

While the above does work, it seems somewhat silly. But it is required, for the cases where output is generated. Is there some sort of smarter way to do it?

Body:
The object oriented way to solve this is to add another abstraction layer.

Have the AbstractWorker class implement an interface (IAbstractWorker) that has only the Execute() method. (well, since it's an async method let's have it return a Task and call it ExecuteAsync to follow best practice)

Have workers that doesn't need to handle the output implement that interface directly,

and workers that need to handle the output use the current abstract class.

Basically something like this:

interface IAbstractWorker
{
    Task ExecuteAsync();
}

abstract class AbstractSepcializedWorker : IAbstractWorker
{
    public async Task ExecuteAsync()
    {
        OutputModel output = await PerformActions();
        await HandleOutput(output);
    }

    protected abstract Task<OutputModel> PerformActionsAsync();
    protected abstract Task HandleOutputAsync(OutputModel);
}

class Worker : IAbstractWorker
{
    public async Task ExecuteAsync()
    {
        // implementation
    }
}

class SepcializedWorker : AbstractSepcializedWorker
{

    protected override Task<OutputModel> PerformActionsAsync()
    {
        // implementation
    }
    protected override Task HandleOutputAsync(OutputModel)
    {
        // implementation
    }
}

Then you have all your worker classes implement the IAbstractWorker interface, and you can easily create new concrete worker classes that either implement the interface directly or inherit the abstract class (and therefor implement it via inheritance).


答: "DEVICES" I believe is related to Azure IoT Hub.

Title: What is the service "DEVICES" in azure services?


问:
How to select a selectbox an option value with JS?
This may sound easy but I'm been having a heck of a time to get this to work. Somebody please help. My select box is like below. How do i select the value 3 from the list?

```<code>        if(!empty($listeDoc))
        {
            $iGroups = 0;
            while($iGroups < count($listeDoc))
            {
            ?>
            <tr>
                <td>
                    <input type="checkbox" name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['product_id']" id="productSelectCreation_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" onchange="setValueToOne(this)"  ><?php echo $listeDoc[$iGroups]->DOC_CLIENT_NOM; ?>
                </td>

                <td>
                    <select name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['quantity']" id="productQty_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" class="form-control1" value="<?php echo $qty; ?>" style="width:100%; height:25px; border : #62270c solid 1px;" tabindex="1">
                        <option value=""/></option>
                        <option value="1"<?php if ($qty == 1) echo 'selected="selected"'; ?>>1</option>
                        <option value="2"<?php if ($qty == 2) echo 'selected="selected"'; ?>>2</option>
                        <option value="3"<?php if ($qty == 3) echo 'selected="selected"'; ?>>3</option>
                        <option value="4"<?php if ($qty == 4) echo 'selected="selected"'; ?>>4</option>
                        <option value="5"<?php if ($qty == 5) echo 'selected="selected"'; ?>>5</option>
                    </select>
                <td>
            </tr>

            <?php
            $iGroups++;
            }
        }
</code>```

here's is what i tried:

function setValueToOne(value)
{
    checkbox = document.getElementById('productSelectCreation');

```<code>if (checkbox.checked == true)
{
    document.getElementById("productQtyCreation").value = 1;
}
else
    document.getElementById("productQtyCreation").value = '0';
</code>```

}

答:
function setValueToOne(checkbox) {
    if(checkbox.checked) {
        document.getElementById('productQtyCreation').value = 3
    }else{
        document.getElementById('productQtyCreation').value = 0
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="productQtyCreation">
    <option disabled selected value=""></option>
    <option value="0">Zero</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
<input type="checkbox" name="productSelect" id="productSelectCreation" onClick="setValueToOne(this)" value="3" /></code>```

Body:
This may sound easy but I'm been having a heck of a time to get this to work. Somebody please help. My select box is like below. How do i select the value 3 from the list?

        if(!empty($listeDoc))
        {
            $iGroups = 0;
            while($iGroups < count($listeDoc))
            {
            ?>

                    <input type="checkbox" name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['product_id']" id="productSelectCreation_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" onchange="setValueToOne(this)"  ><?php echo $listeDoc[$iGroups]->DOC_CLIENT_NOM; ?>

                    <select name="productSelect[<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>]['quantity']" id="productQty_<?php echo $listeDoc[$iGroups]->DOC_CLIENT_ID ?>" class="form-control1" value="<?php echo $qty; ?>" style="width:100%; height:25px; border : #62270c solid 1px;" tabindex="1">
                        <option value=""/></option>
                        <option value="1"<?php if ($qty == 1) echo 'selected="selected"'; ?>>1</option>
                        <option value="2"<?php if ($qty == 2) echo 'selected="selected"'; ?>>2</option>
                        <option value="3"<?php if ($qty == 3) echo 'selected="selected"'; ?>>3</option>
                        <option value="4"<?php if ($qty == 4) echo 'selected="selected"'; ?>>4</option>
                        <option value="5"<?php if ($qty == 5) echo 'selected="selected"'; ?>>5</option>
                    </select>

            <?php
            $iGroups++;
            }
        }

here's is what i tried:

function setValueToOne(value)
{
    checkbox = document.getElementById('productSelectCreation');

if (checkbox.checked == true)
{
    document.getElementById("productQtyCreation").value = 1;
}
else
    document.getElementById("productQtyCreation").value = '0';

}

Body:
function setValueToOne(checkbox) {
    if(checkbox.checked) {
        document.getElementById('productQtyCreation').value = 3
    }else{
        document.getElementById('productQtyCreation').value = 0
    }
}

<select id="productQtyCreation">
    <option disabled selected value=""></option>
    <option value="0">Zero</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
<input type="checkbox" name="productSelect" id="productSelectCreation" onClick="setValueToOne(this)" value="3" />


问:
Mongodb get documents between dates(Stored as string in the format "20-05-2019")
This is the sample document that I have:

```<code>{
  "timestamp" : "1558341279777",
  "date" : "20-05-2019",
  "hour" : "14",
  "month" : "5",
  "time" : "14:4:39",
  "weekDay" : "Monday"
}
</code>```

I want to query documents between given dates. Say between "26-05-2019" and "01-06-2019".

The following is the query that I tried:

```<code>db.getCollection('messagelogs').find({'date': {'$gte': '20-05-2019', '$lt': '31-05-2019'}})
</code>```

The problem with the above query is that it does string comparison, which doesnt always return the correct result when we query for dates. Is there a clean way to do this?

Body:
This is the sample document that I have:

{
  "timestamp" : "1558341279777",
  "date" : "20-05-2019",
  "hour" : "14",
  "month" : "5",
  "time" : "14:4:39",
  "weekDay" : "Monday"
}

I want to query documents between given dates. Say between "26-05-2019" and "01-06-2019".

The following is the query that I tried:

db.getCollection('messagelogs').find({'date': {'$gte': '20-05-2019', '$lt': '31-05-2019'}})

The problem with the above query is that it does string comparison, which doesnt always return the correct result when we query for dates. Is there a clean way to do this?

Body:
Please try below:

    db.collection.find({
      "$expr": {
        "$and": [
      {
        "$gte": [
          { "$dateFromString": { "dateString": "$date, "format": "%m-%d-%Y" }},
          ISODate("2019-05-26T00:00:00Z")
        ]
      },
      {
        "$lte": [
          { "$dateFromString": { "dateString": "$date", "format": "%m-%d-%Y" }},
          ISODate("2019-06-15T23:59:59Z")
        ]
      }
    ]
     }
    })


问:
How to log response body in gin
I need to log the response body in a middleware of gin, but I don't find how to get the response body. Can anyone help?

I am using a middleware like this:

```<code>func Logger() gin.HandlerFunc {

    return func(c *gin.Context) {

        c.Next()

        statusCode := c.Writer.Status()
        if statusCode >= 400 {
            //ok this is an request with error, let's make a record for it
            //log body here
        }
    }
}
</code>```

My question is, how to get response body from Context in middleware?

答:
FYI

Note: implement WriteString() if using c.String() for writing response body

type bodyLogWriter struct {
    gin.ResponseWriter
    body *bytes.Buffer
}

func (w bodyLogWriter) Write(b []byte) (int, error) {
    w.body.Write(b)
    return w.ResponseWriter.Write(b)
}

func (w bodyLogWriter) WriteString(s string) (int, error) {
    w.body.WriteString(s)
    return w.ResponseWriter.WriteString(s)
}

func ginBodyLogMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
        c.Writer = blw
        c.Next()

        fmt.Println("Response body: " + blw.body.String())
    }
}

...

// register
router := r.Group("/", ginBodyLogMiddleware())
```

Title: How to log response body in gin

Body:
I need to log the response body in a middleware of gin, but I don't find how to get the response body. Can anyone help?

I am using a middleware like this:

func Logger() gin.HandlerFunc {

    return func(c *gin.Context) {

        c.Next()

        statusCode := c.Writer.Status()
        if statusCode >= 400 {
            //ok this is an request with error, let's make a record for it
            //log body here
        }
    }
}

My question is, how to get response body from Context in middleware?


问:
I am trying to populate database with the image, image-name, image-number and image-price but only image column is filled
I am using angular as front-end and .NET Web API as backend and SQL Server 2012. I am trying to populate my database with image, image-name, number, and price but only the image is being populated.

Angular

image.component.ts

```<code>imageUrl:String="";
 fileToUpload:File=null;

 handleImageChange(file: FileList){
   this.fileToUpload = file.item(0);
   var reader = new FileReader();
   reader.onload=(event:any)=>{
     this.imageUrl=event.target.result;
   }
   reader.readAsDataURL(this.fileToUpload);
 }
uploadImage(imageData){
    console.log(0)
    let name=imageData.name;
    let number=imageData.number;
    let price=imageData.price;
    this.service.uploadImage(this.fileToUpload, name, number, price).subscribe(
      data=>{
        alert("successfully uploaded");
        this.productForm.reset();
        this.imageUrl="";
      }
    );
  }
</code>```

image.service.ts

```<code> baseUrl:string="http://localhost:62215/api/product/";

  uploadImage(fileToUpload:File, imagename:string, num:string, price:string){

    let formData:FormData = new FormData();
    formData.append("file",fileToUpload,fileToUpload.name);
    formData.append("Imagename",name);
    formData.append("Number",num);
    formData.append("Price",price);

    return this.http.post(this.baseUrl+"UploadImage",formData,this.httpOptions);
  }
</code>```

.NET Web API

ProductController.cs

```<code>[HttpPost]
[Route("UploadImage")]
public IHttpActionResult UploadImage()
{
    HttpRequest Request = HttpContext.Current.Request;

    try
    {
        if (Request.Files.Count > 0)
        {
            using (FreeShareEntities obj = new FreeShareEntities())
            {
                foreach (string file in Request.Files)
                {
                    var postedFile = Request.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
                    postedFile.SaveAs(filePath);

                    ImageDemo image = new ImageDemo();
                    image.Name = Request["name"];
                    image.Image = postedFile.FileName;
                    image.Number = Request["num"];
                    image.Price = Request["price"];

                    obj.ImageDemoes.Add(image);
                    obj.SaveChanges();
                }
            }

            return Ok(true);
        }
    }
    catch (DbEntityValidationException dbEx)
    {
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
            }
        }
    }

    return NotFound();
}
</code>```

What I am expecting is to populate all fields of my database table but not only one field.

答:
The key that you are getting from the Request is different from the Form Data key that you are sending.

```<code>formData.append("Imagename",name)
image.Name = Request["name"];
</code>```

It should be

```<code>image.Name = Request["Imagename"];
</code>```

Same with other mismatches.

If it still doesn't work, I would suggest an alternative. You're sending your data using form data might as well utilize the FromForm attribute.

Ex.

```<code>public IHttpActionResult UploadImage([FromForm]UploadDto dto)
{
    var postedFile = dto.File;
    var filePath =
    HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
    postedFile.SaveAs(filePath);

    ImageDemo image = new ImageDemo();
    image.Name = dto.Name;
    image.Image = postedFile.FileName;
    image.Number = dto.Number;
    image.Price = dto.Price;

    obj.ImageDemoes.Add(image);
    obj.SaveChanges();
}

public class UploadDto
{
    public string Name { get; set; }
    public int Number{ get; set; }
    public int Price{ get; set; }
    public IFormFile File{ get; set; }
}
</code>```

I've been using this approach for a while now and it works great. Remember that the key you are appending on the formdata should be the same with your model properties.

I hope this helps.

Body:
I am using angular as front-end and .NET Web API as backend and SQL Server 2012. I am trying to populate my database with image, image-name, number, and price but only the image is being populated.

Angular

image.component.ts

imageUrl:String="";
 fileToUpload:File=null;

 handleImageChange(file: FileList){
   this.fileToUpload = file.item(0);
   var reader = new FileReader();
   reader.onload=(event:any)=>{
     this.imageUrl=event.target.result;
   }
   reader.readAsDataURL(this.fileToUpload);
 }
uploadImage(imageData){
    console.log(0)
    let name=imageData.name;
    let number=imageData.number;
    let price=imageData.price;
    this.service.uploadImage(this.fileToUpload, name, number, price).subscribe(
      data=>{
        alert("successfully uploaded");
        this.productForm.reset();
        this.imageUrl="";
      }
    );
  }

image.service.ts

 baseUrl:string="http://localhost:62215/api/product/";

  uploadImage(fileToUpload:File, imagename:string, num:string, price:string){

    let formData:FormData = new FormData();
    formData.append("file",fileToUpload,fileToUpload.name);
    formData.append("Imagename",name);
    formData.append("Number",num);
    formData.append("Price",price);

    return this.http.post(this.baseUrl+"UploadImage",formData,this.httpOptions);
  }

.NET Web API

ProductController.cs

[HttpPost]
[Route("UploadImage")]
public IHttpActionResult UploadImage()
{
    HttpRequest Request = HttpContext.Current.Request;

    try
    {
        if (Request.Files.Count > 0)
        {
            using (FreeShareEntities obj = new FreeShareEntities())
            {
                foreach (string file in Request.Files)
                {
                    var postedFile = Request.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
                    postedFile.SaveAs(filePath);

                    ImageDemo image = new ImageDemo();
                    image.Name = Request["name"];
                    image.Image = postedFile.FileName;
                    image.Number = Request["num"];
                    image.Price = Request["price"];

                    obj.ImageDemoes.Add(image);
                    obj.SaveChanges();
                }
            }

            return Ok(true);
        }
    }
    catch (DbEntityValidationException dbEx)
    {
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
            }
        }
    }

    return NotFound();
}

What I am expecting is to populate all fields of my database table but not only one field.

Body:
The key that you are getting from the Request is different from the Form Data key that you are sending.

formData.append("Imagename",name)
image.Name = Request["name"];

It should be

image.Name = Request["Imagename"];

Same with other mismatches.

If it still doesn't work, I would suggest an alternative. You're sending your data using form data might as well utilize the FromForm attribute.

Ex.

public IHttpActionResult UploadImage([FromForm]UploadDto dto)
{
    var postedFile = dto.File;
    var filePath =
    HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
    postedFile.SaveAs(filePath);

    ImageDemo image = new ImageDemo();
    image.Name = dto.Name;
    image.Image = postedFile.FileName;
    image.Number = dto.Number;
    image.Price = dto.Price;

    obj.ImageDemoes.Add(image);
    obj.SaveChanges();
}

public class UploadDto
{
    public string Name { get; set; }
    public int Number{ get; set; }
    public int Price{ get; set; }
    public IFormFile File{ get; set; }
}

I've been using this approach for a while now and it works great. Remember that the key you are appending on the formdata should be the same with your model properties.

I hope this helps.


问:
Doop: Gradle build failed with an exception. Could not resolve dependencies
I am trying to setup doop. After running the command ./doop, I get the following error:

What went wrong:
Error resolving plugin [id: 'net.researchgate.release', version: '2.6.0']

Could not resolve all dependencies for configuration 'detachedConfiguration1'.
  Could not determine artifacts for net.researchgate.release:net.researchgate.release.gradle.plugin:2.6.0
  Could not get resource 'https://plugins.gradle.org/m2/net/researchgate/release/net.researchgate.release.gradle.plugin/2.6.0/net.researchgate.release.gradle.plugin-2.6.0.jar'.
  Could not HEAD 'https://plugins.gradle.org/m2/net/researchgate/release/net.researchgate.release.gradle.plugin/2.6.0/net.researchgate.release.gradle.plugin-2.6.0.jar'.
  Remote host closed connection during handshake

Can anyone help me understand and resolve the error better?

答:
So apparently it was java version issue.
It worked fine with java 1.8. I was using java 1.7</p>


问:
Allocating an Elastic IP address to an existing / running Amazon EC2 instance
Are we able to allocate an Elastic IP address to an existing / running Amazon EC2 instance?

In most cases, we assign the Elastic IP address before configuring the server. However, we are trying to assign the Elastic IP address onto a fully configured server and create an AMI for different instances.

If we associate the new EIP onto an existing instance (created by AMI) will run the same config as the existing one?

答:
Elastic IPs can be allocated and associated to an EC2 instance at any time, while launching or after the launch.

An Elastic IP address is not actually the property of your instance, rather it's a property associated with your server's network card (Elastic Network Interface).

See: Elastic IP Addresses - Amazon Virtual Private Cloud


问:
Spring Cloud Gateway is not finding a route path (404 error)
I am investigating Spring Cloud Gateway as an API gateway solution for a professional application and am running through this tutorial: http://spring.io/guides/gs/gateway/#scratch.

However I am running into issues I cannot solve.

Here is my POM

```<code><groupId>org.springframework</groupId>
<artifactId>gs-gateway</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
</parent>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.RC2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>spring-boot-starter-web</artifactId>
                <groupId>org.springframework.boot</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

and here is the Application.java

```<code>@SpringBootApplication
@RestController
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route(p -> p
            .path("/get")
            .filters(f -> f.addRequestHeader("Hello", "World"))
            .uri("http://httpbin.org:80"))
        .build();
}
}
</code>```

Running this and trying to hit http://localhost:8080/get was giving me a gateway timeout.  Consulting with someone at work I discovered that I am behind a firewall and needed a proxy.  So I modified the Application.java to this:

```<code>@SpringBootApplication
@RestController
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route(p -> p.host("internet.proxy.*****.com").and()
            .path("/get")
            .filters(f -> f.addRequestHeader("Hello", "World"))
            .uri("http://httpbin.org:80"))
        .build();
}
</code>```

Now, I am no longer getting a gateway time out but now I am getting a 404 error.  Here is the output using curl http://localhost:8080/get:

```<code>{"timestamp":"2019-01-
    16T14:24:12.929+0000","path":"/get","status":404,"error":"Not
Found","message":null}
</code>```

I am probably missing something simple but I cannot see it.

EDIT:
according to the tutorial listed above this should be the response I get back:

```<code>{
    "args": {},
    "headers": {
        "Accept": "*/*",
        "Connection": "close",
        "Forwarded":
         "proto=http;host=\"localhost:8080\";for=\"0:0:0:0:0:0:0:1:56207\"",
        "Hello": "World",
        "Host": "httpbin.org",
        "User-Agent": "curl/7.54.0",
        "X-Forwarded-Host": "localhost:8080"
  },
  "origin": "0:0:0:0:0:0:0:1, 73.68.251.70",
  "url": "http://localhost:8080/get"
}
</code>```

答: remove @RestController in your code

Body:
I am investigating Spring Cloud Gateway as an API gateway solution for a professional application and am running through this tutorial: http://spring.io/guides/gs/gateway/#scratch.

However I am running into issues I cannot solve.

Here is my POM

<groupId>org.springframework</groupId>
<artifactId>gs-gateway</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.2.RELEASE</version>
</parent>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.RC2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>spring-boot-starter-web</artifactId>
                <groupId>org.springframework.boot</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

and here is the Application.java

@SpringBootApplication
@RestController
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route(p -> p
            .path("/get")
            .filters(f -> f.addRequestHeader("Hello", "World"))
            .uri("http://httpbin.org:80"))
        .build();
}
}

Running this and trying to hit http://localhost:8080/get was giving me a gateway timeout.  Consulting with someone at work I discovered that I am behind a firewall and needed a proxy.  So I modified the Application.java to this:

@SpringBootApplication
@RestController
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route(p -> p.host("internet.proxy.*****.com").and()
            .path("/get")
            .filters(f -> f.addRequestHeader("Hello", "World"))
            .uri("http://httpbin.org:80"))
        .build();
}

Now, I am no longer getting a gateway time out but now I am getting a 404 error.  Here is the output using curl http://localhost:8080/get:

{"timestamp":"2019-01-
    16T14:24:12.929+0000","path":"/get","status":404,"error":"Not
Found","message":null}

I am probably missing something simple but I cannot see it.

EDIT:
according to the tutorial listed above this should be the response I get back:

{
    "args": {},
    "headers": {
        "Accept": "*/*",
        "Connection": "close",
        "Forwarded":
         "proto=http;host=\"localhost:8080\";for=\"0:0:0:0:0:0:0:1:56207\"",
        "Hello": "World",
        "Host": "httpbin.org",
        "User-Agent": "curl/7.54.0",
        "X-Forwarded-Host": "localhost:8080"
  },
  "origin": "0:0:0:0:0:0:0:1, 73.68.251.70",
  "url": "http://localhost:8080/get"
}

Body: remove @RestController in your code


问:
US Counties map in Highmaps for Angular throws compilation error
I'm trying to deploy US Counties map in Highmaps using the highcharts-chart directive. This works fine with the US States map, but have a problem defining the data element for US Counties as I get a compilation error.

This is the attempt:

HTML

```<code>    <highcharts-chart
        [Highcharts]="Highcharts"
        [constructorType]="'mapChart'"
        [options]="chartMap"
        [(update)]="updateFlag"
        [oneToOne]="true"
        style="width: 500px; height: 400px; display: block;"
    ></highcharts-chart>
</code>```

Typescript

```<code>import * as Highcharts from 'highcharts';
import MapModule from 'highcharts/modules/map';
const mapX = require('@highcharts/map-collection/countries/us/us-all-all.geo.json')
MapModule(Highcharts);

.....
.....
this.chartMap = {
                chart: {
                    map: mapX
                },
                title: {
                    text: 'THIS IS THE US COUNTIES MAP'
                },
                series: [{ // <-- error is thrown here
                    name: 'Unemployment',
                    borderWidth: 0.5,
                    states: {
                        hover: {
                        color: 'red'
                        }
                    },
                    joinBy: ['hc-key', 'code'],
                    data:  [
                        {
                            "code": "us-al-001",
                            "name": "Autauga County, AL",
                            "value": 3.9
                        },
                        {
                            "code": "us-al-003",
                            "name": "Baldwin County, AL",
                            "value": 4.3
                        }
                    ]
                    }]
            };
</code>```

I get the following compilation error:

Type '{ name: string; borderWidth: number; states: { hover: { color:
  string; }; }; joinBy: string[]; data: { "code": string; "name":
  string; "value": number; }[]; }' is not assignable to type
  'SeriesAbandsOptions | SeriesAdOptions | SeriesAoOptions |
  SeriesApoOptions | SeriesAreaOptions | SeriesArearangeOptions |
  SeriesAreasplineOptions | SeriesAreasplinerangeOptions | ... 82 more
  ... | SeriesZigzagOptions'.   Property 'type' is missing in type '{
  name: string; borderWidth: number; states: { hover: { color: string;
  }; }; joinBy: string[]; data: { "code": string; "name": string;
  "value": number; }[]; }' but required in type
  'SeriesXrangeOptions'.ts(2322) highcharts.d.ts(335083, 5): 'type' is
  declared here.

I took the data example from here and the map example from here.

What is this error and how to fix it?

答:
This error occurs because you haven't set the series type which is required for each series when using TypeScript.

```<code>series: [{
  name: 'Unemployment',
  type: 'map', // type is required for each series
  borderWidth: 0.5,
  states: {
    hover: {
      color: 'red'
    }
  },
  joinBy: ['hc-key', 'code'],
  data: [{
      "code": "us-al-001",
      "name": "Autauga County, AL",
      "value": 3.9
    },
    {
      "code": "us-al-003",
      "name": "Baldwin County, AL",
      "value": 4.3
    }
  ]
}]
</code>```

More information about this issue:

How to fix "Property 'type' is missing in type but required in type 'SeriesXrangeOptions'" in angular highcharts module

https://github.com/highcharts/highcharts/issues/9867

Body:
I'm trying to deploy US Counties map in Highmaps using the highcharts-chart directive. This works fine with the US States map, but have a problem defining the data element for US Counties as I get a compilation error.

This is the attempt:

HTML

    <highcharts-chart
        [Highcharts]="Highcharts"
        [constructorType]="'mapChart'"
        [options]="chartMap"
        [(update)]="updateFlag"
        [oneToOne]="true"
        style="width: 500px; height: 400px; display: block;"
    ></highcharts-chart>

Typescript

import * as Highcharts from 'highcharts';
import MapModule from 'highcharts/modules/map';
const mapX = require('@highcharts/map-collection/countries/us/us-all-all.geo.json')
MapModule(Highcharts);

.....
.....
this.chartMap = {
                chart: {
                    map: mapX
                },
                title: {
                    text: 'THIS IS THE US COUNTIES MAP'
                },
                series: [{ // <-- error is thrown here
                    name: 'Unemployment',
                    borderWidth: 0.5,
                    states: {
                        hover: {
                        color: 'red'
                        }
                    },
                    joinBy: ['hc-key', 'code'],
                    data:  [
                        {
                            "code": "us-al-001",
                            "name": "Autauga County, AL",
                            "value": 3.9
                        },
                        {
                            "code": "us-al-003",
                            "name": "Baldwin County, AL",
                            "value": 4.3
                        }
                    ]
                    }]
            };

I get the following compilation error:

Type '{ name: string; borderWidth: number; states: { hover: { color:
  string; }; }; joinBy: string[]; data: { "code": string; "name":
  string; "value": number; }[]; }' is not assignable to type
  'SeriesAbandsOptions | SeriesAdOptions | SeriesAoOptions |
  SeriesApoOptions | SeriesAreaOptions | SeriesArearangeOptions |
  SeriesAreasplineOptions | SeriesAreasplinerangeOptions | ... 82 more
  ... | SeriesZigzagOptions'.   Property 'type' is missing in type '{
  name: string; borderWidth: number; states: { hover: { color: string;
  }; }; joinBy: string[]; data: { "code": string; "name": string;
  "value": number; }[]; }' but required in type
  'SeriesXrangeOptions'.ts(2322) highcharts.d.ts(335083, 5): 'type' is
  declared here.

I took the data example from here and the map example from here.

What is this error and how to fix it?

Body:
This error occurs because you haven't set the series type which is required for each series when using TypeScript.

series: [{
  name: 'Unemployment',
  type: 'map', // type is required for each series
  borderWidth: 0.5,
  states: {
    hover: {
      color: 'red'
    }
  },
  joinBy: ['hc-key', 'code'],
  data: [{
      "code": "us-al-001",
      "name": "Autauga County, AL",
      "value": 3.9
    },
    {
      "code": "us-al-003",
      "name": "Baldwin County, AL",
      "value": 4.3
    }
  ]
}]

More information about this issue:

How to fix "Property 'type' is missing in type but required in type 'SeriesXrangeOptions'" in angular highcharts module

https://github.com/highcharts/highcharts/issues/9867


问:
Using Jinja to filter by nested dictionary values
I have the following YAML in my SaltStack Pillar:

```<code>prometheus:
  services:
    cassandra:
      enabled: False
    cockroachdb:
      enabled: True
    haproxy:
      enabled: True
    swift:
      enabled: False
</code>```

I want to be able to loop over a list of enabled services.

```<code>{% for enabled_service_name in prometheus.services | selectattr('enabled') %}
{{ enabled_service_name }}
{% endfor %}
</code>```

However, this doesn't work because the attribute I'm trying to filter on is in a nested dictionary below the service name:

{'cassandra': {'enabled': False},
 'cockroachdb': {'enabled': True},
 'haproxy': {'enabled': True},
 'swift': {'enabled': False}}
```

<p>I can obviously achieve what I want by applying a conditional test inside the loop:</p>

```{% for name, properties in prometheus.services | dictsort %}
{% if properties.enabled %}
configuration for {{ name }}
{% endif %}
{% endfor %}
```

However, I will be looping over this list often and would prefer to have Jinja apply the filter in-line in the for loop.

Is there a way to filter by the value of an item in the nested dictionary?

答:
Without changing the structure of your pillar, you can divide your list into two groups via groupby.

```<code>{% for group in prometheus.services.items() | groupby ('1.enabled') %}
{% if group.grouper = True %}
{% set enabled_services = group.list %}
{% else %}
{% set disabled_services = group.list %}
{% endif %}
{% endfor %}
</code>```

It looks a bit more complicated, but it's useful if you need to loop through both lists.

Body:
I have the following YAML in my SaltStack Pillar:

prometheus:
  services:
    cassandra:
      enabled: False
    cockroachdb:
      enabled: True
    haproxy:
      enabled: True
    swift:
      enabled: False

I want to be able to loop over a list of enabled services.

{% for enabled_service_name in prometheus.services | selectattr('enabled') %}
{{ enabled_service_name }}
{% endfor %}

However, this doesn't work because the attribute I'm trying to filter on is in a nested dictionary below the service name:

{'cassandra': {'enabled': False},
 'cockroachdb': {'enabled': True},
 'haproxy': {'enabled': True},
 'swift': {'enabled': False}}

I can obviously achieve what I want by applying a conditional test inside the loop:

{% for name, properties in prometheus.services | dictsort %}
{% if properties.enabled %}
configuration for {{ name }}
{% endif %}
{% endfor %}

However, I will be looping over this list often and would prefer to have Jinja apply the filter in-line in the for loop.

Is there a way to filter by the value of an item in the nested dictionary?

Body:
Without changing the structure of your pillar, you can divide your list into two groups via groupby.

{% for group in prometheus.services.items() | groupby ('1.enabled') %}
{% if group.grouper = True %}
{% set enabled_services = group.list %}
{% else %}
{% set disabled_services = group.list %}
{% endif %}
{% endfor %}

It looks a bit more complicated, but it's useful if you need to loop through both lists.


问:
Angular route guard always redirects to app component only
I have a guard which should run on every route. If user is logged in, they should be redirected to dashboard else to login. Login works fine but auth guard never redirects to dashboard. it always stays in base route. If i manually redirect to dashboard from guard it causes an infinite loop.

app-routes.module.ts

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children: [
      {
        path: 'dashboard',
        component: DashboardComponent
      },
      {
        path: 'home',
        component: AppComponent
      }
    ]
  },
  {
    path: 'login',
    component: LoginComponent
  }
];
```

<p><strong>AuthGuard.ts</strong></p>

<pre class="lang-js prettyprint-override"><code>export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private _router: Router, private _loaderService: LoaderService) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    this._loaderService.show();
    this.authService.isLoggedIn().subscribe( (_allowed: boolean) => {
      if (_allowed) {
        this._loaderService.hide();
        console.info('authenticated', next, _state);
        // this._router.navigate(['/dashboard']); // this cause infinite loop if uncommented
        return true;
      } else {
        console.info('not authenticated');
        this._loaderService.hide();
        this._router.navigate(['/login'], {
          queryParams: {
            return: _state.url
          }
        });
      }
    });
    return false;
  }
}
</code>```

AuthService.ts

isLoggedIn(): Observable<boolean> {
    if (this.token) {
      return this._httpClient.get(environment.api_url + `/api/auth/` + this.token)
        .pipe(map((_response: any) => {
          this._user.updateUser(_response.data);
          this.updateToken(_response.token);
          return _response.status;
        }));
    } else {
      return of(false);
    }
  }
```

答:
Because your public route shouldn't be a child of a protected route. </p>

<p>Move the public route at the root of your routes, and you should be good to go. </p>

Body:
I have a guard which should run on every route. If user is logged in, they should be redirected to dashboard else to login. Login works fine but auth guard never redirects to dashboard. it always stays in base route. If i manually redirect to dashboard from guard it causes an infinite loop.

app-routes.module.ts

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children: [
      {
        path: 'dashboard',
        component: DashboardComponent
      },
      {
        path: 'home',
        component: AppComponent
      }
    ]
  },
  {
    path: 'login',
    component: LoginComponent
  }
];

AuthGuard.ts

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private _router: Router, private _loaderService: LoaderService) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    _state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    this._loaderService.show();
    this.authService.isLoggedIn().subscribe( (_allowed: boolean) => {
      if (_allowed) {
        this._loaderService.hide();
        console.info('authenticated', next, _state);
        // this._router.navigate(['/dashboard']); // this cause infinite loop if uncommented
        return true;
      } else {
        console.info('not authenticated');
        this._loaderService.hide();
        this._router.navigate(['/login'], {
          queryParams: {
            return: _state.url
          }
        });
      }
    });
    return false;
  }
}

AuthService.ts

isLoggedIn(): Observable<boolean> {
    if (this.token) {
      return this._httpClient.get(environment.api_url + `/api/auth/` + this.token)
        .pipe(map((_response: any) => {
          this._user.updateUser(_response.data);
          this.updateToken(_response.token);
          return _response.status;
        }));
    } else {
      return of(false);
    }
  }

Body:
Because your public route shouldn't be a child of a protected route.

Move the public route at the root of your routes, and you should be good to go.


问:
Why are my RenderingHints keys, when applied to a Graphics2D object, not being honored?
When drawing various things using a Graphics2D object and BasicStroke at 1.0f, I can't seem to get the g2d object to honor my RenderingHints settings. Specifically the KEY_ANTIALIASING set to VALUE_ANTIALIAS_ON.

```<code>public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D)g;

    g2d.setStroke(new BasicStroke(1.0f));
    g2d.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON
    );

    // draw stuff...
}
</code>```

Are there other keys I should be using? Am I not applying the keys in the appropriate place? Using it the way described above results in normal, pixelated shapes being drawn.

答:
If you are stroking (as it looks like you are from your snippet), you might want to also try:         </p>

```<code>g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
</code>```

OwnerDisplayName: spligak

ContentLicense: CC BY-SA 2.5

Body:
When drawing various things using a Graphics2D object and BasicStroke at 1.0f, I can't seem to get the g2d object to honor my RenderingHints settings. Specifically the KEY_ANTIALIASING set to VALUE_ANTIALIAS_ON.

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D)g;

    g2d.setStroke(new BasicStroke(1.0f));
    g2d.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON
    );

    // draw stuff...
}

Are there other keys I should be using? Am I not applying the keys in the appropriate place? Using it the way described above results in normal, pixelated shapes being drawn.

Body:
If you are stroking (as it looks like you are from your snippet), you might want to also try:

g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

OwnerDisplayName: jedierikb


问:
Database connection, checking database path
i have created database in sqlite manager. my project get terminated due to exception. when i took the help of break point then i get the "bad access" at line 3rd.
I am unable to get the solution for the problem at 3rd line.

 ```
-(void)checkAndCreateDB
{
    BOOL Success;
    //NSFileManager maintains file
    NSFileManager *FileManager = [NSFileManager defaultManager];
    //Checks Database Path
    Success = [FileManager fileExistsAtPath:dbpath];
    //If file exists it return true
    if(Success)return;
    NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:dbname];
[FileManager copyItemAtPath:databasePathFromApp toPath:dbpath error:nil];
    [FileManager release];
}
```

Here dbpath=

```
/Users/gauravmurghai/Library/Application Support/iPhone Simulator/User/Applications/E48F72FD-5CC9-438C-B412-7D16FEF8DD8C/Documents/dbnitu.sqlite

```

Error is displayed at line 3:“EXC_BAD_ACCESS”.

line 3 is:  Success = [FileManager fileExistsAtPath:dbpath];
I cannot understand where the problem is?Unable to overcome this error.

答:
```<code>-(void)checkAndCreateDB
{

    //NSFileManager maintains file
    NSFileManager *FileManager = [NSFileManager defaultManager];
    //Checks Database Path
    if([FileManager fileExistsAtPath:dbpath]);
    //If file exists it return true
    return;
    NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:dbname];
[FileManager copyItemAtPath:databasePathFromApp toPath:dbpath error:nil];
    [FileManager release];
}
</code>```

Body:
i have created database in sqlite manager. my project get terminated due to exception. when i took the help of break point then i get the "bad access" at line 3rd.
I am unable to get the solution for the problem at 3rd line.

-(void)checkAndCreateDB
{
    BOOL Success;
    //NSFileManager maintains file
    NSFileManager *FileManager = [NSFileManager defaultManager];
    //Checks Database Path
    Success = [FileManager fileExistsAtPath:dbpath];
    //If file exists it return true
    if(Success)return;
    NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:dbname];
[FileManager copyItemAtPath:databasePathFromApp toPath:dbpath error:nil];
    [FileManager release];
}

Here dbpath=

/Users/gauravmurghai/Library/Application Support/iPhone Simulator/User/Applications/E48F72FD-5CC9-438C-B412-7D16FEF8DD8C/Documents/dbnitu.sqlite

Error is displayed at line 3:“EXC_BAD_ACCESS”.

line 3 is:  Success = [FileManager fileExistsAtPath:dbpath];
I cannot understand where the problem is?Unable to overcome this error.


问:
How can I determine if a variable is 'undefined' or 'null'?
How do I determine if a variable is undefined or null?

My code is as follows:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  // DO SOMETHING
};
```
<pre class="lang-html prettyprint-override"><code><div id="esd-names">
  <div id="name"></div>
</div>
</code>```

But when I do this, the JavaScript interpreter halts execution.

答:
The easiest way to check is:</p>

```<code>if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}
</code>```

Body:
How do I determine if a variable is undefined or null?

My code is as follows:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  // DO SOMETHING
};

But when I do this, the JavaScript interpreter halts execution.

Body:
The easiest way to check is:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}


问:
How can I store regex captures in an array in Perl?
Is it possible to store all matches for a regular expression into an array?

I know I can use ($1,...,$n) = m/expr/g;, but it seems as though that can only be used if you know the number of matches you are looking for. I have tried my @array = m/expr/g;, but that doesn't seem to work.

答:
Note that if you know the number of capturing groups you need per match, you can use this simple approach, which I present as an example (of 2 capturing groups.)

Suppose you have some 'data' like

```<code>my $mess = <<'IS_YOURS';
Richard     Rich
April           May
Harmony             Ha\rm
Winter           Win
Faith     Hope
William         Will
Aurora     Dawn
Joy
IS_YOURS
</code>```

With the following regex

```<code>my $oven = qr'^(\w+)\h+(\w+)$'ma;  # skip the /a modifier if using perl < 5.14
</code>```

I can capture all 12 (6 pairs, not 8...Harmony escaped and Joy is missing) in the @box below.

```<code>my @box = $mess =~ m[$oven]g;
</code>```

If I want to "hash out" the details of the box I could just do:

```<code>my %hash = @box;
</code>```

Or I just could have just skipped the box entirely,

```<code>my %hash = $mess =~ m[$oven]g;
</code>```

Note that %hash contains the following. Order is lost and dupe keys (if any had existed) are squashed:

```<code>(
          'April'   => 'May',
          'Richard' => 'Rich',
          'Winter'  => 'Win',
          'William' => 'Will',
          'Faith'   => 'Hope',
          'Aurora'  => 'Dawn'
);
</code>```

Body:
Note that if you know the number of capturing groups you need per match, you can use this simple approach, which I present as an example (of 2 capturing groups.)

Suppose you have some 'data' like

my $mess = <<'IS_YOURS';
Richard     Rich
April           May
Harmony             Ha\rm
Winter           Win
Faith     Hope
William         Will
Aurora     Dawn
Joy
IS_YOURS

With the following regex

my $oven = qr'^(\w+)\h+(\w+)$'ma;  # skip the /a modifier if using perl < 5.14

I can capture all 12 (6 pairs, not 8...Harmony escaped and Joy is missing) in the @box below.

my @box = $mess =~ m[$oven]g;

If I want to "hash out" the details of the box I could just do:

my %hash = @box;

Or I just could have just skipped the box entirely,

my %hash = $mess =~ m[$oven]g;

Note that %hash contains the following. Order is lost and dupe keys (if any had existed) are squashed:

(
          'April'   => 'May',
          'Richard' => 'Rich',
          'Winter'  => 'Win',
          'William' => 'Will',
          'Faith'   => 'Hope',
          'Aurora'  => 'Dawn'
);