答:
Use ORDER BY and a limit the result set to one row:

```<code>SELECT tfs.type , SUM(tfs.price) AS TotalProfit
FROM ticketsforsale tfs INNER JOIN
     transactions t
     ON tfs.ticket_id = t.ticket_id
GROUP BY tfs.type
ORDER BY TotalProfit DESC
FETCH FIRST 1 ROW ONLY;
</code>```

Note that I introduced table aliases as well, so the query is easier to write and to read.

Based on this query, you don't seem to need the JOIN:

```<code>SELECT tfs.type , SUM(tfs.price) AS TotalProfit
FROM ticketsforsale tfs
GROUP BY tfs.type
ORDER BY TotalProfit DESC
FETCH FIRST 1 ROW ONLY;
</code>```

Title: How to show ONLY the max value of a inner join table column?

Body:
I used INNER JOIN on two tables :

Transactions
 - transaction_id (PK)
 -ticket_id (FK) reference to ticketsforsale

Ticketsforsale :
 - ticket_id (PK)
 - type
 - price

(there are more columns in each table but serve no purpose for this question)

The query i tried is the following :

SELECT ticketsforsale.type , SUM(ticketsforsale.price) AS TotalProfit
   FROM ticketsforsale INNER JOIN transactions
   ON ticketsforsale.ticket_id = transactions.ticket_id
GROUP BY ticketsforsale.type

The result is :
  Sports | 300
  Cruise | 600
  Theater| 100

I tried using this line in the query

