问:
Overlapping
's with an image on a wrapper
I know this question has been answered but I am having extreme difficulty using the answers given before and applying them into my code.

I am making an tab-pane with different images. I want to put the image in the lighter orange section on the right with the text on the left. However, this tab is placed onto a wrapper and it's confusing me with the indexes.

In addition, all the solutions that work without considering the wrapper doesn't work when I use XXAMP.

Below is what I have so far and applies to the description :

Here is the code I have so far:

body {
  background-color: #FFF;
  background-image: url(../media/style/background.jpg);
  font-family: helvetica;
  background-repeat: no-repeat;
  background-size: cover;
  overflow-x: hidden;
  background-attachment: fixed;
}

#wrapper img {
  width: 80%;
  height: 60%;
}

#wrapper {
  width: 900px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 20px;
  margin-top: 20;
  margin-right: auto;
  margin-bottom: 20;
  margin-left: auto;
  height: auto;
  border: medium none #9C0;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.images {
  position: relative;
  text-align: center;
}

.tab-content {
  width: 825px;
  border-bottom: 2px solid white;
  border-right: 2px solid white;
  border-left: 2px solid white;
  border-top: 2px solid white;
  padding: 13px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  text-align: right;
}

.nav-tabs {
  margin-bottom: 0;
  width: 805px;
}

.tab-content {
  display: block;
  background-color: rgba(245, 172, 64, 0.9);
  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.1) 50%, #F4B350 50%);
  min-height: 300px;
  z-index: -1;
}

.tab-content img {
  position: relative;
  width: 58vw;
  height: 42vw;
}

.container a {
  background-color: rgba(245, 172, 64, 0.9);
  color: black;
}

.tab-content p {
  font-size: 15px;
}

.tab-content h3 {
  font-size: 28px;
}

#tab1 h3 p {
  background-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <meta charset="UTF-8" />
  <title>Hanler Products - Home</title>
</head>

<body>

  <!-- TAB -->

  <div class="container">
    <ul class="nav nav-tabs">
      <li class="active">Upright Towbar Caddy</li>
      <li>Upright Trailer lid Caddy</li>
      <li>Park Stand</li>
      <li>Gates / Burglar Bars / Security Gates</li>
      <li>Fences</li>
    </ul>

    <div class="tab-content">
      <div id="tab1" class="tab-pane fade in active">
        <div class="box">
          <h3>Upright Towbar Caddy</h3>
          <p>Ideal for short trips to school and back.</p>
        </div>
        <img src="media/style/slider/UTC.jpg" alt="Upright Towbar Caddy">
      </div>
      <div id="tab2" class="tab-pane fade">
        <h3>Upright Trailer lid Caddy</h3>
        <p>Now, taking your cycles on holiday, is a breeze.</p>
        <img src="media/style/UTC.jpg" alt="Upright Trailer lid Caddy" />
      </div>
      <div id="tab3" class="tab-pane fade">
        <h3>Park Stand</h3>
        <p>Ideal for parking bikes at shops, schools and at shopping malls.<br/>The parkstand could prevent damage to vehicles <br/> in parking areas.<br/>The bike could also be chained to be stand <br/> to protect it from being stolen.</p>
      </div>
      <div id="tab4" class="tab-pane fade">
        <h3>Gates / Burglar Bars / Security Gates</h3>
        <p>Custom security bars to keep you and your belongings safe.</p>
      </div>
      <div id="tab5" class="tab-pane fade">
        <h3>Fences</h3>
        <p>Custom fencing for your home and/or business.</p>
      </div>
    </div>
  </div>
</body>

</html></code>```

答:
Try pulling the text to the left, like this;</p>

```<code><div class="tab-content">
        <div id="tab1" class="tab-pane fade in active">
          <div class="box pull-left">
</code>```

Title: Overlapping <div>'s with an image on a wrapper

Body:
I know this question has been answered but I am having extreme difficulty using the answers given before and applying them into my code.

I am making an tab-pane with different images. I want to put the image in the lighter orange section on the right with the text on the left. However, this tab is placed onto a wrapper and it's confusing me with the indexes.

In addition, all the solutions that work without considering the wrapper doesn't work when I use XXAMP.

Below is what I have so far and applies to the description :

Here is the code I have so far:

body {
  background-color: #FFF;
  background-image: url(../media/style/background.jpg);
  font-family: helvetica;
  background-repeat: no-repeat;
  background-size: cover;
  overflow-x: hidden;
  background-attachment: fixed;
}

#wrapper img {
  width: 80%;
  height: 60%;
}

#wrapper {
  width: 900px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 20px;
  margin-top: 20;
  margin-right: auto;
  margin-bottom: 20;
  margin-left: auto;
  height: auto;
  border: medium none #9C0;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.images {
  position: relative;
  text-align: center;
}

.tab-content {
  width: 825px;
  border-bottom: 2px solid white;
  border-right: 2px solid white;
  border-left: 2px solid white;
  border-top: 2px solid white;
  padding: 13px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  text-align: right;
}

.nav-tabs {
  margin-bottom: 0;
  width: 805px;
}

.tab-content {
  display: block;
  background-color: rgba(245, 172, 64, 0.9);
  background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.1) 50%, #F4B350 50%);
  min-height: 300px;
  z-index: -1;
}

.tab-content img {
  position: relative;
  width: 58vw;
  height: 42vw;
}

.container a {
  background-color: rgba(245, 172, 64, 0.9);
  color: black;
}

.tab-content p {
  font-size: 15px;
}

.tab-content h3 {
  font-size: 28px;
}

#tab1 h3 p {
  background-color: white;
}

<!DOCTYPE html>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <meta charset="UTF-8" />
  <title>Hanler Products - Home</title>

Upright Towbar Caddy

Upright Trailer lid Caddy

Park Stand

Gates / Burglar Bars / Security Gates

Fences

Upright Towbar Caddy

Ideal for short trips to school and back.

Upright Trailer lid Caddy

Now, taking your cycles on holiday, is a breeze.

Park Stand

Ideal for parking bikes at shops, schools and at shopping malls.
The parkstand could prevent damage to vehicles
 in parking areas.
The bike could also be chained to be stand
 to protect it from being stolen.

Gates / Burglar Bars / Security Gates

Custom security bars to keep you and your belongings safe.

Fences

Custom fencing for your home and/or business.

Body:
Try pulling the text to the left, like this;

<div class="tab-content">
        <div id="tab1" class="tab-pane fade in active">
          <div class="box pull-left">


来源: stackexchange

问:
How to change timezone on docker private registry running container?
How can I change timezone/time on my running docker private registry container

Host OS: CentOS 7
Docker Version:

```<code>Server:
Version:      17.09.0-ce
API version:  1.32 (minimum version 1.12)
Go version:   go1.8.3
Git commit:   afdb6d4
Built:        Tue Sep 26 22:42:49 2017
OS/Arch:      linux/amd64
Experimental: false
</code>```

Docker registry image: registry:2 ID: a07e3f32a779

Tried execute on container:

    export TZ=Europe/Warsaw
    ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

but without any result for real time.

Same solution works on another containers without any problems.

Any Ideas?

Edit:

Recreated container with compose like this:

```<code>apache:
  image: "httpd:2.4"
  hostname: deleted
  restart: always
  environment:
    - TZ=Europe/Warsaw
  ports:
    - 5043:5043
  links:
    - registry:registry
  volumes:
    - /opt/docker-registry-bundle/auth:/usr/local/apache2/conf
    - /etc/timezone:/etc/timezone:ro

registry:
  image: registry:2
  restart: always
  environment:
    - TZ=Europe/Warsaw
  ports:
    - 127.0.0.1:5000:5000
  volumes:
    - /opt/docker-registry-bundle/registry-data:/var/lib/registry
    - /etc/timezone:/etc/timezone:ro
</code>```

On apache container time is ok.
On registry container still doesn't work.

答:
Solution from sanath

registry:2 image uses alpine base image because of that dpkg command
  is missing, refer below link which explains how to change timezone in
  alpine based images.
  ivankrizsan.se/2015/10/31/time-in-docker-containers ( see Alpine Linux
  section )

ContentLicense: CC BY-SA 3.0

Body:
How can I change timezone/time on my running docker private registry container

Host OS: CentOS 7
Docker Version:

Server:
Version:      17.09.0-ce
API version:  1.32 (minimum version 1.12)
Go version:   go1.8.3
Git commit:   afdb6d4
Built:        Tue Sep 26 22:42:49 2017
OS/Arch:      linux/amd64
Experimental: false

Docker registry image: registry:2 ID: a07e3f32a779

Tried execute on container:

    export TZ=Europe/Warsaw
    ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

but without any result for real time.

Same solution works on another containers without any problems.

Any Ideas?

Edit:

Recreated container with compose like this:

apache:
  image: "httpd:2.4"
  hostname: deleted
  restart: always
  environment:
    - TZ=Europe/Warsaw
  ports:
    - 5043:5043
  links:
    - registry:registry
  volumes:
    - /opt/docker-registry-bundle/auth:/usr/local/apache2/conf
    - /etc/timezone:/etc/timezone:ro

registry:
  image: registry:2
  restart: always
  environment:
    - TZ=Europe/Warsaw
  ports:
    - 127.0.0.1:5000:5000
  volumes:
    - /opt/docker-registry-bundle/registry-data:/var/lib/registry
    - /etc/timezone:/etc/timezone:ro

On apache container time is ok.
On registry container still doesn't work.


问:
Programming style of method declaration of get/set method variables in C++?
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp. </p>

答:
I prefer to put them into the .cpp file, for the sake of fast compile/link times. Even tiny one-liners (empty virtual destructors!) can blow up your compile times, if they are instantiated a lot. In one project, I could cut the compile time by a few seconds by moving all virtual destructors into the .cpp files.

Since then, I'm sold on this, and I would only put them into the header again if a profiler tells me that I can profit from inlining. Only downside is you need more typing, but if you create the .cpp file while you write the header, you can often just copy&paste the declarations and fill them out in the .cpp file, so it's not that bad. Worse of course if you later find out you want to move stuff into a .cpp file.

A nice side effect is that reading stuff is simpler when you have only documentation and declarations in your header, especially if new developers join the project.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie Parker

OwnerDisplayName: Anteru


问:
C# fill an access database from a dataset
I have a program which is supposed to open, edit, create and save access databases. For saving I copy an empty database with just the tables (just to avoid going through the hassle of creating every table  and column etc) and try to fill it with values via the TableAdapterManager.UpdateAll method.

```<code>string _TemplateConnectString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};";
_connection = new OleDbConnection(string.Format(_TemplateConnectString, dlg.FileName));
_connection.Open();

DataSet1TableAdapters.TableAdapterManager tam=new TableAdapterManager();
tam.Connection = _connection;
try
{
    tam.UpdateAll(dataset);
}
catch (System.Exception ex)
{
   MessageBox.Show("Update failed");
}
</code>```

It finishes with no exceptions but the values don't get inserted into the new database.

Also as far as I know the UpdateAll method only updates modified row so if I open some db and it inserts it's rows, it will not take them into account even though there are not in the database that I am trying to fill.

I have also tried filling the database with the ADODB and ADOX extensions but all the solutions I found with those was a lot of hardcoding and no regards for hierarchy, keys, etc.

Is there a way to force insert everything in the new database?

答:
A clumsy solution but it works. I iterate the tables of the dataset and save the via an sql string generator like this:

```<code>void SaveTable(DataTable dt)
    {
        string[] inserts;
        try
        {
            inserts = SqlHelper.GenerateInserts(dt, null, null, null);

            foreach (string s in inserts)
            {
                OleDbCommand cmd = new OleDbCommand();
                cmd.CommandText = s;
                cmd.Connection = _connection;
                int n = cmd.ExecuteNonQuery();
            }
        }
        catch (Exception e)
        {
            SaveOk = false;
        }
    }