WHERE TotalProfit = SELECT(MAX(TotalProfit)

But I can't figure out the right place for this line.

What i want the query to do is to show only the ROW containing the max value of "TotalProfit" . I am just missing the right MAX function usage on this query , thanks !

Body:
Use ORDER BY and a limit the result set to one row:

SELECT tfs.type , SUM(tfs.price) AS TotalProfit
FROM ticketsforsale tfs INNER JOIN
     transactions t
     ON tfs.ticket_id = t.ticket_id
GROUP BY tfs.type
ORDER BY TotalProfit DESC
FETCH FIRST 1 ROW ONLY;

Note that I introduced table aliases as well, so the query is easier to write and to read.

Based on this query, you don't seem to need the JOIN:

SELECT tfs.type , SUM(tfs.price) AS TotalProfit
FROM ticketsforsale tfs
GROUP BY tfs.type
ORDER BY TotalProfit DESC
FETCH FIRST 1 ROW ONLY;


来源: stackexchange

问:
Why does componentDidMount not execute when I navigate to initial route from other screen?
I'm using react-navigation for my mobile app and I have 2 routes- Home and Favoriti, where Home is initial route. Both of those components have componentDidMount. Whenever I navigate to Favoriti from Home, Favoriti component mounts, but when I navigate back to Home, its componentDidMount doesn't execute. It only executes the first time I open the app, but I need it to mount every time I navigate to it.

```<code>import { createStackNavigator, createAppContainer} from 'react-navigation';
import  Home  from './views/Home';
import Favoriti from './views/Favoriti';

const MainNavigator = createStackNavigator({

    FavoritiRT: Favoriti,
    HomeRT: Home
  },
  {
    initialRouteName: "HomeRT"
  }
);

const MyRoutes = createAppContainer(MainNavigator);

export default MyRoutes;
</code>```

There is no error showing, it's just that componentDidMount of initial route doesn't execute every time I navigate to it, but with other routes it does.

答:
"componentDidMount" does not run again because the "Home" component has already been created and will continue to exist as long as it is in the stack. That instance of the Home component will be reused and the user will continue where they left off when they go back to that Home component. To run componentDidMount again you need to start a new instance of the Home component.

Instead of using the back button. Create a button and in the onPress prop navigate to a new instance of Home using the push method.

```<code><Button
  title="Home"
  onPress={() => this.props.navigation.push('Home')}
/>
</code>```

https://reactnavigation.org/docs/en/navigating.html#going-back

Edit:

While this will get your app running for now; sfratini makes a good point and his answer will be better for you if you end up working for a company/client or publish your own app. Adding a listener would be ideal for all the reasons he said.

ContentLicense: CC BY-SA 4.0

Body:
I'm using react-navigation for my mobile app and I have 2 routes- Home and Favoriti, where Home is initial route. Both of those components have componentDidMount. Whenever I navigate to Favoriti from Home, Favoriti component mounts, but when I navigate back to Home, its componentDidMount doesn't execute. It only executes the first time I open the app, but I need it to mount every time I navigate to it.

import { createStackNavigator, createAppContainer} from 'react-navigation';
import  Home  from './views/Home';
import Favoriti from './views/Favoriti';

const MainNavigator = createStackNavigator({

    FavoritiRT: Favoriti,
    HomeRT: Home
  },
  {
    initialRouteName: "HomeRT"
  }
);

const MyRoutes = createAppContainer(MainNavigator);

export default MyRoutes;

There is no error showing, it's just that componentDidMount of initial route doesn't execute every time I navigate to it, but with other routes it does.

Body:
"componentDidMount" does not run again because the "Home" component has already been created and will continue to exist as long as it is in the stack. That instance of the Home component will be reused and the user will continue where they left off when they go back to that Home component. To run componentDidMount again you need to start a new instance of the Home component.

Instead of using the back button. Create a button and in the onPress prop navigate to a new instance of Home using the push method.

<Button
  title="Home"
  onPress={() => this.props.navigation.push('Home')}
/>

https://reactnavigation.org/docs/en/navigating.html#going-back

Edit:

While this will get your app running for now; sfratini makes a good point and his answer will be better for you if you end up working for a company/client or publish your own app. Adding a listener would be ideal for all the reasons he said.


问:
Fetch and Update large population of Entity records in Console app
Looking for the best approach to fetch and update the entities in bulk. Please suggest best approach to deal with this requirement, I am fetching List of Guids (~80K+) from an external database and want to update an entity in CRM by increment the counter integer field and setting one option set field. So far as per my understanding following are the possible approaches :

Using Early-bound classes - Querying the context in batches by passing 5K entity id at once and then looping through the entitylist and update the entity context with-in foreach loop.

Using QueryExpression - Passing the Guid ids in batch/page of 5k in query expression using ConditionOperator.In operator, retriveMultipleRespone and then loop through the entities and preparing the updaterequest collection and call executeMultiple again repeat the same for remaining pages.

Please suggest which approach will better or any-other approach to handling it more efficient way. Can we use multi-threading here ?

答:
Early bound classes simply provide strong typing for CRM objects and Early vs Late Bound has little or no effect on performance. In both cases you would want to use a RetrieveMultiple operation to get the records, and an ExecuteMultiple operation to update them. Since you already have the Guids, you may not need to retrieve the records before you update them, this would obviously improve performance.

From the Microsoft documentation on ExecuteMultiple the operation has the following pertinent limitations:
https://learn.microsoft.com/en-us/dynamics365/customer-engagement/developer/org-service/use-executemultiple-improve-performance-bulk-data-load

- There is a limit of 2 concurrent ExecuteMultiple requests per organization

- The default max batch size for ExecuteMultiple is 1k records

Both of these settings can be changed on the org level

You can use multi-threading, and it might improve performance, but I don't have much experience in this area. For only 80k records you probably don't need to bother.


问:
Curved geojson polygon edges on map projections
I am trying to draw rectangles on different map projections using d3.js and geojson. The mapped coordinates seem right, however the edges appear curved in a strange way. I understand that this may have to do with the shortest path on the real Earth, but what I would like is that the edges follow the parallels/meridians graticule of the projection. Is there a way to do that? Can anyone help?

Example: Aitoff Projection
Example: Mercator
Here is the code I am using:

```<code><!DOCTYPE html>
<html>

<head>
  <title>World Map</title>
  <meta charset="utf-8">

  <script src="https://d3js.org/d3-geo-projection.v2.min.js"></script>

  <script src="https://d3js.org/d3.v4.min.js"></script>
  <script src="https://d3js.org/topojson.v2.min.js"></script>
  <style>
    path {
      fill: red;
      stroke: #000;
      stroke-width: .1px;
    }
    .graticule {
      fill: none;
      stroke: #000;
      stroke-width: .2px;
    }
    .foreground {
      fill: none;
      stroke: #333;
      stroke-width: 1.2px;
    }

  </style>
</head>

<body>
  <svg width="960" height="600"></svg>
  <script>
    const svg = d3.select("svg")
    const myProjection = d3.geoMercator()
    const path = d3.geoPath().projection(myProjection)
    const graticule = d3.geoGraticule()

    const geojson = {

"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": {
    "color": "blue"
},
"geometry": {
    "type": "Polygon",
    "coordinates": [[[-80.0, 50.0], [-20.0, 50.0], [-20.0, -10.0], [-80.0, -10.0], [-80.0, 50.0]]]
} }
]
}
    function drawMap(err, world) {
      if (err) throw err

      svg.append("g")
        .selectAll("path")
        .data(topojson.feature(world, world.objects.land).features)
        .enter().append("path")
        .attr("d", path);

      svg.append("path")
        .datum(graticule)
        .attr("class", "graticule")
        .attr("d", path);

      svg.append("path")
        .datum(graticule.outline)
        .attr("class", "foreground")
        .attr("d", path);

      svg.append("g")
        .selectAll("path")
        .data(geojson.features)
        .enter().append("path")
        .attr("d", path)

    }
    d3.json("https://unpkg.com/world-atlas@1.1.4/world/50m.json", drawMap)

  </script>
</body>

</html>
</code>```

答:
Your assumption is right: d3 uses great circle distances to draw lines: this means that any path between two points using a d3 geoProjection and geoPath follows the shortest real world path between those two points. This means:

that the same path between two points aligns with other geographic points and features no matter the projection

that the anti-meridian can be accounted for

and the resulting map more accurately depicts lines.

To draw straight lines and/or lines that follow parallels (meridians are the shortest path between two points that fall on them - so paths follow this already, assuming an unrotated graticule) there are a few possibilities.

The easiest solution is to use a cylindrical projection like a Mercator to create a custom geoTransform. d3.geoTransforms do not use spherical geometry, unlike d3.geoProjections, instead they use Cartesian data. Consequently they don't sample along lines to create curved lines: this is unecessary when working with Cartesian data. This allows us to use spherical geometry for the geojson vertices within the geoTransform while still keeping straight lines on the map:

```<code>var transform = d3.geoTransform({
    point: function(x, y) {
      var projection = d3.geoMercator();
      this.stream.point(...projection([x,y]));
    }
});
</code>```

As seen below:

var projection = d3.geoMercator();

var transform = d3.geoTransform({
    point: function(x, y) {
      var projection = d3.geoMercator();
      this.stream.point(...projection([x,y]));
    }
});

var color = ["steelblue","orange"]

var geojson = {type:"LineString",coordinates:[[-160,60],[30,45]]};
var geojson2 = {type:"Polygon",coordinates:[[[-160,60,],[-80,60],[-100,30],[-160,60]]]}

var svg = d3.select("body")
  .append("svg")
  .attr("width",960)
  .attr("height",500);

svg.selectAll(null)
  .data([projection,transform])
  .enter()
  .append("path")
  .attr("d", function(d) {
    return d3.geoPath().projection(d)(geojson)
  })
  .attr("fill","none")
  .attr("stroke",function(d,i) { return color[i]; } )
  .attr("stroke-width",1);

svg.selectAll(null)
  .data([projection,transform])
  .enter()
  .append("path")
  .attr("d", function(d) {
    return d3.geoPath().projection(d)(geojson2)
  })
  .attr("fill","none")
  .attr("stroke",function(d,i) { return color[i]; } )
  .attr("stroke-width",2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script></code>```

The orange lines use the transform, the blue lines use a plain Mercator

In some cases you could set the precision of the projection (which regulates the adaptive sampling) to some absurdly high number, this will work for some lines, but not others due to things like anti-meridian cutting:

var projection = d3.geoMercator().precision(1000000);

var transform = d3.geoTransform({
    point: function(x, y) {
      var projection = d3.geoMercator();
      this.stream.point(...projection([x,y]));
    }
});

var color = ["steelblue","orange"]

var geojson = {type:"LineString",coordinates:[[-160,60],[30,45]]};
var geojson2 = {type:"Polygon",coordinates:[[[-160,60,],[-80,60],[-100,30],[-160,60]]]}

var svg = d3.select("body")
  .append("svg")
  .attr("width",960)
  .attr("height",500);

svg.selectAll(null)
  .data([projection,transform])
  .enter()
  .append("path")
  .attr("d", function(d) {
    return d3.geoPath().projection(d)(geojson)
  })
  .attr("fill","none")
  .attr("stroke",function(d,i) { return color[i]; } )
  .attr("stroke-width",1);

svg.selectAll(null)
  .data([projection,transform])
  .enter()
  .append("path")
  .attr("d", function(d) {
    return d3.geoPath().projection(d)(geojson2)
  })
  .attr("fill","none")
  .attr("stroke",function(d,i) { return color[i]; } )
  .attr("stroke-width",2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script></code>```

Neither approach works if you want to draw lines that are aligned with parallels on a non-cylindrical projection. For a cylindrical projection parallels are straight. The above approaches will only create straight lines. If the parallels aren't projected straight, such as the Aitoff, the lines will not align with the graticule.

To have a line follow a parallel you will need to sample points along your paths  because the projected parallels will not all be straight and parallels don't follow great circle distance. Therefore neither the default projection nor the method above will work in these instances.

When sampling you will need to treat the data as Cartesian - essentially using a cylindrical projection (Plate Carree) to have lines follow parallels.

Body:
I am trying to draw rectangles on different map projections using d3.js and geojson. The mapped coordinates seem right, however the edges appear curved in a strange way. I understand that this may have to do with the shortest path on the real Earth, but what I would like is that the edges follow the parallels/meridians graticule of the projection. Is there a way to do that? Can anyone help?

Example: Aitoff Projection
Example: Mercator
Here is the code I am using:

<!DOCTYPE html>

  <title>World Map</title>
  <meta charset="utf-8">

  <svg width="960" height="600"></svg>

Body:
Your assumption is right: d3 uses great circle distances to draw lines: this means that any path between two points using a d3 geoProjection and geoPath follows the shortest real world path between those two points. This means:

that the same path between two points aligns with other geographic points and features no matter the projection

that the anti-meridian can be accounted for

and the resulting map more accurately depicts lines.

To draw straight lines and/or lines that follow parallels (meridians are the shortest path between two points that fall on them - so paths follow this already, assuming an unrotated graticule) there are a few possibilities.

The easiest solution is to use a cylindrical projection like a Mercator to create a custom geoTransform. d3.geoTransforms do not use spherical geometry, unlike d3.geoProjections, instead they use Cartesian data. Consequently they don't sample along lines to create curved lines: this is unecessary when working with Cartesian data. This allows us to use spherical geometry for the geojson vertices within the geoTransform while still keeping straight lines on the map:

var transform = d3.geoTransform({
    point: function(x, y) {
      var projection = d3.geoMercator();
      this.stream.point(...projection([x,y]));
    }
});

As seen below:

var projection = d3.geoMercator();

var transform = d3.geoTransform({
    point: function(x, y) {
      var projection = d3.geoMercator();
      this.stream.point(...projection([x,y]));
    }
});

var color = ["steelblue","orange"]

var geojson = {type:"LineString",coordinates:[[-160,60],[30,45]]};
var geojson2 = {type:"Polygon",coordinates:[[[-160,60,],[-80,60],[-100,30],[-160,60]]]}

var svg = d3.select("body")
  .append("svg")
  .attr("width",960)
  .attr("height",500);

svg.selectAll(null)
  .data([projection,transform])
  .enter()
  .append("path")
  .attr("d", function(d) {
    return d3.geoPath().projection(d)(geojson)
  })
  .attr("fill","none")
  .attr("stroke",function(d,i) { return color[i]; } )
  .attr("stroke-width",1);

svg.selectAll(null)
  .data([projection,transform])
  .enter()
  .append("path")
  .attr("d", function(d) {
    return d3.geoPath().projection(d)(geojson2)
  })
  .attr("fill","none")
  .attr("stroke",function(d,i) { return color[i]; } )
  .attr("stroke-width",2);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

The orange lines use the transform, the blue lines use a plain Mercator

In some cases you could set the precision of the projection (which regulates the adaptive sampling) to some absurdly high number, this will work for some lines, but not others due to things like anti-meridian cutting:

var projection = d3.geoMercator().precision(1000000);

var transform = d3.geoTransform({
    point: function(x, y) {
      var projection = d3.geoMercator();
      this.stream.point(...projection([x,y]));
    }
});

var color = ["steelblue","orange"]

var geojson = {type:"LineString",coordinates:[[-160,60],[30,45]]};
var geojson2 = {type:"Polygon",coordinates:[[[-160,60,],[-80,60],[-100,30],[-160,60]]]}

var svg = d3.select("body")
  .append("svg")
  .attr("width",960)
  .attr("height",500);

svg.selectAll(null)
  .data([projection,transform])
  .enter()
  .append("path")
  .attr("d", function(d) {
    return d3.geoPath().projection(d)(geojson)
  })
  .attr("fill","none")
  .attr("stroke",function(d,i) { return color[i]; } )
  .attr("stroke-width",1);

svg.selectAll(null)
  .data([projection,transform])
  .enter()
  .append("path")
  .attr("d", function(d) {
    return d3.geoPath().projection(d)(geojson2)
  })
  .attr("fill","none")
  .attr("stroke",function(d,i) { return color[i]; } )
  .attr("stroke-width",2);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Neither approach works if you want to draw lines that are aligned with parallels on a non-cylindrical projection. For a cylindrical projection parallels are straight. The above approaches will only create straight lines. If the parallels aren't projected straight, such as the Aitoff, the lines will not align with the graticule.

To have a line follow a parallel you will need to sample points along your paths  because the projected parallels will not all be straight and parallels don't follow great circle distance. Therefore neither the default projection nor the method above will work in these instances.

When sampling you will need to treat the data as Cartesian - essentially using a cylindrical projection (Plate Carree) to have lines follow parallels.


问:
using prepared statements and fetchAll() to display to a table
I'm trying to get my code SQL Injection safe, I am having trouble converting the pdo data to an array then comparing row data.

I have been reading up on how to prevent sql injection as well as fetchAll() documentation and
how to handle SELECT statements with pdo.

Here is the relevant code. I believe it prepares the statement, then executes it, then the table is fetched and stored in $data where it is handed to $row, and then it looks up the player column and compares it with the logged in user to get the context based code to run. Where is the issue?

$stmt = $pdo->prepare("SELECT * FROM userdata");

$stmt->execute();

$data = $stmt->fetchAll();

echo "

username
words

";

while($row = $data)
{
echo $row['player'];
echo "
";
echo "" . $row['player'] . "	";
if($row['player'] == $logedInUsername)
{
    echo "" . $row['words'] . " edit	";
}
else
{
    echo "" . $row['words'] . "	";
}
echo "
";
}
echo "
";

```

<p>My current error is reoccurring, here is the segment which the while loop keeps printing.</p>

```Notice: Undefined index: player on line 41

Notice: Undefined index: player on line 43

Notice: Undefined index: player on line 44

Notice: Undefined index: words on line 50

Notice: Undefined index: player on line 41

Notice: Undefined index: player on line 43

Notice: Undefined index: player on line 44

Notice: Undefined index: words on line 50
```

答:
You have got two options. Either change the while loop to a foreach loop as @NigelRen suggested or use fetch method to fetch each record one by one from DB.

```<code>foreach ( $data as $row) {
    // ...
}
// or
// Remove $data = $stmt->fetchAll();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    // ...
}
</code>```

Body:
I'm trying to get my code SQL Injection safe, I am having trouble converting the pdo data to an array then comparing row data.

I have been reading up on how to prevent sql injection as well as fetchAll() documentation and
how to handle SELECT statements with pdo.

Here is the relevant code. I believe it prepares the statement, then executes it, then the table is fetched and stored in $data where it is handed to $row, and then it looks up the player column and compares it with the logged in user to get the context based code to run. Where is the issue?

$stmt = $pdo->prepare("SELECT * FROM userdata");

$stmt->execute();

$data = $stmt->fetchAll();

echo "

username
words

";

while($row = $data)
{
echo $row['player'];
echo "
";
echo "" . $row['player'] . "	";
if($row['player'] == $logedInUsername)
{
    echo "" . $row['words'] . " edit	";
}
else
{
    echo "" . $row['words'] . "	";
}
echo "
";
}
echo "
";

My current error is reoccurring, here is the segment which the while loop keeps printing.

Notice: Undefined index: player on line 41

Notice: Undefined index: player on line 43

Notice: Undefined index: player on line 44

Notice: Undefined index: words on line 50

Notice: Undefined index: player on line 41

Notice: Undefined index: player on line 43

Notice: Undefined index: player on line 44

Notice: Undefined index: words on line 50

Body:
You have got two options. Either change the while loop to a foreach loop as @NigelRen suggested or use fetch method to fetch each record one by one from DB.

foreach ( $data as $row) {
    // ...
}
// or
// Remove $data = $stmt->fetchAll();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    // ...
}


问:
How to handle TokenMistmatchException in axios
A token mistmatch occurs when the page stays for so long till session variable expires...

I can handle this exception in  handler.php under exceptions in normal laravel blade files but having problems handling this error with axios post request in vue.js.

I have tried using

try..catch (TokenMistsmatchException $e)

but I still cant get a json reaponse in my axios response callback.

I am trying to find solutions in these ways

Either I find a way to refresh the token when expired before the exception gets triggered

To get a response to my axios callback so I reload the page from within my vue template.

Your helps will be much appreciated

答:
In your app/Exceptions/Handler.php file

Add a handler for TokenMismatchException in the render method

```<code>public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
    if ($request->expectsJson()) {
        return response()->json([
            'error' => 'Token mismatch'
        ], $exception->getStatusCode());
    };
}