</code>```

I found the SqlHelper somewhere on this site, but completely lost where, unforunately. So here is the pastebin with it https://pastebin.com/iCMVuYyu

Body:
I have a program which is supposed to open, edit, create and save access databases. For saving I copy an empty database with just the tables (just to avoid going through the hassle of creating every table  and column etc) and try to fill it with values via the TableAdapterManager.UpdateAll method.

string _TemplateConnectString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};";
_connection = new OleDbConnection(string.Format(_TemplateConnectString, dlg.FileName));
_connection.Open();

DataSet1TableAdapters.TableAdapterManager tam=new TableAdapterManager();
tam.Connection = _connection;
try
{
    tam.UpdateAll(dataset);
}
catch (System.Exception ex)
{
   MessageBox.Show("Update failed");
}

It finishes with no exceptions but the values don't get inserted into the new database.

Also as far as I know the UpdateAll method only updates modified row so if I open some db and it inserts it's rows, it will not take them into account even though there are not in the database that I am trying to fill.

I have also tried filling the database with the ADODB and ADOX extensions but all the solutions I found with those was a lot of hardcoding and no regards for hierarchy, keys, etc.

Is there a way to force insert everything in the new database?

Body:
A clumsy solution but it works. I iterate the tables of the dataset and save the via an sql string generator like this:

void SaveTable(DataTable dt)
    {
        string[] inserts;
        try
        {
            inserts = SqlHelper.GenerateInserts(dt, null, null, null);

            foreach (string s in inserts)
            {
                OleDbCommand cmd = new OleDbCommand();
                cmd.CommandText = s;
                cmd.Connection = _connection;
                int n = cmd.ExecuteNonQuery();
            }
        }
        catch (Exception e)
        {
            SaveOk = false;
        }
    }

I found the SqlHelper somewhere on this site, but completely lost where, unforunately. So here is the pastebin with it https://pastebin.com/iCMVuYyu


问:
Angular2: Web Speech API - Voice recognition
After reading the documentation of webkitSpeechRecognition (voice recognition in Javascript) I tried to implement it in Angular 2.

But when I did this:

```<code>const recognition = new webkitSpeechRecognition();
</code>```

TypeScript say this error:

```<code>[ts] Cannot find name 'webkitSpeechRecognition'. any
</code>```

And if I try to extract webkitSpeechRecognition from window:

```<code>if ('webkitSpeechRecognition' in window) {

    console.log("Enters inside the condition"); // => It's printing

    const { webkitSpeechRecognition } = window; // => TypeScript Error
    const recognition = new webkitSpeechRecognition();
}
</code>```

If I comment the last two lines the console.log is printed, enters to the condition! webkitSpeechRecognition exists inside window!! But if not comment the last two lines the TypeScript error now is this:

```<code>[ts] Type 'Window' has no property 'webkitSpeechRecognition' and no string index signature.
const webkitSpeechRecognition: any
</code>```

How can I create a new recognition in Angular 2? Has anybody tried it?

答:
You can solve the problem by

```<code>const speechRecognition = Window['webkitSpeechRecognition'];
</code>```

Or if You are using jQuery

```<code>const sr = $(window).get(0).webkitSpeechRecognition;
</code>```

Body:
After reading the documentation of webkitSpeechRecognition (voice recognition in Javascript) I tried to implement it in Angular 2.

But when I did this:

const recognition = new webkitSpeechRecognition();

TypeScript say this error:

[ts] Cannot find name 'webkitSpeechRecognition'. any

And if I try to extract webkitSpeechRecognition from window:

if ('webkitSpeechRecognition' in window) {

    console.log("Enters inside the condition"); // => It's printing

    const { webkitSpeechRecognition } = window; // => TypeScript Error
    const recognition = new webkitSpeechRecognition();
}

If I comment the last two lines the console.log is printed, enters to the condition! webkitSpeechRecognition exists inside window!! But if not comment the last two lines the TypeScript error now is this:

[ts] Type 'Window' has no property 'webkitSpeechRecognition' and no string index signature.
const webkitSpeechRecognition: any

How can I create a new recognition in Angular 2? Has anybody tried it?

Body:
You can solve the problem by

const speechRecognition = Window['webkitSpeechRecognition'];

Or if You are using jQuery

const sr = $(window).get(0).webkitSpeechRecognition;


问:
Control structure of document
I have a document, in which is stored information about products. Each chapter has a small table inside it with three rows: Price, Description, Image. Here is how it looks:

I want to change the order of rows in all these tables. Or alternatively, I want to add an additional row to each of them. So the desired result should be:

An explanation of how it could work:

We need a database (Access/Excel/CSV) to store information about each product:

We need to somehow tell Word in which order display the rows. I found something close here:

https://msdn.microsoft.com/en-us/library/office/jj889465.aspx - See example with "Harry Potter" and "Learning XML".

Then we need to insert this into Word. Fields are the first thing which came to mind:

```<code>Product A

{ InsertProduct A }

Product B

{ InsertProduct B }
</code>```

I don't understand how it could be done. Using only VBA? Using custom content controls? Do I need to connect Excel/Access to this document?

答:
It would be much easier to have data structured in Excel worksheets, not in the Word document. So, my first proposal is to ask your partner from the client side or from the other department to provide you data in Excel. If is not possible, you can copy tables from MS Word to MS Excel. Let's assume, that tables are like you have showed and everyone is preceded with product name. I have adapted one of my macros for you:

```<code>Sub CopyTablesFromWord()
    Dim wdApp As Object
    Dim docFile As Object
    Dim tbl As Object
    Dim rngToCopy As Range
    Dim cl As Object
    Dim wdRow As Object
    Dim wdCell As Object
    Dim i As Long, j As Long
    Dim ws As Worksheet
    Dim tblRw As Object, tblCl As Object

    Set wdApp = GetObject(, "Word.Application")
    Set docFile = wdApp.Documents(1)
    Set ws = ActiveWorkbook.Worksheets.Add

    For Each tbl In docFile.Tables
        Set rngToCopy = ws.Range("A" & ws.Cells.Rows.Count).End(xlUp).Offset(1, 0)
        With rngToCopy
            .Value = "Product"
            .Offset(, 1).Value = tbl.Cell(1, 1).Range.Previous.Paragraphs(1).Range
            Set rngToCopy = .Offset(1)
        End With

        i = 1
        For Each tblRw In tbl.Rows
            j = 1
            For Each tblCl In tblRw.Cells
                rngToCopy.Offset(i - 1, j - 1).Value = tbl.Rows(i).Cells(j).Range
                j = j + 1
            Next tblCl
            i = i + 1
        Next tblRw

    Next tbl

End Sub
</code>```

This macro reads all tables from the Word document and copy them to the Excel workbook.
Note, I have assumed that product name is just one line before each table. You may need amend this macro for your purpose. As you have data in the spreadsheet, you can use another subroutine to vlookup product name, price, description or whatever and add arrange them in your table or database.

I cannot tell you how you can add quantity to this, because I don't know where are you taking it from.

Title: Control structure of document

Body:
I have a document, in which is stored information about products. Each chapter has a small table inside it with three rows: Price, Description, Image. Here is how it looks:

I want to change the order of rows in all these tables. Or alternatively, I want to add an additional row to each of them. So the desired result should be:

An explanation of how it could work:

We need a database (Access/Excel/CSV) to store information about each product:

We need to somehow tell Word in which order display the rows. I found something close here:

https://msdn.microsoft.com/en-us/library/office/jj889465.aspx - See example with "Harry Potter" and "Learning XML".

Then we need to insert this into Word. Fields are the first thing which came to mind:

Product A

{ InsertProduct A }

Product B

{ InsertProduct B }

I don't understand how it could be done. Using only VBA? Using custom content controls? Do I need to connect Excel/Access to this document?

Body:
It would be much easier to have data structured in Excel worksheets, not in the Word document. So, my first proposal is to ask your partner from the client side or from the other department to provide you data in Excel. If is not possible, you can copy tables from MS Word to MS Excel. Let's assume, that tables are like you have showed and everyone is preceded with product name. I have adapted one of my macros for you:

Sub CopyTablesFromWord()
    Dim wdApp As Object
    Dim docFile As Object
    Dim tbl As Object
    Dim rngToCopy As Range
    Dim cl As Object
    Dim wdRow As Object
    Dim wdCell As Object
    Dim i As Long, j As Long
    Dim ws As Worksheet
    Dim tblRw As Object, tblCl As Object

    Set wdApp = GetObject(, "Word.Application")
    Set docFile = wdApp.Documents(1)
    Set ws = ActiveWorkbook.Worksheets.Add

    For Each tbl In docFile.Tables
        Set rngToCopy = ws.Range("A" & ws.Cells.Rows.Count).End(xlUp).Offset(1, 0)
        With rngToCopy
            .Value = "Product"
            .Offset(, 1).Value = tbl.Cell(1, 1).Range.Previous.Paragraphs(1).Range
            Set rngToCopy = .Offset(1)
        End With

        i = 1
        For Each tblRw In tbl.Rows
            j = 1
            For Each tblCl In tblRw.Cells
                rngToCopy.Offset(i - 1, j - 1).Value = tbl.Rows(i).Cells(j).Range
                j = j + 1
            Next tblCl
            i = i + 1
        Next tblRw

    Next tbl

End Sub

This macro reads all tables from the Word document and copy them to the Excel workbook.
Note, I have assumed that product name is just one line before each table. You may need amend this macro for your purpose. As you have data in the spreadsheet, you can use another subroutine to vlookup product name, price, description or whatever and add arrange them in your table or database.

I cannot tell you how you can add quantity to this, because I don't know where are you taking it from.


问:
Force deletion of a variable in Python
Okay, so here is my problem :

I have a function that I call very often (several times per second), and a variable old_date that is supposed to be computed in the function.

But it seems that this variable is only calculated once, when the function is first called, and then keeps the same value.

Here is the function :

```<code>def can_push(date):
    """
    Check if the last data was pushed more than TIMEFRAME ago
    :param date: string, date of the new data
    TIMEFRAME = datetime.timedelta(seconds=1)
    DB = MongoClient(HOST, PORT).database
    DATE_FMT = '%Y-%m-%dT%H:%M:%S.%fZ'
    """

    # If collection doesn't exist, we create it and return True

    out = False
    # Get MongoDB collection
    coll = DB.coll
    # Date of the new data (got through websocket)
    new_date = datetime.strptime(date, DATE_FMT)
    # Date of the last data pushed in DB
    cursor = coll.find().sort('{date:-1}').limit(1)
    old_date = cursor[0]['date']
    print old_date # Format is okay, but date is too old

    if (new_date - old_date) > TIMEFRAME:
        out = True
    # gc.collect()
    del old_date
    return out