return parent::render($request, $exception);
}
</code>```

After this you can catch errors in axios like

```<code>axios.post(pathname", { body:body })
     .catch(error => {
         handle error / Display error message
     })
     .then(({ data }) => {
         If successfully request performed
     });
</code>```

Body:
In your app/Exceptions/Handler.php file

Add a handler for TokenMismatchException in the render method

public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
    if ($request->expectsJson()) {
        return response()->json([
            'error' => 'Token mismatch'
        ], $exception->getStatusCode());
    };
}

return parent::render($request, $exception);
}

After this you can catch errors in axios like

axios.post(pathname", { body:body })
     .catch(error => {
         handle error / Display error message
     })
     .then(({ data }) => {
         If successfully request performed
     });


问:
How to listen on load event when using turbolinks in rails?
I am using Rails with turbolinks. I want to trigger some script on load page event. The problem is that TL does not fire this event on page navigation. This log does not happen on page navigation:

```<code>window.addEventListener('load', (event) => {
  console.log('load');
});
</code>```

It get fire on full page refresh. But that does not helps.

My goal is to scroll on certain #id (using anchor at the end of link) after all content of the page loads (mainly images). Without this event images change scroll positions after fully images loaded.

Github to something about it. For example this link:
https://github.com/uBlockOrigin/uBlock-issues/issues/338#issuecomment-452847292
will scroll to the comment even though there is image just before it.

Is there away to achieve this using TL or any other way?

答:
To install behavior, or to perform more complex operations when the page changes, avoid script elements and use the turbolinks:load event instead

source https://github.com/turbolinks/turbolinks

For older versions page:change

Body:
I am using Rails with turbolinks. I want to trigger some script on load page event. The problem is that TL does not fire this event on page navigation. This log does not happen on page navigation:

window.addEventListener('load', (event) => {
  console.log('load');
});

It get fire on full page refresh. But that does not helps.

My goal is to scroll on certain #id (using anchor at the end of link) after all content of the page loads (mainly images). Without this event images change scroll positions after fully images loaded.

Github to something about it. For example this link:
https://github.com/uBlockOrigin/uBlock-issues/issues/338#issuecomment-452847292
will scroll to the comment even though there is image just before it.

Is there away to achieve this using TL or any other way?


问:
How to get the id of span which is deep inside li when the li is clicked
```<code> <li class="service">
                    <div class="name">>
                       <span class="price"></span>
                       Stock<span class="stock" id="ds"></span>
                    </div>
</li>
 <li class="service">
                    <div class="name">>
                       <span class="price"></span>
                       Stock<span class="stock" id="ju"></span>
                    </div>
</li>
 <li class="service">
                    <div class="name">>
                       <span class="price"></span>
                       Stock<span class="stock" id="zx"></span>
                    </div>
</li>
</code>```

I want to get the id of the span which has the class name stock depending on the li clicked

```<code>$("li").click(function() {

        });
</code>```

答:
You can use the this keyword within the click event handler to refer to the li which was clicked. From there you can use find() to retrieve the span you require before calling prop() to get the id. Try this:

$("li").click(function() {
  var id = $(this).find('.stock').prop('id');
  console.log(id);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="service">
    <div class="name">>
      <span class="price"></span>
      Stock <span class="stock" id="ds"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">>
      <span class="price"></span>
      Stock <span class="stock" id="ju"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">>
      <span class="price"></span>
      Stock <span class="stock" id="zx"></span>
    </div>
  </li>
</ul></code>```

Body:
>

                       Stock

>

                       Stock

>

                       Stock

I want to get the id of the span which has the class name stock depending on the li clicked

$("li").click(function() {

        });

Body:
You can use the this keyword within the click event handler to refer to the li which was clicked. From there you can use find() to retrieve the span you require before calling prop() to get the id. Try this:

$("li").click(function() {
  var id = $(this).find('.stock').prop('id');
  console.log(id);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="service">
    <div class="name">>
      <span class="price"></span>
      Stock <span class="stock" id="ds"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">>
      <span class="price"></span>
      Stock <span class="stock" id="ju"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">>
      <span class="price"></span>
      Stock <span class="stock" id="zx"></span>
    </div>
  </li>
</ul>


问:
Zoom automatically returns to its initial zoomlevel
My objective is to make a map in which the user location is shown with annotation and zoom, everything is ok, the location is there with a red annotation and a pretty zoom, for that I have a view which is called PositionActuelleViewController, here is my code :

PositionActuelleViewController.h :

```<code>@interface PositionActuelleViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate> {

        MKMapView                   *mapView;
            MKReverseGeocoder           *geoCoder;
        MKPlacemark         *mPlacemark;
        CLLocationCoordinate2D  location;

       }
@property (nonatomic,retain)IBOutlet MKMapView *mapView;

@end
</code>```

PositionActuelleViewController.m :

```<code>    - (void)viewDidLoad {
        [super viewDidLoad];
        [mapView setShowsUserLocation:TRUE];
        [mapView setMapType:MKMapTypeStandard];
        [mapView setDelegate:self];
        [self.view insertSubview:mapView atIndex:0];
        CLLocationManager *locationManager=[[CLLocationManager alloc] init];
        [locationManager setDelegate:self];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
        [locationManager startUpdatingLocation];
    }

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

    location = newLocation.coordinate;
    MKCoordinateRegion region;
    region.center = location;
    MKCoordinateSpan span;
    span.latitudeDelta = .005;
    span.longitudeDelta = .005;
    region.span = span;
    [mapView setRegion:region animated:TRUE];

}
</code>```

My only problem is that the zoom in is always enabled even if the user zoom out the map, it zoomed in automatically. How can I fix this?

答:
Your code in didUpdateToLocation sets a span of a fixed value. Every time that delegate call is invoked it will set the zoom based on those .005 spans.

If you simply put a breakpoint or log in the function you'll see it generally gets called quite frequently.

ContentLicense: CC BY-SA 3.0

Body:
My objective is to make a map in which the user location is shown with annotation and zoom, everything is ok, the location is there with a red annotation and a pretty zoom, for that I have a view which is called PositionActuelleViewController, here is my code :

PositionActuelleViewController.h :

@interface PositionActuelleViewController : UIViewController<MKMapViewDelegate,CLLocationManagerDelegate> {

        MKMapView                   *mapView;
            MKReverseGeocoder           *geoCoder;
        MKPlacemark         *mPlacemark;
        CLLocationCoordinate2D  location;

       }
@property (nonatomic,retain)IBOutlet MKMapView *mapView;

@end

PositionActuelleViewController.m :

    - (void)viewDidLoad {
        [super viewDidLoad];
        [mapView setShowsUserLocation:TRUE];
        [mapView setMapType:MKMapTypeStandard];
        [mapView setDelegate:self];
        [self.view insertSubview:mapView atIndex:0];
        CLLocationManager *locationManager=[[CLLocationManager alloc] init];
        [locationManager setDelegate:self];
        [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
        [locationManager startUpdatingLocation];
    }

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

    location = newLocation.coordinate;
    MKCoordinateRegion region;
    region.center = location;
    MKCoordinateSpan span;
    span.latitudeDelta = .005;
    span.longitudeDelta = .005;
    region.span = span;
    [mapView setRegion:region animated:TRUE];

}

My only problem is that the zoom in is always enabled even if the user zoom out the map, it zoomed in automatically. How can I fix this?


问:
How to add a custom library to a scratch file
In PhpStorm/WebStorm how can I add a custom library so that the file compiles? In my case it would be Lodash?

I tried to add lodash to global libs but it did not help...

答:
Well I would suggest in this case to use plugin named Quokka.js available for Webstorm and other JetBrains tools.

It's recognise automatically the libraries from node_modules and have a lot of other features (work much better that pure scratch files).

When you will install it the default scratch Javascript and Typescript files will work with Quokka.

You will find the details on the official tool page: https://quokkajs.com/

Please select JET BRAINS tool on main page. Hope it helps.


答:
Raymond answer should work and the explanation is the same. ComponentDidMount only runs once and it has no need to run again as you Have Home in your stack.

I would recommend adding a listener on the componentWillReceiveProps which should be firing as well when the Home screen loads again, and you can see if you need to refresh or reload the screen.

But of course, it depends on your use case. If you keep pushing the Home screen on the stack, the only downsize is that once the user reaches Home, usually the back button should mean "leaving the app" and if you push it to the stack and you press back, you will just go back one screen. To be that is bad UX, but if taht works for you, fine.

Title: Why does componentDidMount not execute when I navigate to initial route from other screen?


问:
How do you dynamically create multiple bootstrap cards with Vue
I want to use the bootstrap cards with Vue dynamically. With Bootstrap Vue, to create a card I can do the following.

```<code>      <b-card title="Title" img-src="https://placekitten.com/500/350" img-alt="Image" img-top>
        <b-card-text>
          {{getBlogOfType("Vue")}}
        </b-card-text>
        <b-card-text class="small text-muted">Last updated 3 mins ago</b-card-text>
      </b-card>
</code>```

What I want to be able to do is create the number of cards based on the number of blogs I have from a database. I have my project linked to Firebase and I am able to access the content. I have written a method "getBlogOfType(param)" to get the blog from firebase. As shown above I can call the method multiple times to get the blog I want, but how can I achieve this without manually creating a separate card every time?

答:
Once you have a variable set aside for the data, for example var posts = [...];, you can use VueJs's v-for as follows:

```<code>  <b-card v-for="post in posts" title="Title" img-src="https://placekitten.com/500/350" img-alt="Image" img-top>
    <b-card-text>
      {{getBlogOfType("Vue")}}
    </b-card-text>
    <b-card-text class="small text-muted">Last updated 3 mins ago</b-card-text>
  </b-card>
</code>```

And use access the values of each element via the post object (post.title).

Body:
I want to use the bootstrap cards with Vue dynamically. With Bootstrap Vue, to create a card I can do the following.

          {{getBlogOfType("Vue")}}

        Last updated 3 mins ago

What I want to be able to do is create the number of cards based on the number of blogs I have from a database. I have my project linked to Firebase and I am able to access the content. I have written a method "getBlogOfType(param)" to get the blog from firebase. As shown above I can call the method multiple times to get the blog I want, but how can I achieve this without manually creating a separate card every time?

Body:
Once you have a variable set aside for the data, for example var posts = [...];, you can use VueJs's v-for as follows:

  <b-card v-for="post in posts" title="Title" img-src="https://placekitten.com/500/350" img-alt="Image" img-top>
    <b-card-text>
      {{getBlogOfType("Vue")}}
    </b-card-text>
    <b-card-text class="small text-muted">Last updated 3 mins ago</b-card-text>
  </b-card>

And use access the values of each element via the post object (post.title).


答:
You can use find to get the span with stock class. Use attr to get the attribute.

$("li").click(function() {
  var id = $(this).find('.stock').attr('id');
  console.log(id);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="ds"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="ju"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="zx"></span>
    </div>
  </li>
</ul></code>```

Title: How to get the id of span which is deep inside li when the li is clicked

Body:
You can use find to get the span with stock class. Use attr to get the attribute.

$("li").click(function() {
  var id = $(this).find('.stock').attr('id');
  console.log(id);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="ds"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="ju"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="zx"></span>
    </div>
  </li>
</ul>


问:
How to stop setInterval and resume?
How can I stop setInterval and then resume from the same place?

Example:

```<code>start ---> 1,2,3,4,5 .... ---> stop ---> start ---> 6,7,8 ...
</code>```

index.html

```<code><div onclick=start()>start</div>
<div onclick=stop()>stop</div>
</code>```

index.js

```<code>let refreshInterval = null;

start() {
  var i = 0;
    refreshInterval = setInterval(function() {
      console.log(i);
      i++;
    }, 1000);
}

stop() {
    ???????
}
</code>```

答:
You need a global variable i and for stopping a clearInterval.

function start() {
    if (refreshInterval !== undefined) return; // prevent more than one interval
    refreshInterval = setInterval(function() {
        console.log(i);
        i++;
    }, 1000);
}

function stop() {
    clearInterval(refreshInterval);
    refreshInterval = undefined;
}

var refreshInterval,
    i = 0;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div onclick="start()">start</div>
<div onclick="stop()">stop</div> </code>```

Title: How to stop setInterval and resume?

Body:
How can I stop setInterval and then resume from the same place?

Example:

start ---> 1,2,3,4,5 .... ---> stop ---> start ---> 6,7,8 ...

index.html

start

stop

index.js

let refreshInterval = null;

start() {
  var i = 0;
    refreshInterval = setInterval(function() {
      console.log(i);
      i++;
    }, 1000);
}

stop() {
    ???????
}

Body:
You need a global variable i and for stopping a clearInterval.

function start() {
    if (refreshInterval !== undefined) return; // prevent more than one interval
    refreshInterval = setInterval(function() {
        console.log(i);
        i++;
    }, 1000);
}

function stop() {
    clearInterval(refreshInterval);
    refreshInterval = undefined;
}

var refreshInterval,
    i = 0;

<div onclick="start()">start</div>
<div onclick="stop()">stop</div>


答:
You must add the class selector with li so it would not add on all lis.

Try this:

```<code>$("li.service").click(function() {
      var spanid = $(this).find('span.stock').attr('id');

      alert(spanid);
});
</code>```

Body:
You must add the class selector with li so it would not add on all lis.

Try this:

$("li.service").click(function() {
      var spanid = $(this).find('span.stock').attr('id');

      alert(spanid);
});


问:
CSS file referenced twice
I have a asp.net web app that uses themes, iframes, and master pages. I've analyzed the pages with IE Web developer and FF Firebug and noticed that every page references the same css file twice. I don't know if this is because of the master page model or because of the iframe. Anyone have any idea on how to reference the css only once?</p>

答:
If you set the page theme in the config, all the .css files in the App_Themes/YourTheme folder will be referenced automatically.

```<code><system.web>
    <pages theme="ThemeName">
        <controls>
        </controls>
    </pages>
<system.web>
</code>```

So, you don't need to add any references to your CSS files.

One catch though, the CSS files will be referenced in alphabetical order (as far as I'm aware there is no way to change this), so if you want one .css file to override another you need to be careful with file names.

OwnerDisplayName: jkm

ContentLicense: CC BY-SA 2.5

Title: CSS file referenced twice

Body:
If you set the page theme in the config, all the .css files in the App_Themes/YourTheme folder will be referenced automatically.

<system.web>
    <pages theme="ThemeName">
        <controls>
        </controls>
    </pages>
<system.web>

So, you don't need to add any references to your CSS files.

One catch though, the CSS files will be referenced in alphabetical order (as far as I'm aware there is no way to change this), so if you want one .css file to override another you need to be careful with file names.

OwnerDisplayName: Sophia


问:
SingleValueEventListener do not get the value after button click
I need to get nickname value from Firebase Real time database after button is clicked. So i made singleValueListner() in button´s onClick method. But it don´t work.

I have tried debug it, but code didn´t get into singleValueEventListener()

```<code>Button getName = (Button)findViewById(R.id.getName);

getName.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Member").child(user.getUid());
        db.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    TextView tv = (TextView)findViewById(R.id.tv);
                    tv.setText(data.child("nickname").getValue().toString());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
});

</code>```

Database JSON structure:

```<code>{
  "Member" : {
    "1Zuv6VZZ0kPluwc33f1QQQ7DZD93" /* UID */ : {
      "-LgIHwiAjfuh5pjK7wzl" : {
        "actualScore" : 0,
        "bestScore" : 0,
        "email" : "some@email.com",
        "nickname" : "Vitek",
        "season" : 0
      }
    }
  }
}
</code>```

Database structure:
https://drive.google.com/file/d/15B4b6Rb_WAiS6fioI9gItyijrbDiVjzJ/view

I need to get nickname, I think this is writen good, but not. So, what is wrong?

答:
You are only referring up to user's id but there is also a parent key of user detail which you need to reference.

```<code>tv.setText(data.child("LgiH------").child("nickname").getValue().toString());
</code>```

but try to remove that second key from your registering user's code because it is not helpful.

Body:
I need to get nickname value from Firebase Real time database after button is clicked. So i made singleValueListner() in button´s onClick method. But it don´t work.

I have tried debug it, but code didn´t get into singleValueEventListener()

Button getName = (Button)findViewById(R.id.getName);

getName.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        DatabaseReference db = FirebaseDatabase.getInstance().getReference().child("Member").child(user.getUid());
        db.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    TextView tv = (TextView)findViewById(R.id.tv);
                    tv.setText(data.child("nickname").getValue().toString());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
});

Database JSON structure:

{
  "Member" : {
    "1Zuv6VZZ0kPluwc33f1QQQ7DZD93" /* UID */ : {
      "-LgIHwiAjfuh5pjK7wzl" : {
        "actualScore" : 0,
        "bestScore" : 0,
        "email" : "some@email.com",
        "nickname" : "Vitek",
        "season" : 0
      }
    }
  }
}

Database structure:
https://drive.google.com/file/d/15B4b6Rb_WAiS6fioI9gItyijrbDiVjzJ/view

I need to get nickname, I think this is writen good, but not. So, what is wrong?

Body:
You are only referring up to user's id but there is also a parent key of user detail which you need to reference.

tv.setText(data.child("LgiH------").child("nickname").getValue().toString());

but try to remove that second key from your registering user's code because it is not helpful.


问:
How to use $this in another file on Codeigniter?
I have a file named fn.php in my view, then I create a function to post data, like this

```<code>function post($input_name){
   return $this->input->post($input_name);
}
</code>```

In my controller I call it like this,

```<code>public function myFunc(){
   $this->input->load('fn.php');
   // then I use the function that I have created like this
   post('myinputname');
}
</code>```

But... I got error, how I can solve this problem? thank you so much

答:
You should take some time to try and understand the MVC architecture. It is, after all, one of the main points of using a framework.

You can't put functions in a view and expect to load them somehow and access them. You can put functions in a model, controller, library or helper. In you case I would suggest a helper:

application/helpers/some_file_helper.php

```<code>function post($input_name){
   $CI = &get_instance();
   return $CI->input->post($input_name);
}
</code>```

The get_instance() part is only used when $this (CI context) isn't available. This only happens in helpers and libraries. In views, controllers, and models $this is always available.

Model or controller:

```<code>$this->load->helper('some_file');

print_r(post('somevar'));
</code>```

However if all you want to do is access the post variable use $this->input->post('somevar') directly and don't introduce an extra layer.

Body:
I have a file named fn.php in my view, then I create a function to post data, like this

function post($input_name){
   return $this->input->post($input_name);
}

In my controller I call it like this,

public function myFunc(){
   $this->input->load('fn.php');
   // then I use the function that I have created like this
   post('myinputname');
}

But... I got error, how I can solve this problem? thank you so much

Body:
You should take some time to try and understand the MVC architecture. It is, after all, one of the main points of using a framework.

You can't put functions in a view and expect to load them somehow and access them. You can put functions in a model, controller, library or helper. In you case I would suggest a helper:

application/helpers/some_file_helper.php

function post($input_name){
   $CI = &get_instance();
   return $CI->input->post($input_name);
}

The get_instance() part is only used when $this (CI context) isn't available. This only happens in helpers and libraries. In views, controllers, and models $this is always available.

Model or controller:

$this->load->helper('some_file');

print_r(post('somevar'));

However if all you want to do is access the post variable use $this->input->post('somevar') directly and don't introduce an extra layer.


问:
What is the C++ stream equivalent to perror?

Possible Duplicate:

  C++ alternative to perror()

I can't find the stream equivalent to perror. Is there such a thing? I like the fact that I can call:

```<code>perror("Error");
</code>```

And it will fill in what errno is. Can I do this with streams?

答:
To print an error message:

```<code>str << strerror(errno);
</code>```

If you're talking about the streams error state - no you can't get an automatic meaningful error message for that.

Body:
Possible Duplicate:

  C++ alternative to perror()

I can't find the stream equivalent to perror. Is there such a thing? I like the fact that I can call:

perror("Error");

And it will fill in what errno is. Can I do this with streams?

Body:
To print an error message:

str << strerror(errno);

If you're talking about the streams error state - no you can't get an automatic meaningful error message for that.


答:
You can keep the count variable in outer scope so it will not reset everytime you run start function

let refreshInterval = null;
let count = 0

function start() {
    refreshInterval = setInterval(function() {
      document.getElementById('value').innerText = count
      count++;
    }, 1000);
    document.getElementById('start').disabled=true
}

function stop() {
    clearInterval(refreshInterval)
    document.getElementById('start').disabled=false
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#counter{
  padding: 0.25rem;
  font-size: 1.25rem;
  border: 1px solid black;
  margin-bottom: 1rem;
}</code>```

counter:
0

<button onclick=start() id='start'>start</button>
<button onclick=stop() id='stop'>stop</button>```

Title: How to stop setInterval and resume?

Body:
You can keep the count variable in outer scope so it will not reset everytime you run start function

let refreshInterval = null;
let count = 0

function start() {
    refreshInterval = setInterval(function() {
      document.getElementById('value').innerText = count
      count++;
    }, 1000);
    document.getElementById('start').disabled=true
}

function stop() {
    clearInterval(refreshInterval)
    document.getElementById('start').disabled=false
}

#counter{
  padding: 0.25rem;
  font-size: 1.25rem;
  border: 1px solid black;
  margin-bottom: 1rem;
}

<div  id='counter'><span>counter:</span>
<span id='value'/>0</div>
<button onclick=start() id='start'>start</button>
<button onclick=stop() id='stop'>stop</button>


问:
js-cookie is not encoding the value the same as php setcookie
When I create a cookie using this https://github.com/js-cookie/js-cookie

This is my crypt variable contents..

s192aBszcV7NPrR8KpQbl4u/hkOOmMBzPg2mAhGlZB1/nAcus=0

Then setting cookie with js-cookie..

```<code>Cookies.set('_siteauth',crypt, {
   expires: 1,
   path: '/'
});
</code>```

This is the js set cookie value...

s192aBszcV7NPrR8KpQbl4u/hkOOmMBzPg2mAhGlZB1/nAcus=0

So if I set the same var using php setcookie..

```<code>setcookie('_siteauth', $crypt, time() + 86400, '/');
</code>```

The value of the cookie is this..

```<code>s192aBszcV7NPrR8KpQbl4u%2FhkOOmMBzPg2mAhGlZB1%2FnAcus%3D
</code>```

Which is how I expect a cookie value should be. Encoded.

But the documentation for js-cookie about encoding says this https://github.com/js-cookie/js-cookie#encoding, which i'm surprised that the value of the set js-cookie is not being encoded at all.

Can anybody shed some light on this please, or I'm missing something with js-cookie plugin?

答:
As the js-cookie documentation says:

This project is RFC 6265 compliant. All special characters that are not allowed in the cookie-name or cookie-value are encoded with each one's UTF-8 Hex equivalent using percent-encoding.

[...]

Please note that the default encoding/decoding strategy is meant to be interoperable only between cookies that are read/written by js-cookie. To override the default encoding/decoding strategy you need to use a converter.

(Emphasis mine.)

According to RFC 6265, cookie values can contain any characters from the set !#$%&'()*+-./:<=>?@[]^_`{|}~ as well as digits (0-9) and letters (a-zA-Z).

Note that both / and = are valid characters in cookie values.

Also, no encoding or escaping mechanism is specified:

The semantics of the cookie-value are not defined by this document.

To maximize compatibility with user agents, servers that wish to
store arbitrary data in a cookie-value SHOULD encode that data, for
example, using Base64 [RFC4648].

The use of percent-encoding for cookie values is not standardized. It's no surprise that different libraries come up with different encoding schemes for cookie values. In particular, js-cookie wasn't designed to be compatible with any encoding scheme but its own.

Body:
When I create a cookie using this https://github.com/js-cookie/js-cookie

This is my crypt variable contents..

s192aBszcV7NPrR8KpQbl4u/hkOOmMBzPg2mAhGlZB1/nAcus=0

Then setting cookie with js-cookie..

Cookies.set('_siteauth',crypt, {
   expires: 1,
   path: '/'
});

This is the js set cookie value...

s192aBszcV7NPrR8KpQbl4u/hkOOmMBzPg2mAhGlZB1/nAcus=0

So if I set the same var using php setcookie..

setcookie('_siteauth', $crypt, time() + 86400, '/');

The value of the cookie is this..

s192aBszcV7NPrR8KpQbl4u%2FhkOOmMBzPg2mAhGlZB1%2FnAcus%3D

Which is how I expect a cookie value should be. Encoded.

But the documentation for js-cookie about encoding says this https://github.com/js-cookie/js-cookie#encoding, which i'm surprised that the value of the set js-cookie is not being encoded at all.

Can anybody shed some light on this please, or I'm missing something with js-cookie plugin?


问:
Different results when training a model with same initial weights and same data
I'm trying to make some transfer learning to adjust the ResNet50 to my data set.
the problem is when I run the training again with the same parameters, I get a different result (loss and accuracy for train and val sets, so I guess also different weights and as a result different error rate for the test set)
here is my model:

the weights parameter is 'imagenet', all other parameter value isn't really important, the important thing is they are the same for each run...

```<code>def ImageNet_model(train_data, train_labels, param_dict, num_classes):
    X_datagen = get_train_augmented()
    validatin_cut_point= math.ceil(len(train_data)*(1-param_dict["validation_split"]))
    base_model = applications.resnet50.ResNet50(weights=param_dict["weights"], include_top=False, pooling=param_dict["pooling"],
                                                   input_shape=(param_dict["image_size"], param_dict["image_size"],3))
    # Define the layers in the new classification prediction
    x = base_model.output
    x = Dense(num_classes, activation='relu')(x)  # new FC layer, random init
    predictions = Dense(num_classes, activation='softmax')(x)  # new softmax layer

    model = Model(inputs=base_model.input, outputs=predictions)
    #   Freeze layers
    layers_to_freeze = param_dict["freeze"]
    for layer in model.layers[:layers_to_freeze]:
       layer.trainable = False
    for layer in model.layers[layers_to_freeze:]:
       layer.trainable = True
    sgd = optimizers.SGD(lr=param_dict["lr"], momentum=param_dict["momentum"], decay=param_dict["decay"])
    model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])
    lables_ints = [y.argmax() for y in np.array(train_labels)]
    class_weights = class_weight.compute_class_weight('balanced',
                                             np.unique(lables_ints),
                                             np.array(lables_ints))
    train_generator = X_datagen.flow(np.array(train_data)[0:validatin_cut_point],np.array(train_labels)[0:validatin_cut_point], batch_size=param_dict['batch_size'])
    validation_generator = X_datagen.flow(np.array(train_data)[validatin_cut_point:len(train_data)],
                                   np.array(train_labels)[validatin_cut_point:len(train_data)],
                                   batch_size=param_dict['batch_size'])
    history= model.fit_generator(
    train_generator,
    epochs=param_dict['epochs'],
    steps_per_epoch=validatin_cut_point // param_dict['batch_size'],
    validation_data=validation_generator,
    validation_steps=(len(train_data)-validatin_cut_point) // param_dict['batch_size'],
    class_weight=class_weights)
    shuffle=False,class_weight=class_weights)
    graph_of_loss_and_acc(history)
    model.save(param_dict['model_file_name'])
    return model
</code>```

what can make the output of each run different?
Since the initial weights are the same, it can't explain the difference ( I also tried to freeze some layers, didn't help). any ideas?

Thank!

答:
When you initialize the weights randomly in Dense layer, weights are initialized differently across runs and also converge to different local minima.

```<code>x = Dense(num_classes, activation='relu')(x)  # new FC layer, random init
</code>```

If you want the output to be same you need to initialize weights with same value across runs. You can read the details on how to obtain reproducible results on Keras here. These are the steps you need to follow

Set the PYTHONHASHSEED environment variable to 0

Set random seed for numpy generated random numbers np.random.seed(SEED)

Set random seed for Python generated random numbers random.seed(SEED)

Set random state for tensorflow backend tf.set_random_seed(SEED)

Body:
I'm trying to make some transfer learning to adjust the ResNet50 to my data set.
the problem is when I run the training again with the same parameters, I get a different result (loss and accuracy for train and val sets, so I guess also different weights and as a result different error rate for the test set)
here is my model:

the weights parameter is 'imagenet', all other parameter value isn't really important, the important thing is they are the same for each run...

def ImageNet_model(train_data, train_labels, param_dict, num_classes):
    X_datagen = get_train_augmented()
    validatin_cut_point= math.ceil(len(train_data)*(1-param_dict["validation_split"]))
    base_model = applications.resnet50.ResNet50(weights=param_dict["weights"], include_top=False, pooling=param_dict["pooling"],
                                                   input_shape=(param_dict["image_size"], param_dict["image_size"],3))
    # Define the layers in the new classification prediction
    x = base_model.output
    x = Dense(num_classes, activation='relu')(x)  # new FC layer, random init
    predictions = Dense(num_classes, activation='softmax')(x)  # new softmax layer

    model = Model(inputs=base_model.input, outputs=predictions)
    #   Freeze layers
    layers_to_freeze = param_dict["freeze"]
    for layer in model.layers[:layers_to_freeze]:
       layer.trainable = False
    for layer in model.layers[layers_to_freeze:]:
       layer.trainable = True
    sgd = optimizers.SGD(lr=param_dict["lr"], momentum=param_dict["momentum"], decay=param_dict["decay"])
    model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])
    lables_ints = [y.argmax() for y in np.array(train_labels)]
    class_weights = class_weight.compute_class_weight('balanced',
                                             np.unique(lables_ints),
                                             np.array(lables_ints))
    train_generator = X_datagen.flow(np.array(train_data)[0:validatin_cut_point],np.array(train_labels)[0:validatin_cut_point], batch_size=param_dict['batch_size'])
    validation_generator = X_datagen.flow(np.array(train_data)[validatin_cut_point:len(train_data)],
                                   np.array(train_labels)[validatin_cut_point:len(train_data)],
                                   batch_size=param_dict['batch_size'])
    history= model.fit_generator(
    train_generator,
    epochs=param_dict['epochs'],
    steps_per_epoch=validatin_cut_point // param_dict['batch_size'],
    validation_data=validation_generator,
    validation_steps=(len(train_data)-validatin_cut_point) // param_dict['batch_size'],
    class_weight=class_weights)
    shuffle=False,class_weight=class_weights)
    graph_of_loss_and_acc(history)
    model.save(param_dict['model_file_name'])
    return model