</code>```

I tried del old_date but it doesn't seem to work.

After reading this I tried to use gc.collect() but I'm not very familiar with Python so I'm not sure what it really does (and it doesn't appear to work either).

If I connect to MongoDB shell, I can actually check that the last data pushed in the database is way younger than old_date shows me.

Does anybody have an idea of another way to forcefully delete old_date at the end of the function ?

Python version : 2.7.12

Kernel : Ubuntu 16.04

答:
Ok so the error was a typo, my bad.

It should be :

```<code>cursor = coll.find().sort("date", -1).limit(1)
</code>```

I was conviced that my request was correct since it worked in MongoDB shell.

Sorry for taking your time and thank you for the help !

Title: Force deletion of a variable in Python

Body:
Okay, so here is my problem :

I have a function that I call very often (several times per second), and a variable old_date that is supposed to be computed in the function.

But it seems that this variable is only calculated once, when the function is first called, and then keeps the same value.

Here is the function :

def can_push(date):
    """
    Check if the last data was pushed more than TIMEFRAME ago
    :param date: string, date of the new data
    TIMEFRAME = datetime.timedelta(seconds=1)
    DB = MongoClient(HOST, PORT).database
    DATE_FMT = '%Y-%m-%dT%H:%M:%S.%fZ'
    """

    # If collection doesn't exist, we create it and return True

    out = False
    # Get MongoDB collection
    coll = DB.coll
    # Date of the new data (got through websocket)
    new_date = datetime.strptime(date, DATE_FMT)
    # Date of the last data pushed in DB
    cursor = coll.find().sort('{date:-1}').limit(1)
    old_date = cursor[0]['date']
    print old_date # Format is okay, but date is too old

    if (new_date - old_date) > TIMEFRAME:
        out = True
    # gc.collect()
    del old_date
    return out

I tried del old_date but it doesn't seem to work.

After reading this I tried to use gc.collect() but I'm not very familiar with Python so I'm not sure what it really does (and it doesn't appear to work either).

If I connect to MongoDB shell, I can actually check that the last data pushed in the database is way younger than old_date shows me.

Does anybody have an idea of another way to forcefully delete old_date at the end of the function ?

Python version : 2.7.12

Kernel : Ubuntu 16.04

Body:
Ok so the error was a typo, my bad.

It should be :

cursor = coll.find().sort("date", -1).limit(1)

I was conviced that my request was correct since it worked in MongoDB shell.

Sorry for taking your time and thank you for the help !


问:
Get image url in prestashop
I need to make a feed for my site for a comparing site. It has to be a sql statement.
For now I have this:

```<code>select  pl.name as Titel,
    ROUND(p.price*1.21,2) as Price,
    replace(concat('http://', ifnull(conf.value,'domain/'), cl.name, '/', p.id_product, '-' , pl.name, '.html'),' ','-') as Link,
     concat('http://', ifnull(conf.value,'domain'), '/img/p/', p.id_product, '-' , pi.id_image, '.jpg') as "Image-location",
     cl.name as Categorie,
    p.id_product AS ID
from dbrb_product p
left join dbrb_image pi on p.id_product = pi.id_product
left join dbrb_product_lang pl on p.id_product = pl.id_product
left join dbrb_category_lang cl on p.id_category_default = cl.id_category
left join dbrb_configuration conf on conf.name = 'dbrb_SHOP_DOMAIN'
left join dbrb_product_carrier x on p.id_product = x.id_product
group by p.id_product
</code>```

But now with the new prestashop version 1.6 the image doesn't work anymore.

Now the image path is: domain.com/img/p/number/number/number/image.png
I don't get the logic from it, can somebody tell me?

There is also another problem I have to deal with, because there are some products which have the same image.

Can somebody complete the SQL code or help me further?

Thanks!

答:
Here $productID is your product's ID :)</p>

```<code>$prod = new Product($productID);
$imgArray = $prod->getImages('1');
if (count($imgArray)>0) {
    $imgID = $imgArray[0]["id_image"];
    $imageUrl=_THEME_PROD_DIR_.Image::getImgFolderStatic($imgID).$imgID.".jpg";
}
</code>```

Title: Get image url in prestashop

Body:
I need to make a feed for my site for a comparing site. It has to be a sql statement.
For now I have this:

select  pl.name as Titel,
    ROUND(p.price*1.21,2) as Price,
    replace(concat('http://', ifnull(conf.value,'domain/'), cl.name, '/', p.id_product, '-' , pl.name, '.html'),' ','-') as Link,
     concat('http://', ifnull(conf.value,'domain'), '/img/p/', p.id_product, '-' , pi.id_image, '.jpg') as "Image-location",
     cl.name as Categorie,
    p.id_product AS ID
from dbrb_product p
left join dbrb_image pi on p.id_product = pi.id_product
left join dbrb_product_lang pl on p.id_product = pl.id_product
left join dbrb_category_lang cl on p.id_category_default = cl.id_category
left join dbrb_configuration conf on conf.name = 'dbrb_SHOP_DOMAIN'
left join dbrb_product_carrier x on p.id_product = x.id_product
group by p.id_product

But now with the new prestashop version 1.6 the image doesn't work anymore.

Now the image path is: domain.com/img/p/number/number/number/image.png
I don't get the logic from it, can somebody tell me?

There is also another problem I have to deal with, because there are some products which have the same image.

Can somebody complete the SQL code or help me further?

Thanks!

Body:
Here $productID is your product's ID :)

$prod = new Product($productID);
$imgArray = $prod->getImages('1');
if (count($imgArray)>0) {
    $imgID = $imgArray[0]["id_image"];
    $imageUrl=_THEME_PROD_DIR_.Image::getImgFolderStatic($imgID).$imgID.".jpg";
}


问:
Issue while executing npm commands
We are facing the below issue while running npm commands multiple times on a machine at the same time.

This issue occurs randomly. Couldn't find any root cause.

Details are attached to below error log

Error log:

```<code> 0 info it worked if it ends with ok
    1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
    1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
    1 verbose cli   'run',
    1 verbose cli   'coverage' ]
    2 info using npm@5.3.0
    3 info using node@v6.4.0
    4 verbose run-script [ 'precoverage', 'coverage', 'postcoverage' ]
    5 info lifecycle gulp-karma@1.0.0~precoverage: gulp-karma@1.0.0
    6 info lifecycle gulp-karma@1.0.0~coverage: gulp-karma@1.0.0
    7 verbose lifecycle gulp-karma@1.0.0~coverage: unsafe-perm in lifecycle true
    8 verbose lifecycle gulp-karma@1.0.0~coverage:
    9 verbose lifecycle gulp-karma@1.0.0~coverage: CWD: D:\workspace\TestGroup\viewer
    10 silly lifecycle gulp-karma@1.0.0~coverage: Args: [ '/d /s /c',
    10 silly lifecycle   'concurrently "gulp common" "gulp feature" "gulp file" "gulp layout" "gulp widget_zero" "gulp widget_one" "gulp mobile_common" "gulp mobile_feature" "gulp mobile_file" "gulp mobile_layout" "gulp mobile_widget"' ]
    11 silly lifecycle gulp-karma@1.0.0~coverage: Returned: code: 1  signal: null
    12 info lifecycle gulp-karma@1.0.0~coverage: Failed to exec coverage script
    13 verbose stack Error: gulp-karma@1.0.0 coverage: `concurrently "gulp common" "gulp feature" "gulp file" "gulp layout" "gulp widget_zero" "gulp widget_one" "gulp mobile_common" "gulp mobile_feature" "gulp mobile_file" "gulp mobile_layout" "gulp mobile_widget"`
    13 verbose stack Exit status 1
    13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:289:16)
    13 verbose stack     at emitTwo (events.js:125:13)
    13 verbose stack     at EventEmitter.emit (events.js:213:7)
    13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:40:14)
    13 verbose stack     at emitTwo (events.js:125:13)
    13 verbose stack     at ChildProcess.emit (events.js:213:7)
    13 verbose stack     at maybeClose (internal/child_process.js:927:16)
    13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
    14 verbose pkgid gulp-karma@1.0.0
    15 verbose cwd D:\workspace\TestGroup\viewer
    16 verbose Windows_NT 10.0.14393
    17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "coverage"
    18 verbose node v6.4.0
    19 verbose npm  v5.3.0
    20 error code ELIFECYCLE
    21 error errno 1
    22 error gulp-karma@1.0.0 coverage: `concurrently "gulp common" "gulp feature" "gulp file
</code>```

It would be grateful if someone helps me to get resolve

答: It seems that your command concurrently returns with an "EXIT_FAILURE" exit code, this can be caused by an javascript error by the inside any of your gulp tasks. Since i don't know what these tasks do i can't really help you on that. You could run each command on it's own to find the one who returns the error.

Title: Issue while executing npm commands

Body:
We are facing the below issue while running npm commands multiple times on a machine at the same time.

This issue occurs randomly. Couldn't find any root cause.

Details are attached to below error log

Error log:

 0 info it worked if it ends with ok
    1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
    1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
    1 verbose cli   'run',
    1 verbose cli   'coverage' ]
    2 info using npm@5.3.0
    3 info using node@v6.4.0
    4 verbose run-script [ 'precoverage', 'coverage', 'postcoverage' ]
    5 info lifecycle gulp-karma@1.0.0~precoverage: gulp-karma@1.0.0
    6 info lifecycle gulp-karma@1.0.0~coverage: gulp-karma@1.0.0
    7 verbose lifecycle gulp-karma@1.0.0~coverage: unsafe-perm in lifecycle true
    8 verbose lifecycle gulp-karma@1.0.0~coverage:
    9 verbose lifecycle gulp-karma@1.0.0~coverage: CWD: D:\workspace\TestGroup\viewer
    10 silly lifecycle gulp-karma@1.0.0~coverage: Args: [ '/d /s /c',
    10 silly lifecycle   'concurrently "gulp common" "gulp feature" "gulp file" "gulp layout" "gulp widget_zero" "gulp widget_one" "gulp mobile_common" "gulp mobile_feature" "gulp mobile_file" "gulp mobile_layout" "gulp mobile_widget"' ]
    11 silly lifecycle gulp-karma@1.0.0~coverage: Returned: code: 1  signal: null
    12 info lifecycle gulp-karma@1.0.0~coverage: Failed to exec coverage script
    13 verbose stack Error: gulp-karma@1.0.0 coverage: `concurrently "gulp common" "gulp feature" "gulp file" "gulp layout" "gulp widget_zero" "gulp widget_one" "gulp mobile_common" "gulp mobile_feature" "gulp mobile_file" "gulp mobile_layout" "gulp mobile_widget"`
    13 verbose stack Exit status 1
    13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:289:16)
    13 verbose stack     at emitTwo (events.js:125:13)
    13 verbose stack     at EventEmitter.emit (events.js:213:7)
    13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:40:14)
    13 verbose stack     at emitTwo (events.js:125:13)
    13 verbose stack     at ChildProcess.emit (events.js:213:7)
    13 verbose stack     at maybeClose (internal/child_process.js:927:16)
    13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
    14 verbose pkgid gulp-karma@1.0.0
    15 verbose cwd D:\workspace\TestGroup\viewer
    16 verbose Windows_NT 10.0.14393
    17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "coverage"
    18 verbose node v6.4.0
    19 verbose npm  v5.3.0
    20 error code ELIFECYCLE
    21 error errno 1
    22 error gulp-karma@1.0.0 coverage: `concurrently "gulp common" "gulp feature" "gulp file

It would be grateful if someone helps me to get resolve


问:
How ItemRenderer is different from ItemEditor in Flex 4?
I know this type of questions already asked by many person but that post didn't give me more information to understand regarding the actually difference between ItemRenderer and ItenEditor in Flex Framework.

As I know ItemRenderer is used for displaying visual elements mostly and ItemEditor is used for editing purpose mainly.

So I have tried following Example to find the difference among that:

For ItemRenderer I used following codes:

```<code><mx:DataGrid dataProvider="{initDG}">
    <mx:columns>
        <mx:DataGridColumn headerText="Artist" dataField="Artist"/>
        <mx:DataGridColumn headerText="Album" dataField="Album"/>
        <mx:DataGridColumn headerText="Price" dataField="Price">
            <mx:itemRenderer>
                <fx:Component>
                    <mx:TextInput restrict="0-9" maxChars="10" />
                </fx:Component>
            </mx:itemRenderer>
        </mx:DataGridColumn>
        <mx:DataGridColumn headerText="Cover" dataField="Cover"/>
    </mx:columns>