what can make the output of each run different?
Since the initial weights are the same, it can't explain the difference ( I also tried to freeze some layers, didn't help). any ideas?

Thank!

Body:
When you initialize the weights randomly in Dense layer, weights are initialized differently across runs and also converge to different local minima.

x = Dense(num_classes, activation='relu')(x)  # new FC layer, random init

If you want the output to be same you need to initialize weights with same value across runs. You can read the details on how to obtain reproducible results on Keras here. These are the steps you need to follow

Set the PYTHONHASHSEED environment variable to 0

Set random seed for numpy generated random numbers np.random.seed(SEED)

Set random seed for Python generated random numbers random.seed(SEED)

Set random state for tensorflow backend tf.set_random_seed(SEED)


问:
Cannot get cookie in vue-router to work. Undefined "this"
The problem is that I cannot get cookie in vue-router. When I try to do this: this.$cookie.get('token'); I get this undefined. Even though I can use this.$cookie in vue components. This is my code snippet:

Vue-Router:

This is a function to check if I get token from cookie (but it doesnt work):

```<code>function isLoggedIn (to, from, next) {
  console.log(this.$cookie.get('token'));
}
</code>```

And this is the route and I use that isLoggedIn in it:

```<code>{
  path: '/',
  name: 'login',
  component: Login,
  beforeEnter: isLoggedIn()
},
</code>```

Maybe someone knows how to get that cookie ? It it setted up in vue component correctly just don't know how to pass it to vue router.

EDIT
So by using Vue.cookie.get('token'); I get that next is not a function. This is the current function:

```<code>function isLoggedIn (to, from, next) {
  if(Vue.cookie.get('token')) {
    next({name: 'game'});
  } else {
    next();
  }
}
</code>```

Okay so when I added this function directly into route like this it worked:

```<code>{
  path: '/',
  name: 'login',
  component: Login,
  beforeEnter: (to, from, next) => {
    if(Vue.cookie.get('token')) {
      next('/game');
    } else {
      next;
    }
  }
},
</code>```

答:
If you are using the vue-cookie plugin from npm then you will need to use this syntax outside of components:

```<code>function isLoggedIn (to, from, next) {
  console.log(Vue.cookie.get('token'));
}
</code>```

With regards to your next is not a function error, this is because you are invoking your function with no arguments, isLoggedIn(), rather than passing the function reference, isLoggedIn, which will be invoked by the router with the appropriate arguments.

Try this instead:

```<code>{
  path: '/',
  name: 'login',
  component: Login,
  beforeEnter: isLoggedIn // No parentheses here
},
</code>```

I hope this helps.

Body:
The problem is that I cannot get cookie in vue-router. When I try to do this: this.$cookie.get('token'); I get this undefined. Even though I can use this.$cookie in vue components. This is my code snippet:

Vue-Router:

This is a function to check if I get token from cookie (but it doesnt work):

function isLoggedIn (to, from, next) {
  console.log(this.$cookie.get('token'));
}

And this is the route and I use that isLoggedIn in it:

{
  path: '/',
  name: 'login',
  component: Login,
  beforeEnter: isLoggedIn()
},

Maybe someone knows how to get that cookie ? It it setted up in vue component correctly just don't know how to pass it to vue router.

EDIT
So by using Vue.cookie.get('token'); I get that next is not a function. This is the current function:

function isLoggedIn (to, from, next) {
  if(Vue.cookie.get('token')) {
    next({name: 'game'});
  } else {
    next();
  }
}

Okay so when I added this function directly into route like this it worked:

{
  path: '/',
  name: 'login',
  component: Login,
  beforeEnter: (to, from, next) => {
    if(Vue.cookie.get('token')) {
      next('/game');
    } else {
      next;
    }
  }
},

Body:
If you are using the vue-cookie plugin from npm then you will need to use this syntax outside of components:

function isLoggedIn (to, from, next) {
  console.log(Vue.cookie.get('token'));
}

With regards to your next is not a function error, this is because you are invoking your function with no arguments, isLoggedIn(), rather than passing the function reference, isLoggedIn, which will be invoked by the router with the appropriate arguments.

Try this instead:

{
  path: '/',
  name: 'login',
  component: Login,
  beforeEnter: isLoggedIn // No parentheses here
},

I hope this helps.


问:
How to visualize mean edit distance in Tensorboard using Keras callback?
So far, I have been experimenting with Tensorflow and Keras. I took a code from image_ocr.py which allowed me to train printed text ocr. I want to see the training progress as it goes and have successfuly visualized the accuracy and loss of the training model. However, from what I have heard OCR RNN does not take accuracy as a validation but using mean edit distance instead to validate the accuracy of the words. In this case, I have been trying to get a variable called mean_ed and mean_norm_ed to be visualized in Tensorboard from class VizCallback. I have tried the method from this link but it still does not work. Can anyone help me with visualizing the mean edit distance variables? Here are the code snippets from my code:

```<code>class VizCallback(keras.callbacks.Callback):

def __init__(self, run_name, test_func, text_img_gen, num_display_words=6):
    self.test_func = test_func
    self.output_dir = os.path.join(
        OUTPUT_DIR, run_name)
    self.text_img_gen = text_img_gen
    self.num_display_words = num_display_words
    if not os.path.exists(self.output_dir):
        os.makedirs(self.output_dir)

def on_train_begin(self, logs={}):
    self.med = []
    self.nmed = []

def show_edit_distance(self, num, logs={}):
    num_left = num
    mean_norm_ed = 0.0
    mean_ed = 0.0
    while num_left > 0:
        word_batch = next(self.text_img_gen)[0]
        num_proc = min(word_batch['the_input'].shape[0], num_left)
        decoded_res = decode_batch(self.test_func, word_batch['the_input'][0:num_proc])
        for j in range(num_proc):
            edit_dist = editdistance.eval(decoded_res[j], word_batch['source_str'][j])
            mean_ed += float(edit_dist)
            mean_norm_ed += float(edit_dist) / len(word_batch['source_str'][j])
        num_left -= num_proc
    mean_norm_ed = mean_norm_ed / num
    mean_ed = mean_ed / num
    #Create scalar summaries for both mean edit distance and normalized mean edit distance
    tf_med_ph = tf.placeholder(tf.float32,shape=None,name='med_summary')
    tf_nmed_ph = tf.placeholder(tf.float32,shape=None,name='nmed_summary')
    tf_med = tf.summary.scalar('med', tf_med_ph)
    tf_nmed = tf.summary.scalar('nmed', tf_nmed_ph)
    performance_summaries = tf.summary.merge([tf_med,tf_nmed])

    #Create a session for displaying the summary
    config = tf.ConfigProto(allow_soft_placement=True)
    session = tf.InteractiveSession(config=config)
    summ_writer = tf.summary.FileWriter(os.path.join('summaries','first'), session.graph)

    # Execute the summaries defined above
    summ = session.run(performance_summaries, feed_dict={tf_med_ph:mean_ed, tf_nmed_ph:mean_norm_ed})

    # Write the obtained summaries to the file, so it can be displayed in the TensorBoard
    summ_writer.add_summary(summ, epoch)

    session.close()
    print('\nOut of %d samples:  Mean edit distance: %.3f Mean normalized edit distance: %0.3f'
          % (num, mean_ed, mean_norm_ed))

def on_epoch_end(self, epoch, logs={}):
    self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
    self.show_edit_distance(256)
    word_batch = next(self.text_img_gen)[0]
    res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
    if word_batch['the_input'][0].shape[0] < 256:
        cols = 2
    else:
        cols = 1
    for i in range(self.num_display_words):
        plt.subplot(self.num_display_words // cols, cols, i + 1)
        if K.image_data_format() == 'channels_first':
            the_input = word_batch['the_input'][i, 0, :, :]
        else:
            the_input = word_batch['the_input'][i, :, :, 0]
        plt.imshow(the_input.T, cmap='Greys_r')
        plt.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
    fig = plt.gcf()
    fig.set_size_inches(10, 13)
    plt.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
    plt.close()

def train(run_name, start_epoch, stop_epoch, img_w):
# Input Parameters
img_h = 64
words_per_epoch = 16000
val_split = 0.2
val_words = int(words_per_epoch * (val_split))

# Network parameters
conv_filters = 16
kernel_size = (3, 3)
pool_size = 2
time_dense_size = 32
rnn_size = 512
minibatch_size = 32

if K.image_data_format() == 'channels_first':
    input_shape = (1, img_w, img_h)
else:
    input_shape = (img_w, img_h, 1)

fdir = os.path.dirname(get_file('wordlists.tgz',
                                origin='http://test.com/wordlist.tgz', untar=True))

img_gen = TextImageGenerator(monogram_file=os.path.join(fdir, 'wordlist_mono_clean.txt'),
                             bigram_file=os.path.join(fdir, 'wordlist_bi_clean.txt'),
                             minibatch_size=minibatch_size,
                             img_w=img_w,
                             img_h=img_h,
                             downsample_factor=(pool_size ** 2),
                             val_split=words_per_epoch - val_words
                             )
act = 'relu'
input_data = Input(name='the_input', shape=input_shape, dtype='float32')
inner = Conv2D(conv_filters, kernel_size, padding='same',
               activation=act, kernel_initializer='he_normal',
               name='conv1')(input_data)
inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max1')(inner)
inner = Conv2D(conv_filters, kernel_size, padding='same',
               activation=act, kernel_initializer='he_normal',
               name='conv2')(inner)
inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max2')(inner)

conv_to_rnn_dims = (img_w // (pool_size ** 2), (img_h // (pool_size ** 2)) * conv_filters)
inner = Reshape(target_shape=conv_to_rnn_dims, name='reshape')(inner)

# cuts down input size going into RNN:
inner = Dense(time_dense_size, activation=act, name='dense1')(inner)

# Two layers of bidirectional GRUs
# GRU seems to work as well, if not better than LSTM:

gru_1 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru1')(inner)
gru_1b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru1_b')(inner)
gru1_merged = add([gru_1, gru_1b])
gru_2 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru2')(gru1_merged)
gru_2b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru2_b')(gru1_merged)

# transforms RNN output to character activations:
inner = Dense(img_gen.get_output_size(), kernel_initializer='he_normal',
              name='dense2')(concatenate([gru_2, gru_2b]))
y_pred = Activation('softmax', name='softmax')(inner)
Model(inputs=input_data, outputs=y_pred).summary()

labels = Input(name='the_labels', shape=[img_gen.absolute_max_string_len], dtype='float32')
input_length = Input(name='input_length', shape=[1], dtype='int64')
label_length = Input(name='label_length', shape=[1], dtype='int64')
# Keras doesn't currently support loss funcs with extra parameters
# so CTC loss is implemented in a lambda layer
loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, labels, input_length, label_length])

# clipnorm seems to speeds up convergence
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)

model = Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)

#Make tensorboard instance
init_op = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init_op)
tbname="tensorboard-of-{}".format(int(time.time()))
tensorboard = keras.callbacks.TensorBoard(
log_dir="logs/{}".format(tbname),
histogram_freq=0,
write_images=True)

# the loss calc occurs elsewhere, so use a dummy lambda func for the loss
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=sgd,
          metrics=['accuracy'])
if start_epoch > 0:
    weight_file = os.path.join(OUTPUT_DIR, os.path.join(run_name, 'weights%02d.h5' % (start_epoch - 1)))
    model.load_weights(weight_file)
# captures output of softmax so we can decode the output during visualization
test_func = K.function([input_data], [y_pred])

viz_cb = VizCallback(run_name, test_func, img_gen.next_val())

model.fit_generator(generator=img_gen.next_train(),
                    steps_per_epoch=(words_per_epoch - val_words) // minibatch_size,
                    epochs=stop_epoch,
                    validation_data=img_gen.next_val(),
                    validation_steps=val_words // minibatch_size,
                    callbacks=[tensorboard,viz_cb, img_gen],
                    initial_epoch=start_epoch)
</code>```