</mx:DataGrid>
</code>```

And I got the result as follows:

Where Price field is showing as editable.

And again I tried the same code with ItemEditor as follows:

```<code><mx:DataGrid dataProvider="{initDG}">
    <mx:columns>
        <mx:DataGridColumn headerText="Artist" dataField="Artist"/>
        <mx:DataGridColumn headerText="Album" dataField="Album"/>
        <mx:DataGridColumn headerText="Price" dataField="Price">
            <mx:itemEditor>
                <fx:Component>
                    <mx:TextInput restrict="0-9" maxChars="10" />
                </fx:Component>
            </mx:itemEditor>
        </mx:DataGridColumn>
        <mx:DataGridColumn headerText="Cover" dataField="Cover"/>
    </mx:columns>
</mx:DataGrid>
</code>```

And I got the result as follows:

But here Price field is non editable .

So As I am new to these controls I am getting confused why it is happening. After using ItemEditor as why that field is non editable.

If anybody have knowledge what is the reason behind that please help me to understand more details regarding these two controls.

答:
In the first case, edit works in a roundabout way since you embedded an editable field inside a renderer. The cell is always in the edit mode and does not use the built-in edit mode of the DataGrid.

In the second case, your itemEditor is not activated by Flex because the DataGrid requires 'editable=true'. If you set editable to true, your itemEditor should be activated when the user clicks on the cell.

There is a third approach: use 'editable=true' for the DataGrid, keep the itemRenderer, and set 'rendererIsEditor' on the Column.

Check the examples here; Adobe Flex doc

Body:
I know this type of questions already asked by many person but that post didn't give me more information to understand regarding the actually difference between ItemRenderer and ItenEditor in Flex Framework.

As I know ItemRenderer is used for displaying visual elements mostly and ItemEditor is used for editing purpose mainly.

So I have tried following Example to find the difference among that:

For ItemRenderer I used following codes:

<mx:DataGrid dataProvider="{initDG}">
    <mx:columns>
        <mx:DataGridColumn headerText="Artist" dataField="Artist"/>
        <mx:DataGridColumn headerText="Album" dataField="Album"/>
        <mx:DataGridColumn headerText="Price" dataField="Price">
            <mx:itemRenderer>
                <fx:Component>
                    <mx:TextInput restrict="0-9" maxChars="10" />
                </fx:Component>
            </mx:itemRenderer>
        </mx:DataGridColumn>
        <mx:DataGridColumn headerText="Cover" dataField="Cover"/>
    </mx:columns>
</mx:DataGrid>

And I got the result as follows:

Where Price field is showing as editable.

And again I tried the same code with ItemEditor as follows:

<mx:DataGrid dataProvider="{initDG}">
    <mx:columns>
        <mx:DataGridColumn headerText="Artist" dataField="Artist"/>
        <mx:DataGridColumn headerText="Album" dataField="Album"/>
        <mx:DataGridColumn headerText="Price" dataField="Price">
            <mx:itemEditor>
                <fx:Component>
                    <mx:TextInput restrict="0-9" maxChars="10" />
                </fx:Component>
            </mx:itemEditor>
        </mx:DataGridColumn>
        <mx:DataGridColumn headerText="Cover" dataField="Cover"/>
    </mx:columns>
</mx:DataGrid>

And I got the result as follows:

But here Price field is non editable .

So As I am new to these controls I am getting confused why it is happening. After using ItemEditor as why that field is non editable.

If anybody have knowledge what is the reason behind that please help me to understand more details regarding these two controls.


问:
Toastr passed to child element in angular4
I have a parent component that uses ng2-toastr (4.1.2).

Parent element :

```<code>import { Component, ViewContainerRef } from '@angular/core';
    import { AfterViewInit, ViewChild } from '@angular/core';
    import { Router } from '@angular/router';
    declare var jquery: any;
    declare var $: any;
    import { ToastsManager } from 'ng2-toastr/ng2-toastr';

    import { File } from '../models/file';
    import { Tag } from '../models/tag';
    import { Group } from '../models/group';
    import { CmsService } from '../services/cms.service';

    @Component({
        selector: 'app-cms',
        template: `
             <ul *ngFor="let directory of structure?.root.directories">
                <app-directory (refresh)="refresh($event)" [directory]="directory" *ngIf="directory"></app-directory>
                <li *ngFor="let file of directory.files">
                    {{file.name}}.{{file.extension}}
                </li>
            </ul>
        `,
        providers: [
            CmsService
        ]
    })
    export class CmsComponent  {
        structure: any;
        tags: Array<Tag>;
        groups: Array<Group>;
        file: {name: string, firstPageAsCover: boolean, shareable: boolean, tags: Array<{id: number}>};
        directory: {name: string, requiredGroups: Array<{id: number}>};
        constructor (
            private cmsService: CmsService,
            private toastr: ToastsManager,
            private _vcr: ViewContainerRef,
            private router: Router
        ) {
            this.toastr.setRootViewContainerRef(_vcr);
        }
    }
</code>```

Child element

```<code>import { Component, Input, Output, ViewContainerRef, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
declare var jquery: any;
declare var $: any;
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

import { File } from '../models/file';
import { Directory } from '../models/directory';
import { CmsService } from '../services/cms.service';

@Component({
    selector: 'app-directory',
    template: `
        <li class="directory" data-id="{{directory.id}}">
            <a (click)="toggle($event.target, directory.id)">+</a>
            {{directory.name}}
            <a class="action addFolder" (click)="addDirectory(directory)"></a>
            <a class="action editFile" (click)="editDirectory(directory)"></a>
            <a class="action addFile" (click)="add(directory)"></a>
            <ul class="sub d-none">
                <app-directory *ngFor="let dir of directory.directories" (refresh)="refreshChild($event)" [directory]="dir"></app-directory>
                <li class="file" *ngFor="let file of directory.files">
                    <a (click)="displayFile(file.id)">
                        {{file.name}}.{{file.extension}} | {{file.sizeInBytes / 1024}} kb | {{file.lastModified}} | {{file.timesViewed}}
                    </a>
                    <a class="action editFile" (click)="edit(file)"></a>
                    <a class="action link" (click)="link(file.id)"></a>
                    <a class="action download" (click)="download(file.id)"></a>
                    <a class="action delete" (click)="delete(file.id)"></a>
                </li>
            </ul>
        </li>
    `,
    providers: [
        CmsService
    ]
})
export class DirectoryComponent  {
    @Output() refresh: EventEmitter<any> = new EventEmitter();
    @Input() directory: Directory;
    constructor (
        private cmsService: CmsService,
        private toastr: ToastsManager,
        private _vcr: ViewContainerRef,
        private router: Router
    ) {
        this.toastr.setRootViewContainerRef(_vcr);
    }

    ngOnInit() {
        this.toastr.success('cucu', 'cucu');
    }
}
</code>```

When I try to enable the toastr in the child element, it only works first time it's loaded.
Then I have this message :

ERROR Error: Uncaught (in promise): Error: ViewDestroyedError: Attempt to use > a destroyed view: detectChanges

Also, the toastr doesn't work anymore on the parent element.

Please note that the child element is recursive.

Thanks !

答:
You need to set setRootViewContainerRef only on root element.

So remove this.toastr.setRootViewContainerRef(_vcr); on child component and you will be fine.

Body:
I have a parent component that uses ng2-toastr (4.1.2).

Parent element :

import { Component, ViewContainerRef } from '@angular/core';
    import { AfterViewInit, ViewChild } from '@angular/core';
    import { Router } from '@angular/router';
    declare var jquery: any;
    declare var $: any;
    import { ToastsManager } from 'ng2-toastr/ng2-toastr';

    import { File } from '../models/file';
    import { Tag } from '../models/tag';
    import { Group } from '../models/group';
    import { CmsService } from '../services/cms.service';

    @Component({
        selector: 'app-cms',
        template: `

                <app-directory (refresh)="refresh($event)" [directory]="directory" *ngIf="directory"></app-directory>

                    {{file.name}}.{{file.extension}}

        `,
        providers: [
            CmsService
        ]
    })
    export class CmsComponent  {
        structure: any;
        tags: Array<Tag>;
        groups: Array<Group>;
        file: {name: string, firstPageAsCover: boolean, shareable: boolean, tags: Array<{id: number}>};
        directory: {name: string, requiredGroups: Array<{id: number}>};
        constructor (
            private cmsService: CmsService,
            private toastr: ToastsManager,
            private _vcr: ViewContainerRef,
            private router: Router
        ) {
            this.toastr.setRootViewContainerRef(_vcr);
        }
    }

Child element

import { Component, Input, Output, ViewContainerRef, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
declare var jquery: any;
declare var $: any;
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

import { File } from '../models/file';
import { Directory } from '../models/directory';
import { CmsService } from '../services/cms.service';

@Component({
    selector: 'app-directory',
    template: `

            +
            {{directory.name}}

                <app-directory *ngFor="let dir of directory.directories" (refresh)="refreshChild($event)" [directory]="dir"></app-directory>

                        {{file.name}}.{{file.extension}} | {{file.sizeInBytes / 1024}} kb | {{file.lastModified}} | {{file.timesViewed}}

    `,
    providers: [
        CmsService
    ]
})
export class DirectoryComponent  {
    @Output() refresh: EventEmitter<any> = new EventEmitter();
    @Input() directory: Directory;
    constructor (
        private cmsService: CmsService,
        private toastr: ToastsManager,
        private _vcr: ViewContainerRef,
        private router: Router
    ) {
        this.toastr.setRootViewContainerRef(_vcr);
    }

    ngOnInit() {
        this.toastr.success('cucu', 'cucu');
    }
}

When I try to enable the toastr in the child element, it only works first time it's loaded.
Then I have this message :

ERROR Error: Uncaught (in promise): Error: ViewDestroyedError: Attempt to use > a destroyed view: detectChanges

Also, the toastr doesn't work anymore on the parent element.

Please note that the child element is recursive.

Thanks !


问:
ZABBIX 3.0.10 - Get incoming/outgoing traffic with ZABBIX API
I want to know if through the ZABBIX API is something method or parameter for obtain the network traffic (i.e., kbps/mbps...).

I searched for it in the official page and not found.

答: You can use Zabbix API, history.get method.</p>


问:
`pointer-events: none;` does not work for iframe in Edge
I'm applying pointer-events: none; on iframe, it works fine in all major browsers except for the Edge (tested with Edge 16).
In Edge, I still can click anything inside the iframe. I've also tried to apply the styling to iframe's parent div, but nothing works.
Note: I can't apply it inside of the iframe

```<code><div style="pointer-events: none;">
  <iframe>...</iframe>
</div>

<iframe style="pointer-events: none;">...</iframe>
</code>```

Is there a workaround?
Thanks!

答:
After a farther investigation, it seems that this is a bug in Edge v16 (Edge/16.16299), everything works fine in Edge v15 and below.
So, be careful: in Edge v16, pointer-events: none; does not affect the iframes in any way, even if you applied it to the parent container.

UPD: I had submitted the bug report to the Edge development team, they have fixed it in April release or so
https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14961910/

Body:
I'm applying pointer-events: none; on iframe, it works fine in all major browsers except for the Edge (tested with Edge 16).
In Edge, I still can click anything inside the iframe. I've also tried to apply the styling to iframe's parent div, but nothing works.
Note: I can't apply it inside of the iframe

  ...

...

Is there a workaround?
Thanks!

ContentLicense: CC BY-SA 4.0


问:
Error returning boolean in Swagger-Node
I'm new to swagger-node and I am creating an API method that returns data of type boolean. The yaml of the method is:

```<code>  /IsBooting:
  get:
    summary: "Returns if the device is booting"
    description: "Returns true when  is in booting state"
    x-swagger-router-controller: printer_status
    operationId: IsBooting
    responses:
      200:
        description: "Returns a bool that indicates if the deviceis booting"
        schema:
          type: "boolean"
      default:
        description: "Unexpected error"
        schema:
          $ref: "#/definitions/Error"
</code>```

The method in the controller that this API method call is:

```<code>function IsBooting(req, res) {
   res.json(false)
}
</code>```

When I call this method using PostMan, some validations fails with this message:

```<code>Error: Response validation failed: not a valid boolean: false
    at throwErrorWithCode (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\lib\validators.js:121:13)
    at validateTypeAndFormat (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\lib\validators.js:536:7)
    at Object.module.exports.validateSchemaConstraints (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\lib\validators.js:627:7)
    at validateValue (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\middleware\swagger-validator.js:117:16)
    at ServerResponse.res.end (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\middleware\swagger-validator.js:242:9)
    at ServerResponse.send (C:\...\node_modules\express\lib\response.js:204:10)
    at ServerResponse.json (C:\...\node_modules\express\lib\response.js:249:15)
    at IsBooting (C:\...\api\controllers\printer_status.js:54:7)
    at swaggerRouter (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\middleware\swagger-router.js:407:20)
    at swagger_router (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\fittings\swagger_router.js:31:5)
</code>```

I don't know how to make a response that contains the data. I cand send it if I use a string as type, or if I create a new complex type that encapsulates the boolean, but I think that there are not very good solutions...

Do you have any idea?

答:
The swagger has DataType for boolean:
https://swagger.io/docs/specification/data-models/data-types/

The most correct would be to create a schema definition for the answer:

```<code>    responses:
      "200":
        description: Success
        schema:
          type: "#/definitions/TrueReponsenDefinition"
</code>```

Make the proper definition, for this case:

```<code>      TrueReponsenDefinition:
        title: A bool that indicates if the deviceis booting
        type: boolean
        properties:
          booted:
            type: boolean
</code>```

Response from the node, would be:

```<code>  const data = {
    booted: true,
  };
  return res.status(httpStatus.OK).json(data);
</code>```

Note that the most appropriate would be to encapsulate the data. In this case, we use "booted"

The body of the answer will be:

```<code>{
  "booted": true
}
</code>```

Title: Error returning boolean in Swagger-Node

Body:
I'm new to swagger-node and I am creating an API method that returns data of type boolean. The yaml of the method is:

  /IsBooting:
  get:
    summary: "Returns if the device is booting"
    description: "Returns true when  is in booting state"
    x-swagger-router-controller: printer_status
    operationId: IsBooting
    responses:
      200:
        description: "Returns a bool that indicates if the deviceis booting"
        schema:
          type: "boolean"
      default:
        description: "Unexpected error"
        schema:
          $ref: "#/definitions/Error"

The method in the controller that this API method call is:

function IsBooting(req, res) {
   res.json(false)
}

When I call this method using PostMan, some validations fails with this message:

Error: Response validation failed: not a valid boolean: false
    at throwErrorWithCode (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\lib\validators.js:121:13)
    at validateTypeAndFormat (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\lib\validators.js:536:7)
    at Object.module.exports.validateSchemaConstraints (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\lib\validators.js:627:7)
    at validateValue (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\middleware\swagger-validator.js:117:16)
    at ServerResponse.res.end (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\middleware\swagger-validator.js:242:9)
    at ServerResponse.send (C:\...\node_modules\express\lib\response.js:204:10)
    at ServerResponse.json (C:\...\node_modules\express\lib\response.js:249:15)
    at IsBooting (C:\...\api\controllers\printer_status.js:54:7)
    at swaggerRouter (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\node_modules\swagger-tools\middleware\swagger-router.js:407:20)
    at swagger_router (C:\...\node_modules\swagger-express-mw\node_modules\swagger-node-runner\fittings\swagger_router.js:31:5)

I don't know how to make a response that contains the data. I cand send it if I use a string as type, or if I create a new complex type that encapsulates the boolean, but I think that there are not very good solutions...

Do you have any idea?

Body:
The swagger has DataType for boolean:
https://swagger.io/docs/specification/data-models/data-types/

The most correct would be to create a schema definition for the answer:

    responses:
      "200":
        description: Success
        schema:
          type: "#/definitions/TrueReponsenDefinition"

Make the proper definition, for this case:

      TrueReponsenDefinition:
        title: A bool that indicates if the deviceis booting
        type: boolean
        properties:
          booted:
            type: boolean

Response from the node, would be:

  const data = {
    booted: true,
  };
  return res.status(httpStatus.OK).json(data);

Note that the most appropriate would be to encapsulate the data. In this case, we use "booted"

The body of the answer will be:

{
  "booted": true
}


问:
Picture shrinks down in size, but doesn't grow back?
I'm trying to make an image shrink down in width, change the image source, and grow back out. It shrinks, but it doesn't grow back. Any ideas what's wrong?</p>

```<code>while (pictureBox2.Size.Width > 0)
{
    int width = pictureBox2.Size.Width;
    width -= 2;
    pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
    pictureBox2.Location = new Point(pictureBox2.Location.X + 1, pictureBox2.Location.Y);
    System.Threading.Thread.Sleep(1);
}
pictureBox1.Image = currentImage;
while (pictureBox2.Size.Width < 191)
{
    int width = pictureBox2.Size.Width;
    width += 2;
    pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
    pictureBox2.Location = new Point(pictureBox2.Location.X - 1, pictureBox2.Location.Y);
    System.Threading.Thread.Sleep(1);
}
</code>```

答:
Mark your method with async, then use await Task.Delay(1); instead of Sleep().  This will keep the app responsive and allow the UI to actually repaint itself as the size of your PictureBox changes:

```<code>private async void button1_Click(object sender, EventArgs e)
{
    while (pictureBox2.Size.Width > 0)
    {
        int width = pictureBox2.Size.Width;
        width -= 2;
        pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
        pictureBox2.Location = new Point(pictureBox2.Location.X + 1, pictureBox2.Location.Y);
        await Task.Delay(1);
    }
    pictureBox1.Image = currentImage;
    while (pictureBox2.Size.Width < 191)
    {
        int width = pictureBox2.Size.Width;
        width += 2;
        pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
        pictureBox2.Location = new Point(pictureBox2.Location.X - 1, pictureBox2.Location.Y);
        await Task.Delay(1);
    }
}
</code>```

Body:
I'm trying to make an image shrink down in width, change the image source, and grow back out. It shrinks, but it doesn't grow back. Any ideas what's wrong?

while (pictureBox2.Size.Width > 0)
{
    int width = pictureBox2.Size.Width;
    width -= 2;
    pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
    pictureBox2.Location = new Point(pictureBox2.Location.X + 1, pictureBox2.Location.Y);
    System.Threading.Thread.Sleep(1);
}
pictureBox1.Image = currentImage;
while (pictureBox2.Size.Width < 191)
{
    int width = pictureBox2.Size.Width;
    width += 2;
    pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
    pictureBox2.Location = new Point(pictureBox2.Location.X - 1, pictureBox2.Location.Y);
    System.Threading.Thread.Sleep(1);
}

Body:
Mark your method with async, then use await Task.Delay(1); instead of Sleep().  This will keep the app responsive and allow the UI to actually repaint itself as the size of your PictureBox changes:

private async void button1_Click(object sender, EventArgs e)
{
    while (pictureBox2.Size.Width > 0)
    {
        int width = pictureBox2.Size.Width;
        width -= 2;
        pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
        pictureBox2.Location = new Point(pictureBox2.Location.X + 1, pictureBox2.Location.Y);
        await Task.Delay(1);
    }
    pictureBox1.Image = currentImage;
    while (pictureBox2.Size.Width < 191)
    {
        int width = pictureBox2.Size.Width;
        width += 2;
        pictureBox2.Size = new Size(width, pictureBox2.Size.Height);
        pictureBox2.Location = new Point(pictureBox2.Location.X - 1, pictureBox2.Location.Y);
        await Task.Delay(1);
    }
}


问:
Query to list users having same profile from two tables
```<code>Table 1 : dbt_m_user (user_id, user_name, email_id, . . . . . )

Table 2 : dbt_m_user_profile (user_id, profile_id, . . . . .)
</code>```

I have e-mail id of an user who has particular profile (role).
Now I need names of users who are having same access profile.

I could get the results from below, but it looks very raw and doesn't seem to be elegant one, considering that there are only 2 tables.

```<code>  select user_name from dbt_m_user where user_id in (
  select user_id from dbt_m_user_profile where profile_id in (
  select profile_id from dbt_m_user_profile where user_id in (
  select user_id from  dbt_m_user where Email_Id = 'snehal.masne@db.com' )))
</code>```

Can this be improvised by using special clauses/joins ?

答:
How about this one? I haven't tested it though</p>

```<code>   SELECT u.username
     FROM dbt_m_user u
     JOIN dbt_m_user_profile p
      ON  (u.user_id = p.user_id)
     JOIN dbt_m_user_profile up
      ON  (p.profile_id = up.profile_id)
    JOIN  dbt_m_user ou
      ON  (up.user_id = ou.user_id)
   WHERE ou.email_id = 'snehal.masne@db.com';
</code>```

Body:
Table 1 : dbt_m_user (user_id, user_name, email_id, . . . . . )

Table 2 : dbt_m_user_profile (user_id, profile_id, . . . . .)

I have e-mail id of an user who has particular profile (role).
Now I need names of users who are having same access profile.

I could get the results from below, but it looks very raw and doesn't seem to be elegant one, considering that there are only 2 tables.

  select user_name from dbt_m_user where user_id in (
  select user_id from dbt_m_user_profile where profile_id in (
  select profile_id from dbt_m_user_profile where user_id in (
  select user_id from  dbt_m_user where Email_Id = 'snehal.masne@db.com' )))

Can this be improvised by using special clauses/joins ?

Body:
How about this one? I haven't tested it though

   SELECT u.username
     FROM dbt_m_user u
     JOIN dbt_m_user_profile p
      ON  (u.user_id = p.user_id)
     JOIN dbt_m_user_profile up
      ON  (p.profile_id = up.profile_id)
    JOIN  dbt_m_user ou
      ON  (up.user_id = ou.user_id)
   WHERE ou.email_id = 'snehal.masne@db.com';


问:
ios version of themes and styles
As an Android developer new to iOS/swift, I am trying to implement a global theme/style which every view controller can inherit. I expect one file which I can modify which would affect all View Controllers's UI. This is possible in android. Does iOS have anything similar?</p>

答:
The best match for what you are looking for is probably UIAppearance, although not quite the same.

What it allows you to do is basically setup each component once, and then have that be the default look for all other components.

An example for setting button colors (you could do this in your AppDelegate):

```<code>UIButton.appearance().setTitleColor(.white, forState: .normal)
UIButton.appearance().backgroundColor = .blue
</code>```

Try looking at these tutorials:

https://www.raywenderlich.com/108766/uiappearance-tutorial

http://blog.iseinc.biz/use-uiappearance-create-ios-app-themes

Title: ios version of themes and styles

Body:
The best match for what you are looking for is probably UIAppearance, although not quite the same.

What it allows you to do is basically setup each component once, and then have that be the default look for all other components.

An example for setting button colors (you could do this in your AppDelegate):

UIButton.appearance().setTitleColor(.white, forState: .normal)
UIButton.appearance().backgroundColor = .blue

Try looking at these tutorials:

https://www.raywenderlich.com/108766/uiappearance-tutorial

http://blog.iseinc.biz/use-uiappearance-create-ios-app-themes


问:
Trying to store image into a variable
I'm trying to store image in a variable.

eg.
I'm creating a dynamic table where image upload is a part
in that table

```<code> $("#pdfFormInsideTblRight").after("<table class='table table-bordered'><thead class='thead-inverse'><tr><th class='text-left'>Properties</th>" +
                        "<th>Detail</th></tr></thead>" +
                        "<tr><td class='text-left'><strong>Product Group</strong></td>" +
    "<td><input type='file' id='flImage' name='flImage[]' multiple /></td>
</tr></table>");
</code>```

and now i want to store the image uploaded above in variable 'flImage', in a variable 'user'  like other inputs value from textbox and lables value are stored through jquery in var 'user' as given below

```<code> <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
        <script type="text/javascript">
        $(function () {
            $(document).on("click", "[id*=btnFrmSubmit]", function () {
    var user = {};
                user.PRODUCT_ID = 1;
    user.REVISION = $("#Revision").text();
    user.P_GROUP = $("[id*=P_Group]").val();
    user.IMG1 = $("[id=flImage]")
     });
    }
</code>```

but there is issue. Any idea would be appreciated how to do it.

答:
I think you want source of image tag. for getting this you should try like below code.</p>

```<code>$("[id=flImage]").attr('src')
</code>```

Title: Trying to store image into a variable

Body:
I'm trying to store image in a variable.

eg.
I'm creating a dynamic table where image upload is a part
in that table

 $("#pdfFormInsideTblRight").after("

Properties	" +
                        "Detail

" +
                        "
Product Group	" +
    "<input type='file' id='flImage' name='flImage[]' multiple />

");

and now i want to store the image uploaded above in variable 'flImage', in a variable 'user'  like other inputs value from textbox and lables value are stored through jquery in var 'user' as given below

Body:
I think you want source of image tag. for getting this you should try like below code.

$("[id=flImage]").attr('src')


问:
AngularFire5 — Reference.update failed: First argument contains a function in property

I'm trying to save changes to an existing node in my Firebase DB, but I'm getting this error here:

Reference.update failed: First argument contains a function in property 'matatu-list.-L-RMcqjnladFM5-V80b.payload.node_.children_.comparator_' with contents = function NAME_COMPARATOR(left, right) {
      return util_1.nameCompare(left, right);
  }

I want to edit an item basing on its respective key (which is passed from another page through navParams).

Here is the interface I used to structure the DB:

interface.ts

```<code>export interface Matatu {
    $key?: string;
    matNumberPlate: string;
    matSacco: string;
    matDriver: string;
    matAccessCode: string;
    matStatus: string;
    matTracker: string;
    matLocation: string;

    //Optionals
    payload?:any;
    key?:any;

}
</code>```

The .ts and .html code that's meant to update the record:

.ts

```<code>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireObject, AngularFireDatabase } from 'angularfire2/database';
import { Matatu } from '../../models/matatu/matatu.interface';
import { Subscription } from 'rxjs/Subscription';

@IonicPage()
@Component({
  selector: 'page-edit-ma3',
  templateUrl: 'edit-ma3.html',
})
export class EditMa3Page {

  matatuRef$: AngularFireObject<Matatu>;
  matatuAsync$: any;
  matatu = {} as Matatu;
  sub: Subscription;

  constructor(public navCtrl: NavController, public navParams: NavParams, private database: AngularFireDatabase) {

    const matKey = this.navParams.get('matKey');
    this.matatuRef$ = this.database.object(`matatu-list/${matKey}`);
    this.matatuAsync$ = this.matatuRef$.snapshotChanges();
    //console.log(matKey);

    this.sub = this.matatuAsync$.subscribe(
      matatu => this.matatu = matatu
    )
  }

  editMatatu(matatu : Matatu){
    this.matatuRef$.update(matatu);

    this.navCtrl.pop();
  }

  ionViewWillLeave(){
    this.sub.unsubscribe();
  }

}
</code>```

.html

```<code><ion-content>
  <ion-list>
    <ion-list-header>
      Matatu Details
    </ion-list-header>

    <ion-item>
        <ion-label>Sacco</ion-label>
        <ion-input type="text" [(ngModel)]="matatu.matSacco"></ion-input>
    </ion-item>

    <ion-item>
        <ion-label>Driver</ion-label>
        <ion-input type="text" [(ngModel)]="matatu.matDriver"></ion-input>
    </ion-item>

    <ion-item>
          <ion-label> Access Code</ion-label>
          <ion-input type="password" [(ngModel)]="matatu.matAccessCode"></ion-input>
    </ion-item>

  </ion-list>
  <ion-list radio-group [(ngModel)]="matatu.matTracker">
    <ion-list-header>
      Preferred Tracking
    </ion-list-header>

    <ion-item>
        <ion-label>GPS</ion-label>
        <ion-radio checked="true" value="GPS"></ion-radio>
    </ion-item>

    <ion-item>
        <ion-label>Driver's Location</ion-label>
        <ion-radio value="Driver's Location"></ion-radio>
    </ion-item>
  </ion-list>

  <div padding>
    <button ion-button block (click)="editMatatu(matatu)">Save Changes</button>
  </div>
</ion-content>
</code>```

How do I go about rectifying this? I'd appreciate it if it was pointed out to me where I went wrong, and what other approaches can get this done(even the dirty ones!).

答:
You can pass the key in a placeholder variable or you could just concatenate it like so:

```<code>this.matatuRef$ = this.database.object(`matatu-list/`+ matKey);
</code>```

Do keep in mind this is not a good approach, but it'll do the trick.

Firebase fires this error when you try to push data that contains a function, or a datatype instead of data values.

Basing on your interface, and the values you are passing from you template, your

update method should be like this:

```<code>editMatatu(matatu : Matatu){

    this.matatuRef$.update({
      matDriver: this.matatu.matDriver,
      matAccessCode: this.matatu.matAccessCode,
      matSacco: this.matatu.matSacco
    });

  }
</code>```

Body:
I'm trying to save changes to an existing node in my Firebase DB, but I'm getting this error here:

Reference.update failed: First argument contains a function in property 'matatu-list.-L-RMcqjnladFM5-V80b.payload.node_.children_.comparator_' with contents = function NAME_COMPARATOR(left, right) {
      return util_1.nameCompare(left, right);
  }

I want to edit an item basing on its respective key (which is passed from another page through navParams).

Here is the interface I used to structure the DB:

interface.ts

export interface Matatu {
    $key?: string;
    matNumberPlate: string;
    matSacco: string;
    matDriver: string;
    matAccessCode: string;
    matStatus: string;
    matTracker: string;
    matLocation: string;

    //Optionals
    payload?:any;
    key?:any;

}

The .ts and .html code that's meant to update the record:

.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireObject, AngularFireDatabase } from 'angularfire2/database';
import { Matatu } from '../../models/matatu/matatu.interface';
import { Subscription } from 'rxjs/Subscription';

@IonicPage()
@Component({
  selector: 'page-edit-ma3',
  templateUrl: 'edit-ma3.html',
})
export class EditMa3Page {

  matatuRef$: AngularFireObject<Matatu>;
  matatuAsync$: any;
  matatu = {} as Matatu;
  sub: Subscription;

  constructor(public navCtrl: NavController, public navParams: NavParams, private database: AngularFireDatabase) {

    const matKey = this.navParams.get('matKey');
    this.matatuRef$ = this.database.object(`matatu-list/${matKey}`);
    this.matatuAsync$ = this.matatuRef$.snapshotChanges();
    //console.log(matKey);

    this.sub = this.matatuAsync$.subscribe(
      matatu => this.matatu = matatu
    )
  }

  editMatatu(matatu : Matatu){
    this.matatuRef$.update(matatu);

    this.navCtrl.pop();
  }

  ionViewWillLeave(){
    this.sub.unsubscribe();
  }

}

.html

<ion-content>
  <ion-list>
    <ion-list-header>
      Matatu Details
    </ion-list-header>

    <ion-item>
        <ion-label>Sacco</ion-label>
        <ion-input type="text" [(ngModel)]="matatu.matSacco"></ion-input>
    </ion-item>

    <ion-item>
        <ion-label>Driver</ion-label>
        <ion-input type="text" [(ngModel)]="matatu.matDriver"></ion-input>
    </ion-item>

    <ion-item>
          <ion-label> Access Code</ion-label>
          <ion-input type="password" [(ngModel)]="matatu.matAccessCode"></ion-input>
    </ion-item>

  </ion-list>
  <ion-list radio-group [(ngModel)]="matatu.matTracker">
    <ion-list-header>
      Preferred Tracking
    </ion-list-header>

    <ion-item>
        <ion-label>GPS</ion-label>
        <ion-radio checked="true" value="GPS"></ion-radio>
    </ion-item>

    <ion-item>
        <ion-label>Driver's Location</ion-label>
        <ion-radio value="Driver's Location"></ion-radio>
    </ion-item>
  </ion-list>

    <button ion-button block (click)="editMatatu(matatu)">Save Changes</button>

</ion-content>

How do I go about rectifying this? I'd appreciate it if it was pointed out to me where I went wrong, and what other approaches can get this done(even the dirty ones!).

Body:
You can pass the key in a placeholder variable or you could just concatenate it like so:

this.matatuRef$ = this.database.object(`matatu-list/`+ matKey);

Do keep in mind this is not a good approach, but it'll do the trick.

Firebase fires this error when you try to push data that contains a function, or a datatype instead of data values.

Basing on your interface, and the values you are passing from you template, your

update method should be like this:

editMatatu(matatu : Matatu){

    this.matatuRef$.update({
      matDriver: this.matatu.matDriver,
      matAccessCode: this.matatu.matAccessCode,
      matSacco: this.matatu.matSacco
    });

  }


问:
value which I range over in slice changes when iterating
I've got a []int that I range over. I get that when I iterate I have a key/value. I want to also access the slice which I'm iterating over. I don't understand why the slice changes however.

```<code>func main() {
var rows []string
rows = append(rows, "1  2   3", "4  5   6")
for _, row := range rows {
    row := formatRow(row)
    fmt.Println("sent row: ", row) // <------ THIS RETURNS [1,2,3]
    for i, _ := range row {
        fmt.Println("sent row: ", row) // <------ THIS RETURNS [1,3,3]
        _ = getShortRow(row, i)
    }
}
}

func getShortRow(row []int, i int) []int {
    if i == 0 {
        row := append(row[1:])
        return row
}
endPosition := i + 1
if endPosition == len(row) {
    row := append(row[:i])
    return row
}

st := append(row[:i])
end := append(row[i+1:])
row = append(st, end...)
return row
}

func formatRow(row string) []int {
    row = strings.Replace(row, "    ", ",", -1)
    if row[len(row)-1:] == "," {
        row = row[:len(row)-1]
    }
    nValues := strings.Count(row, ",") + 1
    var s []int
    // convert []string to []int
    for index := 0; index < nValues; index++ {
        var value int
        if index == nValues-1 {
            value, _ = strconv.Atoi(row)
        } else {
            commaPosition := strings.Index(row, ",")
            value, _ = strconv.Atoi(row[:commaPosition])
            row = row[commaPosition+1:]
        }
        s = append(s, value)
    }
    return s
}
</code>```

I can't figure out why the slice value is [1,2,3] then [1,2,3] then [1,3,3]. It seems like it should never change.

答:
Slices are reference-like types. When you pass it to some function and change contents of it there, it would change the original slice too.

I suggest you to read this and this to fully understand slices.

Your x := append(slice) won't create a new slice. Assuming you have a variable slice with type []int you could copy it with:

```<code>x := append(make([]int, 0), slice...)
</code>```

or without creating an empty slice

```<code>x := append([]int(nil), slice...)
</code>```

or to be more explicit

```<code>x := make([]int, len(slice))
copy(x, slice)
</code>```

Body:
I've got a []int that I range over. I get that when I iterate I have a key/value. I want to also access the slice which I'm iterating over. I don't understand why the slice changes however.

func main() {
var rows []string
rows = append(rows, "1  2   3", "4  5   6")
for _, row := range rows {
    row := formatRow(row)
    fmt.Println("sent row: ", row) // <------ THIS RETURNS [1,2,3]
    for i, _ := range row {
        fmt.Println("sent row: ", row) // <------ THIS RETURNS [1,3,3]
        _ = getShortRow(row, i)
    }
}
}

func getShortRow(row []int, i int) []int {
    if i == 0 {
        row := append(row[1:])
        return row
}
endPosition := i + 1
if endPosition == len(row) {
    row := append(row[:i])
    return row
}

st := append(row[:i])
end := append(row[i+1:])
row = append(st, end...)
return row
}

func formatRow(row string) []int {
    row = strings.Replace(row, "    ", ",", -1)
    if row[len(row)-1:] == "," {
        row = row[:len(row)-1]
    }
    nValues := strings.Count(row, ",") + 1
    var s []int
    // convert []string to []int
    for index := 0; index < nValues; index++ {
        var value int
        if index == nValues-1 {
            value, _ = strconv.Atoi(row)
        } else {
            commaPosition := strings.Index(row, ",")
            value, _ = strconv.Atoi(row[:commaPosition])
            row = row[commaPosition+1:]
        }
        s = append(s, value)
    }
    return s
}

I can't figure out why the slice value is [1,2,3] then [1,2,3] then [1,3,3]. It seems like it should never change.

Body:
Slices are reference-like types. When you pass it to some function and change contents of it there, it would change the original slice too.

I suggest you to read this and this to fully understand slices.

Your x := append(slice) won't create a new slice. Assuming you have a variable slice with type []int you could copy it with:

x := append(make([]int, 0), slice...)

or without creating an empty slice

x := append([]int(nil), slice...)

or to be more explicit

x := make([]int, len(slice))
copy(x, slice)


问:
Posts Displaying In Wrong Order
I have created a file which should fetch the latest 3 blogs from our wordpress blog and post them on the homepage of our site in DESC order. What is happening though is the Oldest blog of the three is showing first followed by the newest then the second newest. The oldest one should be last to be displayed.

```<code>$sql="SELECT title, post_name, date, content, CONCAT(LEFT(image, LENGTH(image) - LOCATE('.', REVERSE(image))),'-500x375.',SUBSTRING_INDEX(image, '.', -1)) AS image
FROM (
  SELECT
  p.post_title AS title,
  p.post_status AS 'status',
  p.post_date_gmt AS date,
  p.post_content AS content,
  p.post_name AS post_name,
  (SELECT `guid` FROM w_posts WHERE id = m.meta_value) AS image
  FROM w_posts p, w_postmeta m
  WHERE p.post_type = 'post'
  AND p.post_status = 'publish'
  AND p.id = m.post_id
  AND m.meta_key = '_thumbnail_id'
  ORDER BY date DESC
  LIMIT 3
) TT";?>
<div class="col-xs-12"><hr><h2 class="title-most-off"><a href="https://www.example.com/blogs/">Latest Blog Posts</a></h2> </div>
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {

        $title=$row['title'];
        $shortTitle = substr($title, 0, 100);
        $content=$row['content'];
        $preview = substr($content, 0, 175);
        $date=$row['date'];
        $name=$row['post_name'];
        $image=$row['image'];?>

        <div class="col-xs-12 col-md-4 post">
        <a href="https://www.example.com/blogs/<?php echo $name; ?>" target="_blank">
        <img class="img-responsive fw" src="<?php echo $image; ?>" />
        <div class="caption">
        <h4 class="blog-post-title"><?php echo $shortTitle; ?></h4>
        </div>
        </a>

      </div>
    <?php }

}?>
</code>```

Not sure why the order is not correct, the same thing happenens when I run the query in phpmyadmin the order is the same even though the date of the first shown result is before the second and third shown results. So the result is 3rd-1st-2nd instead of 1st-2nd-3rd

答:
It turns out the code was correct all along, there was an issue with the date on one of the individual posts that was causing the problem.

Thanks for the help everyone.

Title: Posts Displaying In Wrong Order

Body:
I have created a file which should fetch the latest 3 blogs from our wordpress blog and post them on the homepage of our site in DESC order. What is happening though is the Oldest blog of the three is showing first followed by the newest then the second newest. The oldest one should be last to be displayed.

$sql="SELECT title, post_name, date, content, CONCAT(LEFT(image, LENGTH(image) - LOCATE('.', REVERSE(image))),'-500x375.',SUBSTRING_INDEX(image, '.', -1)) AS image
FROM (
  SELECT
  p.post_title AS title,
  p.post_status AS 'status',
  p.post_date_gmt AS date,
  p.post_content AS content,
  p.post_name AS post_name,
  (SELECT `guid` FROM w_posts WHERE id = m.meta_value) AS image
  FROM w_posts p, w_postmeta m
  WHERE p.post_type = 'post'
  AND p.post_status = 'publish'
  AND p.id = m.post_id
  AND m.meta_key = '_thumbnail_id'
  ORDER BY date DESC
  LIMIT 3
) TT";?>

Latest Blog Posts

<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {

        $title=$row['title'];
        $shortTitle = substr($title, 0, 100);
        $content=$row['content'];
        $preview = substr($content, 0, 175);
        $date=$row['date'];
        $name=$row['post_name'];
        $image=$row['image'];?>

        <a href="https://www.example.com/blogs/<?php echo $name; ?>" target="_blank">
        <img class="img-responsive fw" src="<?php echo $image; ?>" />

<?php echo $shortTitle; ?>

    <?php }

}?>

Not sure why the order is not correct, the same thing happenens when I run the query in phpmyadmin the order is the same even though the date of the first shown result is before the second and third shown results. So the result is 3rd-1st-2nd instead of 1st-2nd-3rd


问:
How to secure the communication between API backend and SPA frontend
I am working a lot with SPAs*. Therefore I am using API based backends to get the entity data for the SPA-ORMs*. This is simple and works fine.

Now I am working on a private project that will be used by many people. I want to prevent the misusage of my APIs without the SPA. Are there ways to make it a little harder for the script-kiddies to misuse the API?

Back in my time :D I used to use simple keys to encrypt the data on a very low level. But with the current dev-tools of f.e. chrome you can easily debug anything in the SPA and how the data is getting crypted/uglified. I am just out of options here.

I am not interested in securing the connection, since SSL is good enough for me. The user password security is safe enough too (modern frameworks do good work here). I am just out of knowledge, how to make it harder to use the API without my SPA.
I am developing both ends, so I am able to make the API whatever I like - do you have tips, best practices, ideas?

Footnotes:

SPA = Single page application (like VueJS, Angular, Ember, etc.)

ORM = Object relational mapping (like VueX, ember-data, etc.)

答:
You just need to authenticate the call. Your application (or whatever else) connecting to the API would need to present an authentication token.

There are various ways to do that, you could for instance

offload the authentication to someone else via oAuth (which is a misuse of the service, OpenID should be used instead but oAuth use is common)

have a login form in your SPA which would authenticate to your API (which in turn would provide an authentication token)

A very bad way to do that (following your comment) is to obfuscate the call, hoping that nobody will discover the secret you share between your JS code and the API.


问:
Gem dependencies incompatibality during upgrade of rails 4.2.10 to rails 5.0.0
I am in a middle of a process of upgrading our rails 4 app.
Following the rails upgrade guide, I have updated current rails version in a gemfile replacing 4.2.10 with 5.0.0.

But after running bundle update rails, I am getting many incompatibility issues even after running 4.2.10 (with rails 4.2.10) which should update all gems to the latest version.

Following are the compatibility errors I am getting after running bundle update rails with rails 5.0.0 in a gemfile:

```<code>Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    active_link_to was resolved to 1.0.3, which depends on
      actionpack

    active_model_serializers was resolved to 0.10.2, which depends on
      actionpack (< 6, >= 4.1)

    inherited_resources was resolved to 1.6.0, which depends on
      actionpack (< 5, >= 3.2)

    inherited_resources was resolved to 1.6.0, which depends on
      actionpack (< 5, >= 3.2)

    kaminari was resolved to 0.17.0, which depends on
      actionpack (>= 3.0.0)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rspec-rails (= 3.6.0) was resolved to 3.6.0, which depends on
      actionpack (>= 3.0)
</code>```

答:
Finally after many trials & testing, I was able to run bundle install. Listing steps that I tried-

1. Create a new demo rails app using rails new with rails 5.

2. Remove existing Gemfile.lock.

3. Remove all current gems: (I used for i in gem list --no-versions; do gem uninstall -aIx $i; done command referenced from here.)

4. Replace existing Gemfile with the new one that was generated from creating new rails 5 app. (assuming you'll be having a backup copy of existing Gemfile.)

5. Copy individual gems from old file to the new one.

6. Run bundle install. (You should be having a :) after this execution.)

7. Run rails app:update to continue with the upgrade process.

Body:
I am in a middle of a process of upgrading our rails 4 app.
Following the rails upgrade guide, I have updated current rails version in a gemfile replacing 4.2.10 with 5.0.0.

But after running bundle update rails, I am getting many incompatibility issues even after running 4.2.10 (with rails 4.2.10) which should update all gems to the latest version.

Following are the compatibility errors I am getting after running bundle update rails with rails 5.0.0 in a gemfile:

Bundler could not find compatible versions for gem "actionpack":
  In Gemfile:
    active_link_to was resolved to 1.0.3, which depends on
      actionpack

    active_model_serializers was resolved to 0.10.2, which depends on
      actionpack (< 6, >= 4.1)

    inherited_resources was resolved to 1.6.0, which depends on
      actionpack (< 5, >= 3.2)

    inherited_resources was resolved to 1.6.0, which depends on
      actionpack (< 5, >= 3.2)

    kaminari was resolved to 0.17.0, which depends on
      actionpack (>= 3.0.0)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rails (= 5.0.0) was resolved to 5.0.0, which depends on
      actionpack (= 5.0.0)

    rspec-rails (= 3.6.0) was resolved to 3.6.0, which depends on
      actionpack (>= 3.0)


问:
How can I add attributes to a public method in an F# type?
I'm just trying out F# for the first time, and playing around with its interop with C# projects.

I have custom attributes defined in a C# project, and added a reference to that project in my new F# project. When I attempt to define the attributes to a "let" statement, the "let" is permanently private and so it doesn't matter that the attributes work. When I attempt to change the "let" statement to something else, say, "member", I'm told the attributes can't target the object. How should I be defining the function if I want it to be public and have attributes?

```<code>module FSharp

type public MyClass() =
    class
        //this one will get the attributes, but is always private and can't be made public
        [<Core.NameAttribute("F# name")>]
        [<Core.DescriptionAttribute("F# desc")>]
        let f1 = "test from F#"

        //this one won't get the attributes, but is public and does return the value
        member this.Function1 = f1
    end
</code>```

As I've stated in the code, I seem to have a problem. My attributes are set to only target methods, and I can set them on "let" statements, but not "member" statements. I'm sure this is something silly, but I thank you in advance for your help!

答:
Try this:</p>

```<code>type myAttribute() =
    inherit System.Attribute()
    ;

type test() =
    [<myAttribute()>]
    member this.func() = "test from f#"
</code>```

Body:
I'm just trying out F# for the first time, and playing around with its interop with C# projects.

I have custom attributes defined in a C# project, and added a reference to that project in my new F# project. When I attempt to define the attributes to a "let" statement, the "let" is permanently private and so it doesn't matter that the attributes work. When I attempt to change the "let" statement to something else, say, "member", I'm told the attributes can't target the object. How should I be defining the function if I want it to be public and have attributes?

module FSharp

type public MyClass() =
    class
        //this one will get the attributes, but is always private and can't be made public
        [<Core.NameAttribute("F# name")>]
        [<Core.DescriptionAttribute("F# desc")>]
        let f1 = "test from F#"

        //this one won't get the attributes, but is public and does return the value
        member this.Function1 = f1
    end

As I've stated in the code, I seem to have a problem. My attributes are set to only target methods, and I can set them on "let" statements, but not "member" statements. I'm sure this is something silly, but I thank you in advance for your help!

Body:
Try this:

type myAttribute() =
    inherit System.Attribute()
    ;

type test() =
    [<myAttribute()>]
    member this.func() = "test from f#"


问:
What alternative is available to nth-child to select divs within other elements?
I have a HTML structure like so in my . I assumed nth-child was the way to go:

```<code>   <nav>
    <article class="menu-items">
    <div class="row">
      <ul class="col-6 column">
        <!-- primary nav group one -->
        <li class="primary-nav">Home</li>
        <li class="primary-nav">News</li>
      </ul>
      <ul class="col-6 column right align-right">
        <!-- primary nav group two -->
        <li class="primary-nav">About</li>
        <li class="primary-nav">Contact</li>
      </ul>
    </div>
    <div class="row">
      <!-- primary nav group three -->
      <h1 class="primary-nav">Connect Online</h1>
      <ul class="col-6 column submenu-items">
        <li class="primary-nav"><a href="/">Twitter</a></li>
        <li class="primary-nav"><a href="/">Instagram</a></li>
      </ul>
      <ul class="col-6 column right submenu-items align-right">
        <!-- primary nav group four -->
        <li class="primary-nav"><a href="/">Facebook</a></li>
        <li class="primary-nav"><a href="/">Sq</a></li>
      </ul>
    </div>
  </article>
 </nav>
</code>```

And some CSS to trigger a transform after a delay

```<code>.primary-nav:nth-child(n) {
    transition-delay: 400ms;
}
.primary-nav:nth-child(2n) {
    transition-delay: 400ms;
}
.primary-nav:nth-child(3n) {
    transition-delay: 700ms;
}
.primary-nav:nth-child(4n) {
    transition-delay: 700ms;
}
.primary-nav:nth-child(5n) {
    transition-delay: 900ms;
}
/* and so on */
</code>```

MDN: The :nth-child() CSS pseudo-class matches one or more elements based on their position among a group of siblings

I can't use nth-child here because primary-nav are among different groups. When the end of the first group is reached, it will restart over. Makes sense. (odd) or (even) won't be much use here either.

How can I taget each .primary-nav div here? Can I do it without JS?

答:
I am not sure if its a suitable solution for you but I think you can do this with Jquery.

```<code>var navDivs = $(".your-class-name").find(".primary-nav"); //Gives the list of divs who have the class .primary-nav.
</code>```

Or, you can give an id to your div and search by ID

```<code> var navDivs = $("#your-parent-div-id").find(".primary-nav"); //Gives the list of divs who have the class .primary-nav.
</code>```

and finally by a for loop you can set any property of items by JQuery:

```<code> for (var i = 0; i < navDivs.length; i++) {
  var div = navDivs[i];
  $(div).css("your-css-property", "your-css-value");
}
</code>```

Body:
I have a HTML structure like so in my . I assumed nth-child was the way to go:

Home

News

About

Contact

Connect Online

Twitter

Instagram

Facebook

Sq

And some CSS to trigger a transform after a delay

.primary-nav:nth-child(n) {
    transition-delay: 400ms;
}
.primary-nav:nth-child(2n) {
    transition-delay: 400ms;
}
.primary-nav:nth-child(3n) {
    transition-delay: 700ms;
}
.primary-nav:nth-child(4n) {
    transition-delay: 700ms;
}
.primary-nav:nth-child(5n) {
    transition-delay: 900ms;
}
/* and so on */

MDN: The :nth-child() CSS pseudo-class matches one or more elements based on their position among a group of siblings

I can't use nth-child here because primary-nav are among different groups. When the end of the first group is reached, it will restart over. Makes sense. (odd) or (even) won't be much use here either.

How can I taget each .primary-nav div here? Can I do it without JS?

Body:
I am not sure if its a suitable solution for you but I think you can do this with Jquery.

var navDivs = $(".your-class-name").find(".primary-nav"); //Gives the list of divs who have the class .primary-nav.

Or, you can give an id to your div and search by ID

 var navDivs = $("#your-parent-div-id").find(".primary-nav"); //Gives the list of divs who have the class .primary-nav.

and finally by a for loop you can set any property of items by JQuery:

 for (var i = 0; i < navDivs.length; i++) {
  var div = navDivs[i];
  $(div).css("your-css-property", "your-css-value");
}


问:
Prevent hover effect from looping
I made a hover effect which toggles a top block to slide up/down at the same time the bottom block slides up / down.

As you can see in the Fiddle: https://jsfiddle.net/wmaL1pm5/1/

However, if you swipe your mouse fast on and off the block the hover effects keeps repeating even if you are not on that block anymore.

In my HTML I have 2 row's with each 3 row containing 3 of these blocks. If you swipe your mouse of these rows all of the blocks are repeating their hover effect.

How can I prevent the hover effect from looping if you hover another block or if your mouse is on the current block.

Below my current jQuery code:

```<code>$(".usp-hover").mouseenter( function(){
     $( this ).find( ".usp-block-title" ).slideToggle('slow')
     $( this ).find( ".usp-block-hover" ).removeClass("usp-block-hidden");
     $( this ).find( ".usp-block-hover" ).slideDown('slow')
});

$(".usp-hover").mouseleave( function(){
     $( this ).find( ".usp-block-title" ).slideToggle('slow')
     $( this ).find( ".usp-block-hover" ).slideToggle('slow')
});
</code>```

答:
you must Stop the currently-running animation on the matched elements.

```<code>$(".usp-hover").mouseleave( function(){
    $( this ).find( ".usp-block-title" ).stop( true, true ).slideToggle('slow')
    $( this ).find( ".usp-block-hover" ).stop( true, true ).slideToggle('slow')
});
</code>```

Title: Prevent hover effect from looping

Body:
I made a hover effect which toggles a top block to slide up/down at the same time the bottom block slides up / down.

As you can see in the Fiddle: https://jsfiddle.net/wmaL1pm5/1/

However, if you swipe your mouse fast on and off the block the hover effects keeps repeating even if you are not on that block anymore.

In my HTML I have 2 row's with each 3 row containing 3 of these blocks. If you swipe your mouse of these rows all of the blocks are repeating their hover effect.

How can I prevent the hover effect from looping if you hover another block or if your mouse is on the current block.

Below my current jQuery code:

$(".usp-hover").mouseenter( function(){
     $( this ).find( ".usp-block-title" ).slideToggle('slow')
     $( this ).find( ".usp-block-hover" ).removeClass("usp-block-hidden");
     $( this ).find( ".usp-block-hover" ).slideDown('slow')
});

$(".usp-hover").mouseleave( function(){
     $( this ).find( ".usp-block-title" ).slideToggle('slow')
     $( this ).find( ".usp-block-hover" ).slideToggle('slow')
});

Body:
you must Stop the currently-running animation on the matched elements.

$(".usp-hover").mouseleave( function(){
    $( this ).find( ".usp-block-title" ).stop( true, true ).slideToggle('slow')
    $( this ).find( ".usp-block-hover" ).stop( true, true ).slideToggle('slow')
});


问:
replace   characters that are hidden in text
How to remove   (that are hidden) and SPACES in below text but

hold UNICODE characters

hold
 tag

i tested:

i used trim($string) => NOT WORKED

i used str_replace(' ', '', $string) => NOT WORKED

i used some regex => NOT WORKED

```<code>            <br>تاريخ ورود: یکشنبه ۲۳ بهمن ماه ۱۳۹۰
</code>```

UPDATE:
Thanks

答:
All solutions above kind of work, until one starts to work with German language where there are such letters:

```<code>ä ä
</code>```

and othere simial ones.
I use the following code:

```<code>$string = preg_replace ( "!\s++!u", ' ', $string );
</code>```

More details here: PCRE(3) Library Functions Manual

Body:
How to remove   (that are hidden) and SPACES in below text but

hold UNICODE characters

hold
 tag

i tested:

i used trim($string) => NOT WORKED

i used str_replace(' ', '', $string) => NOT WORKED

i used some regex => NOT WORKED

تاريخ ورود: یکشنبه ۲۳ بهمن ماه ۱۳۹۰

UPDATE:
Thanks

Body:
All solutions above kind of work, until one starts to work with German language where there are such letters:

ä &auml;

and othere simial ones.
I use the following code:

$string = preg_replace ( "!\s++!u", ' ', $string );

More details here: PCRE(3) Library Functions Manual