Any help would be much appriciated. Thank you!

P.S. I am using Tensorflow 1.9.0 and Python 3.6.8

UPDATE
now it is just a matter of passing the variable performance_summaries from the VizCallbak class towards the metrics in the train function. Any help here?

答:
You could modify show_edit_distance to add the summaries every time this function is being called:

```<code>def show_edit_distance(self, num, epoch):
    ...
    summary = tf.Summary()
    summary.value.add(tag='mean_ed', simple_value=mean_ed)
    summ_writer.add_summary(summary, epoch)

    summary = tf.Summary()
    summary.value.add(tag='mean_norm_ed', simple_value=mean_norm_ed)
    summ_writer.add_summary(summary, epoch)
    ...
</code>```

Note that you will need an extra argument epoch:

```<code>def on_epoch_end(self, epoch, logs={}):
    ...
    self.show_edit_distance(256, epoch)
    ...
</code>```

The Tensorboard callback should automatically pick up these summaries, as they're being added to the GraphKeys.SUMMARIES collection.

NOTE: Unfortunately, I couldn't test the solution. Please let me know if there is something I am missing.

Body:
So far, I have been experimenting with Tensorflow and Keras. I took a code from image_ocr.py which allowed me to train printed text ocr. I want to see the training progress as it goes and have successfuly visualized the accuracy and loss of the training model. However, from what I have heard OCR RNN does not take accuracy as a validation but using mean edit distance instead to validate the accuracy of the words. In this case, I have been trying to get a variable called mean_ed and mean_norm_ed to be visualized in Tensorboard from class VizCallback. I have tried the method from this link but it still does not work. Can anyone help me with visualizing the mean edit distance variables? Here are the code snippets from my code:

class VizCallback(keras.callbacks.Callback):

def __init__(self, run_name, test_func, text_img_gen, num_display_words=6):
    self.test_func = test_func
    self.output_dir = os.path.join(
        OUTPUT_DIR, run_name)
    self.text_img_gen = text_img_gen
    self.num_display_words = num_display_words
    if not os.path.exists(self.output_dir):
        os.makedirs(self.output_dir)

def on_train_begin(self, logs={}):
    self.med = []
    self.nmed = []

def show_edit_distance(self, num, logs={}):
    num_left = num
    mean_norm_ed = 0.0
    mean_ed = 0.0
    while num_left > 0:
        word_batch = next(self.text_img_gen)[0]
        num_proc = min(word_batch['the_input'].shape[0], num_left)
        decoded_res = decode_batch(self.test_func, word_batch['the_input'][0:num_proc])
        for j in range(num_proc):
            edit_dist = editdistance.eval(decoded_res[j], word_batch['source_str'][j])
            mean_ed += float(edit_dist)
            mean_norm_ed += float(edit_dist) / len(word_batch['source_str'][j])
        num_left -= num_proc
    mean_norm_ed = mean_norm_ed / num
    mean_ed = mean_ed / num
    #Create scalar summaries for both mean edit distance and normalized mean edit distance
    tf_med_ph = tf.placeholder(tf.float32,shape=None,name='med_summary')
    tf_nmed_ph = tf.placeholder(tf.float32,shape=None,name='nmed_summary')
    tf_med = tf.summary.scalar('med', tf_med_ph)
    tf_nmed = tf.summary.scalar('nmed', tf_nmed_ph)
    performance_summaries = tf.summary.merge([tf_med,tf_nmed])

    #Create a session for displaying the summary
    config = tf.ConfigProto(allow_soft_placement=True)
    session = tf.InteractiveSession(config=config)
    summ_writer = tf.summary.FileWriter(os.path.join('summaries','first'), session.graph)

    # Execute the summaries defined above
    summ = session.run(performance_summaries, feed_dict={tf_med_ph:mean_ed, tf_nmed_ph:mean_norm_ed})

    # Write the obtained summaries to the file, so it can be displayed in the TensorBoard
    summ_writer.add_summary(summ, epoch)

    session.close()
    print('\nOut of %d samples:  Mean edit distance: %.3f Mean normalized edit distance: %0.3f'
          % (num, mean_ed, mean_norm_ed))

def on_epoch_end(self, epoch, logs={}):
    self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
    self.show_edit_distance(256)
    word_batch = next(self.text_img_gen)[0]
    res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
    if word_batch['the_input'][0].shape[0] < 256:
        cols = 2
    else:
        cols = 1
    for i in range(self.num_display_words):
        plt.subplot(self.num_display_words // cols, cols, i + 1)
        if K.image_data_format() == 'channels_first':
            the_input = word_batch['the_input'][i, 0, :, :]
        else:
            the_input = word_batch['the_input'][i, :, :, 0]
        plt.imshow(the_input.T, cmap='Greys_r')
        plt.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
    fig = plt.gcf()
    fig.set_size_inches(10, 13)
    plt.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
    plt.close()

def train(run_name, start_epoch, stop_epoch, img_w):
# Input Parameters
img_h = 64
words_per_epoch = 16000
val_split = 0.2
val_words = int(words_per_epoch * (val_split))

# Network parameters
conv_filters = 16
kernel_size = (3, 3)
pool_size = 2
time_dense_size = 32
rnn_size = 512
minibatch_size = 32

if K.image_data_format() == 'channels_first':
    input_shape = (1, img_w, img_h)
else:
    input_shape = (img_w, img_h, 1)

fdir = os.path.dirname(get_file('wordlists.tgz',
                                origin='http://test.com/wordlist.tgz', untar=True))

img_gen = TextImageGenerator(monogram_file=os.path.join(fdir, 'wordlist_mono_clean.txt'),
                             bigram_file=os.path.join(fdir, 'wordlist_bi_clean.txt'),
                             minibatch_size=minibatch_size,
                             img_w=img_w,
                             img_h=img_h,
                             downsample_factor=(pool_size ** 2),
                             val_split=words_per_epoch - val_words
                             )
act = 'relu'
input_data = Input(name='the_input', shape=input_shape, dtype='float32')
inner = Conv2D(conv_filters, kernel_size, padding='same',
               activation=act, kernel_initializer='he_normal',
               name='conv1')(input_data)
inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max1')(inner)
inner = Conv2D(conv_filters, kernel_size, padding='same',
               activation=act, kernel_initializer='he_normal',
               name='conv2')(inner)
inner = MaxPooling2D(pool_size=(pool_size, pool_size), name='max2')(inner)

conv_to_rnn_dims = (img_w // (pool_size ** 2), (img_h // (pool_size ** 2)) * conv_filters)
inner = Reshape(target_shape=conv_to_rnn_dims, name='reshape')(inner)

# cuts down input size going into RNN:
inner = Dense(time_dense_size, activation=act, name='dense1')(inner)

# Two layers of bidirectional GRUs
# GRU seems to work as well, if not better than LSTM:

gru_1 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru1')(inner)
gru_1b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru1_b')(inner)
gru1_merged = add([gru_1, gru_1b])
gru_2 = GRU(rnn_size, return_sequences=True, kernel_initializer='he_normal', name='gru2')(gru1_merged)
gru_2b = GRU(rnn_size, return_sequences=True, go_backwards=True, kernel_initializer='he_normal', name='gru2_b')(gru1_merged)

# transforms RNN output to character activations:
inner = Dense(img_gen.get_output_size(), kernel_initializer='he_normal',
              name='dense2')(concatenate([gru_2, gru_2b]))
y_pred = Activation('softmax', name='softmax')(inner)
Model(inputs=input_data, outputs=y_pred).summary()

labels = Input(name='the_labels', shape=[img_gen.absolute_max_string_len], dtype='float32')
input_length = Input(name='input_length', shape=[1], dtype='int64')
label_length = Input(name='label_length', shape=[1], dtype='int64')
# Keras doesn't currently support loss funcs with extra parameters
# so CTC loss is implemented in a lambda layer
loss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([y_pred, labels, input_length, label_length])

# clipnorm seems to speeds up convergence
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True, clipnorm=5)

model = Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)

#Make tensorboard instance
init_op = tf.initialize_all_variables()

sess = tf.Session()
sess.run(init_op)
tbname="tensorboard-of-{}".format(int(time.time()))
tensorboard = keras.callbacks.TensorBoard(
log_dir="logs/{}".format(tbname),
histogram_freq=0,
write_images=True)

# the loss calc occurs elsewhere, so use a dummy lambda func for the loss
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=sgd,
          metrics=['accuracy'])
if start_epoch > 0:
    weight_file = os.path.join(OUTPUT_DIR, os.path.join(run_name, 'weights%02d.h5' % (start_epoch - 1)))
    model.load_weights(weight_file)
# captures output of softmax so we can decode the output during visualization
test_func = K.function([input_data], [y_pred])

viz_cb = VizCallback(run_name, test_func, img_gen.next_val())

model.fit_generator(generator=img_gen.next_train(),
                    steps_per_epoch=(words_per_epoch - val_words) // minibatch_size,
                    epochs=stop_epoch,
                    validation_data=img_gen.next_val(),
                    validation_steps=val_words // minibatch_size,
                    callbacks=[tensorboard,viz_cb, img_gen],
                    initial_epoch=start_epoch)

Any help would be much appriciated. Thank you!

P.S. I am using Tensorflow 1.9.0 and Python 3.6.8

UPDATE
now it is just a matter of passing the variable performance_summaries from the VizCallbak class towards the metrics in the train function. Any help here?

Body:
You could modify show_edit_distance to add the summaries every time this function is being called:

def show_edit_distance(self, num, epoch):
    ...
    summary = tf.Summary()
    summary.value.add(tag='mean_ed', simple_value=mean_ed)
    summ_writer.add_summary(summary, epoch)

    summary = tf.Summary()
    summary.value.add(tag='mean_norm_ed', simple_value=mean_norm_ed)
    summ_writer.add_summary(summary, epoch)
    ...

Note that you will need an extra argument epoch:

def on_epoch_end(self, epoch, logs={}):
    ...
    self.show_edit_distance(256, epoch)
    ...

The Tensorboard callback should automatically pick up these summaries, as they're being added to the GraphKeys.SUMMARIES collection.

NOTE: Unfortunately, I couldn't test the solution. Please let me know if there is something I am missing.


问:
How do I find out the Git commands used at the start of the job?
I'm trying to debug some Git related stuff, but really want to know all the Git commands the runner is calling at the start of a job. How can I do this?</p>

答:
If you are running your own runners, you can set pre_clone_script to set -x. This might output all the commands in verbose mode. See also: https://docs.gitlab.com/runner/configuration/advanced-configuration.html#the-runners-section.

What gitlab does also depends on what stage the job is running. Is it at the beginning, in the middle, or towards the end? I'm using the docker runner which typically does:

Download the docker image used for the build

Login into the docker image

Load the cache from a previous job

Delete all the changes from the previous job, similiar to git clean -qfdx

checkout the hash you want to build, similar to git checkout 234nsdfgow45sdfkj

download artifacts from all previous build jobs, if there are any

start whatever is defined in the script: section of your .gitlab-ci.yml

Look at the output of your job from the beginning. You are better off to describe what your actual problem is rather than "debug" all the git commands gitlab does for you.


问:
Nodejs different HMAC signature from OpenSSL
I've been struggling with creating a correct HMAC signature in Node.

Use case

I'm currently working a Jointspace API client for Node to control Philips smart tv's. But to get this working I need to sign a string for a pairing request.

Current situation

My nodejs code looks like this:

```<code>const crypto = require('crypto');

let secret = Buffer.from('ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA==', 'base64');
let text = '12345';
let algorithm = 'sha1';
let hmac = crypto.createHmac(algorithm, secret);
hmac.write(text);
hmac.end();

console.log(hmac.read('binary').toString('base64'));
</code>```

When I run it, it results to this:

```<code>~ $ node test.js
DURLMkx7YdrIlWdUKo3iNDC3cp0=
</code>```

Expected

When I do the exact same thing with the openssl command via the command line, I get a different result. (The correct result)

```<code>~ $ echo -n "ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA==" | base64 -d | openssl dgst -sha1 -hmac "12345" -binary | base64
GvbRLlBSY8r/jPqUGox8zZHxOew=
</code>```

References

There is an issue on the node Github page which addresses an issue of a difference between Node and openssl. In that issue they basically say that crypto in node is just a wrapper for the C++ openssl library. And in order for it to properly work you need to provide the secret as a Buffer instead of a string because of conversion issues.

E.g.

```<code>crypto.createHmac('sha1', new Buffer('secret_key', 'utf8'));
</code>```

But this does not resolve my issue.

Differences in output

```<code>~ $ echo "DURLMkx7YdrIlWdUKo3iNDC3cp0=" | base64 -d | hexdump -C
00000000  0d 44 4b 32 4c 7b 61 da  c8 95 67 54 2a 8d e2 34  |.DK2L{a...gT*..4|
00000010  30 b7 72 9d                                       |0.r.|
00000014
~ $ echo "GvbRLlBSY8r/jPqUGox8zZHxOew=" | base64 -d | hexdump -C
00000000  1a f6 d1 2e 50 52 63 ca  ff 8c fa 94 1a 8c 7c cd  |....PRc.......|.|
00000010  91 f1 39 ec                                       |..9.|
00000014
</code>```

答:
In your command you're using 12345 as the HMAC key but in your code you're using it as data! so here's an update on the code

```<code>const crypto = require('crypto');

let secret = 'ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA=='
let key = '12345';
let algorithm = 'sha1';
let hmac = crypto.createHmac(algorithm, key);
hmac.write(secret);
hmac.end();

console.log(hmac.read('binary').toString('base64'));
</code>```

And here's the command

```<code>echo -n "ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA==" | openssl dgst -sha1 -hmac "12345" -binary | base64
</code>```

They both return the same hash.

Body:
I've been struggling with creating a correct HMAC signature in Node.

Use case

I'm currently working a Jointspace API client for Node to control Philips smart tv's. But to get this working I need to sign a string for a pairing request.

Current situation

My nodejs code looks like this:

const crypto = require('crypto');

let secret = Buffer.from('ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA==', 'base64');
let text = '12345';
let algorithm = 'sha1';
let hmac = crypto.createHmac(algorithm, secret);
hmac.write(text);
hmac.end();

console.log(hmac.read('binary').toString('base64'));

When I run it, it results to this:

~ $ node test.js
DURLMkx7YdrIlWdUKo3iNDC3cp0=

Expected

When I do the exact same thing with the openssl command via the command line, I get a different result. (The correct result)

~ $ echo -n "ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA==" | base64 -d | openssl dgst -sha1 -hmac "12345" -binary | base64
GvbRLlBSY8r/jPqUGox8zZHxOew=

References

There is an issue on the node Github page which addresses an issue of a difference between Node and openssl. In that issue they basically say that crypto in node is just a wrapper for the C++ openssl library. And in order for it to properly work you need to provide the secret as a Buffer instead of a string because of conversion issues.

E.g.

crypto.createHmac('sha1', new Buffer('secret_key', 'utf8'));

But this does not resolve my issue.

Differences in output

~ $ echo "DURLMkx7YdrIlWdUKo3iNDC3cp0=" | base64 -d | hexdump -C
00000000  0d 44 4b 32 4c 7b 61 da  c8 95 67 54 2a 8d e2 34  |.DK2L{a...gT*..4|
00000010  30 b7 72 9d                                       |0.r.|
00000014
~ $ echo "GvbRLlBSY8r/jPqUGox8zZHxOew=" | base64 -d | hexdump -C
00000000  1a f6 d1 2e 50 52 63 ca  ff 8c fa 94 1a 8c 7c cd  |....PRc.......|.|
00000010  91 f1 39 ec                                       |..9.|
00000014

Body:
In your command you're using 12345 as the HMAC key but in your code you're using it as data! so here's an update on the code

const crypto = require('crypto');

let secret = 'ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA=='
let key = '12345';
let algorithm = 'sha1';
let hmac = crypto.createHmac(algorithm, key);
hmac.write(secret);
hmac.end();

console.log(hmac.read('binary').toString('base64'));

And here's the command

echo -n "ZmVay1EQVFOaZhwQ4Kv81ypLAZNczV9sG4KkseXWn1NEk6cXmPKO/MCa9sryslvLCFMnNe4Z4CPXzToowvhHvA==" | openssl dgst -sha1 -hmac "12345" -binary | base64

They both return the same hash.


问:
How to run two different DB's click event using third DB
I have two databases in MS Access having different codes, but both have unique form i.e form2. Now i have form in third database and i want run database 1 and database 2 form2 click event using this form.

I have code for this purpose on third form and code is running both db's form correctly but click event not running at that time.

My code is given below

```<code>Private Sub Command0_Click()
OpenRemoteForm "C:\Data\Offer\Chrome\Main_Ch.accdb", "Form2", "Command17_Click()"
End Sub

Function OpenRemoteForm(strDbFile As String, strFormName As String, strclick As String)
    Dim objAcc As Object
    Dim accFrm As Object
    Dim rst As DAO.Recordset
    DoCmd.RunCommand acCmdAppMinimize
    Dim strBookmark As String

    Set objAcc = CreateObject("Access.Application")
    objAcc.OpenCurrentDatabase (strDbFile)

'    objAcc.DoCmd.OpenForm strFormName
'    With objAcc.Forms(strFormName)
'        Set rst = .RecordsetClone
'        rst.FindFirst strKeyFieldName & "=" & lngIDToFind
'        If rst.NoMatch Then
'            MsgBox "No Match"
'        Else
'            .Bookmark = rst.Bookmark
'        End If
'    End With

    objAcc.UserControl = True

End Function
</code>```

When i press button on third db form then click event should be run of DB 1 form2 and DB2 form2 simultanously.

答:
There is no code in that procedure to call procedure in other db. If you want to call form procedure from 3rd db, procedure cannot be Private. Remove private qualifier from button Click event declaration in the two dbs.

Form name can definitely be passed in a variable and referenced that way. Must open form before calling procedure.

objAcc.DoCmd.OpenForm strFormName

Referencing form procedures is trickier. One approach is to give both buttons same name and explicitly reference that name.

objAcc.Forms(strFormName).Command17_Click

Another approach uses CallByName intrinsic function which does allow passing procedure reference in a variable.

CallByName objAcc.Forms(strFormName), strClick, vbMethod

Have to remove parentheses from the strClick parameter.

OpenRemoteForm "C:\Data\Offer\Chrome\Main_Ch.accdb", "Form2", "Command17_Click"

If you want to open db and then just hand control over to user, really don't even need all this code declaring and setting application objects. Have code behind those forms to run their own button Click event using Open or Load events. If form is set to open by default when db opens, then code in those events should execute when db opens. Methods for simply opening a file use FollowHyperlink or Shell commands.

Recommend assigning more meaningful names than defaults assigned by Access.

Body:
I have two databases in MS Access having different codes, but both have unique form i.e form2. Now i have form in third database and i want run database 1 and database 2 form2 click event using this form.

I have code for this purpose on third form and code is running both db's form correctly but click event not running at that time.

My code is given below

Private Sub Command0_Click()
OpenRemoteForm "C:\Data\Offer\Chrome\Main_Ch.accdb", "Form2", "Command17_Click()"
End Sub

Function OpenRemoteForm(strDbFile As String, strFormName As String, strclick As String)
    Dim objAcc As Object
    Dim accFrm As Object
    Dim rst As DAO.Recordset
    DoCmd.RunCommand acCmdAppMinimize
    Dim strBookmark As String

    Set objAcc = CreateObject("Access.Application")
    objAcc.OpenCurrentDatabase (strDbFile)

'    objAcc.DoCmd.OpenForm strFormName
'    With objAcc.Forms(strFormName)
'        Set rst = .RecordsetClone
'        rst.FindFirst strKeyFieldName & "=" & lngIDToFind
'        If rst.NoMatch Then
'            MsgBox "No Match"
'        Else
'            .Bookmark = rst.Bookmark
'        End If
'    End With

    objAcc.UserControl = True

End Function

When i press button on third db form then click event should be run of DB 1 form2 and DB2 form2 simultanously.