问:
Display output of process in php
```<code>header("Content-type: text/plain");

// tell php to automatically flush after every output
// including lines of output produced by shell commands
disable_ob();

$command = 'sudo rsync -arz --progress /home/lokesh/Desktop /home/lokesh/Downloads --stats';
system($command);

function disable_ob() {
    // Turn off output buffering
    ini_set('output_buffering', 'off');
    // Turn off PHP output compression
    ini_set('zlib.output_compression', false);
    // Implicitly flush the buffer(s)
    //ini_set('implicit_flush', true);
    ob_implicit_flush(true);
    // Clear, and turn off output buffering
    while (ob_get_level() > 0) {
        // Get the curent level
        $level = ob_get_level();
        // End the buffering
        ob_end_clean();
        // If the current level has not changed, abort
        if (ob_get_level() == $level) break;
    }
    // Disable apache output buffering/compression
    if (function_exists('apache_setenv')) {
        apache_setenv('no-gzip', '1');
        apache_setenv('dont-vary', '1');
    }
}
</code>```

above my code gives me output like this.

OUTPUT

Desktop/
Desktop/CloudRDP.bat

```<code>        336 100%    0.00kB/s    0:00:00
        336 100%    0.00kB/s    0:00:00 (xfr#1, ir-chk=1055/1057)
</code>```

Desktop/Days of the Week Song - 7 Days of the Week - Children's Songs by The Learning Station.mp4

```<code>     32,768   0%  888.89kB/s    0:00:22
  5,308,416  27%    5.06MB/s    0:00:02
  5,636,096  28%    2.41MB/s    0:00:05
 10,846,208  55%    3.20MB/s    0:00:02
 15,826,944  80%    3.56MB/s    0:00:01
 19,611,127 100%    3.75MB/s    0:00:04 (xfr#2, ir-chk=1054/1057)
</code>```

Desktop/EnjayEsync Ver 2.4.1.rar

```<code>     32,768   1%   42.61kB/s    0:00:49
  1,277,952  59%    1.22MB/s    0:00:00
  2,135,855 100%    1.73MB/s    0:00:01 (xfr#3, ir-chk=1053/1057)
</code>```

Desktop/EnjayOnlineProductRegistration.sql

```<code>     32,768  13%  181.82kB/s    0:00:01
    235,670 100%    1.05MB/s    0:00:00 (xfr#4, ir-chk=1052/1057)
</code>```

But I want to count number of file transfer by searching "xfr#" string. How this is possible. I have tried to loop but unable to do this. Means  after get this string (xfr#4) it show me output 4.

答: If you need not only the last line of the command's output, then instead of system — Execute an external program and display the output — use popen — Opens process file pointer — (to read line by line) or exec — Execute an external program (to get an array filled with every line of output).</p>

Title: Display output of process in php

Body:
header("Content-type: text/plain");

// tell php to automatically flush after every output
// including lines of output produced by shell commands
disable_ob();

$command = 'sudo rsync -arz --progress /home/lokesh/Desktop /home/lokesh/Downloads --stats';
system($command);

function disable_ob() {
    // Turn off output buffering
    ini_set('output_buffering', 'off');
    // Turn off PHP output compression
    ini_set('zlib.output_compression', false);
    // Implicitly flush the buffer(s)
    //ini_set('implicit_flush', true);
    ob_implicit_flush(true);
    // Clear, and turn off output buffering
    while (ob_get_level() > 0) {
        // Get the curent level
        $level = ob_get_level();
        // End the buffering
        ob_end_clean();
        // If the current level has not changed, abort
        if (ob_get_level() == $level) break;
    }
    // Disable apache output buffering/compression
    if (function_exists('apache_setenv')) {
        apache_setenv('no-gzip', '1');
        apache_setenv('dont-vary', '1');
    }
}

above my code gives me output like this.

OUTPUT

Desktop/
Desktop/CloudRDP.bat

        336 100%    0.00kB/s    0:00:00
        336 100%    0.00kB/s    0:00:00 (xfr#1, ir-chk=1055/1057)

Desktop/Days of the Week Song - 7 Days of the Week - Children's Songs by The Learning Station.mp4

     32,768   0%  888.89kB/s    0:00:22
  5,308,416  27%    5.06MB/s    0:00:02
  5,636,096  28%    2.41MB/s    0:00:05
 10,846,208  55%    3.20MB/s    0:00:02
 15,826,944  80%    3.56MB/s    0:00:01
 19,611,127 100%    3.75MB/s    0:00:04 (xfr#2, ir-chk=1054/1057)

Desktop/EnjayEsync Ver 2.4.1.rar

     32,768   1%   42.61kB/s    0:00:49
  1,277,952  59%    1.22MB/s    0:00:00
  2,135,855 100%    1.73MB/s    0:00:01 (xfr#3, ir-chk=1053/1057)

Desktop/EnjayOnlineProductRegistration.sql

     32,768  13%  181.82kB/s    0:00:01
    235,670 100%    1.05MB/s    0:00:00 (xfr#4, ir-chk=1052/1057)

But I want to count number of file transfer by searching "xfr#" string. How this is possible. I have tried to loop but unable to do this. Means  after get this string (xfr#4) it show me output 4.


来源: stackexchange

问:
Am I using Javascript call-backs appropriately (object-oriented style)?
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

```<code>function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();
</code>```

答:
No, you're not.  You'll want to do this:

```<code>this.initiate = function() {
    setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
}
</code>```

Now, if "afterTimeout" needs the proper object context, you could do this:

```<code>this.initiate = function() {
  var instance = this;
  setTimeout(function() { instance.afterTimeOut(); }, 1000);
}
</code>```

OK well you changed the question considerably with that little edit :-)  If I were you, I'd just do this (like my original second example):

```<code>this.initiate = function() {
  var instance = this;
  setTimeout(function() { instance.afterTimeOut(); }, 1000);
}
</code>```

Then you don't need any ugly global variables around at all.

edit — Stackoverflow user @Christoph comments that this isn't particularly pretty. One thing that might help would be to use a "bind" facility, as provided by newer browsers natively (as a method on the Function prototype) or by some libraries (Prototype or Functional for example).  What "bind" lets you do is create a little wrapper function like I've got above:

```<code>this.initiate = function() {
  setTimeout(this.afterTimeOut.bind(this), 1000);
}
</code>```

That call to "bind" returns a function that is effectively the same sort of thing as the little wrapper I coded explicitly in the example.

ContentLicense: CC BY-SA 2.5

Body:
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();

Body:
No, you're not.  You'll want to do this:

this.initiate = function() {
    setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
}

Now, if "afterTimeout" needs the proper object context, you could do this:

this.initiate = function() {
  var instance = this;
  setTimeout(function() { instance.afterTimeOut(); }, 1000);
}

OK well you changed the question considerably with that little edit :-)  If I were you, I'd just do this (like my original second example):

this.initiate = function() {
  var instance = this;
  setTimeout(function() { instance.afterTimeOut(); }, 1000);
}

Then you don't need any ugly global variables around at all.

edit — Stackoverflow user @Christoph comments that this isn't particularly pretty. One thing that might help would be to use a "bind" facility, as provided by newer browsers natively (as a method on the Function prototype) or by some libraries (Prototype or Functional for example).  What "bind" lets you do is create a little wrapper function like I've got above:

this.initiate = function() {
  setTimeout(this.afterTimeOut.bind(this), 1000);
}

That call to "bind" returns a function that is effectively the same sort of thing as the little wrapper I coded explicitly in the example.


问:
SignalR always downgrades to long polling
I've created a new webservice using SignalR.Core which properly negotiates to use WebSockets.  I also added it to an existing website, but it fails to negotiate both WebSockets and ServerSentEvents, so will always downgrade to use LongPolling.

Both projects target .NET v4.7.1, running on IIS Express 10.  The client is a UWP app using the SignalR.Client library.

Does anyone know what I'm missing?

Client:

```<code>08:46:25.9067539 - null - ChangeState(Disconnected, Connecting)
08:46:28.4516671 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - WS Connecting to: ws://192.168.0.84:8080/signalr/connect?clientProtocol=1.4&transport=webSockets&connectionData=[{"Name":"SyncHub"}]&connectionToken=GsZKYTf9rwH3NqngtHe5f6eUEcHRqlGYsBDkC2g43FOZs8zP%2FJg%2Fhld1fdm9iO91yPBoxNIqY7N%2FlnlJDCSfFwK8YTnJNztxRVS5aUPt9G4KrIYEpMNNwyucyHILDMqr
08:46:28.6707519 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - Auto: Failed to connect to using transport webSockets. System.Exception: Internal server error (500). (Exception from HRESULT: 0x801901F4)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.Client.Transports.WebSocketTransport.<OpenWebSocket>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.Client.Transports.WebSocketTransport.<StartWebSocket>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.Client.Transports.WebSocketTransport.<Start>d__14.MoveNext()
08:46:28.7516001 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - SSE: GET http://192.168.0.84:8080/signalr/connect?clientProtocol=1.4&transport=serverSentEvents&connectionData=[{"Name":"SyncHub"}]&connectionToken=GsZKYTf9rwH3NqngtHe5f6eUEcHRqlGYsBDkC2g43FOZs8zP%2FJg%2Fhld1fdm9iO91yPBoxNIqY7N%2FlnlJDCSfFwK8YTnJNztxRVS5aUPt9G4KrIYEpMNNwyucyHILDMqr
08:46:33.7643871 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - Auto: Failed to connect to using transport serverSentEvents. System.TimeoutException: Transport timed out trying to connect
08:46:33.7763838 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - LP Connect: http://192.168.0.84:8080/signalr/connect?clientProtocol=1.4&transport=longPolling&connectionData=[{"Name":"SyncHub"}]&connectionToken=GsZKYTf9rwH3NqngtHe5f6eUEcHRqlGYsBDkC2g43FOZs8zP%2FJg%2Fhld1fdm9iO91yPBoxNIqY7N%2FlnlJDCSfFwK8YTnJNztxRVS5aUPt9G4KrIYEpMNNwyucyHILDMqr
08:46:33.9198908 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - LP: OnMessage({"C":"d-555200CA-B,0|C,0|D,2","S":1,"M":[]})
08:46:33.9484163 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - LP Poll: http://192.168.0.84:8080/signalr/poll?clientProtocol=1.4&transport=longPolling&connectionData=[{"Name":"SyncHub"}]&connectionToken=GsZKYTf9rwH3NqngtHe5f6eUEcHRqlGYsBDkC2g43FOZs8zP%2FJg%2Fhld1fdm9iO91yPBoxNIqY7N%2FlnlJDCSfFwK8YTnJNztxRVS5aUPt9G4KrIYEpMNNwyucyHILDMqr&messageId=d-555200CA-B%2C0%7CC%2C0%7CD%2C2
08:46:34.0659311 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - ChangeState(Connecting, Connected)
</code>```

Server:

```<code>SignalR.PerformanceCounterManager Error: 0 : Performance counter failed to load: System.InvalidOperationException: The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
   at System.Diagnostics.PerformanceCounter.InitializeImpl()
   at System.Diagnostics.PerformanceCounter..ctor(String categoryName, String counterName, String instanceName, Boolean readOnly)

...

SignalR.Transports.TransportHeartBeat Information: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 is New.
SignalR.Transports.ServerSentEventsTransport Verbose: 0 : Sending outgoing message. Connection id: 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341, transport: ServerSentEventsTransport, message: data: {"C":"d-555200CA-B,0|C,0|D,1","S":1,"M":[]}

SignalR.Transports.ServerSentEventsTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.ServerSentEventsTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.TransportHeartBeat Verbose: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 exists. Closing previous connection.
SignalR.Transports.ServerSentEventsTransport Information: 0 : End(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.ServerSentEventsTransport Verbose: 0 : Cancel(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.ServerSentEventsTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.ServerSentEventsTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
Client Connected: 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341
SignalR.Transports.TransportHeartBeat Verbose: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 exists. Closing previous connection.
SignalR.Transports.LongPollingTransport Information: 0 : End(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Diagnostics.Debug\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Diagnostics.Debug.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
SignalR.HubDispatcher Verbose: 0 : Sending hub invocation result to connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 using transport LongPollingTransport
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'Microsoft.AspNet.SignalR.Hubs.TypedClientBuilder'.
SignalR.Transports.LongPollingTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Collections.Concurrent\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Collections.Concurrent.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
SignalR.Transports.TransportHeartBeat Verbose: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 exists. Closing previous connection.
SignalR.Transports.LongPollingTransport Information: 0 : End(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Threading\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Threading.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
SignalR.Transports.TransportHeartBeat Verbose: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 exists. Closing previous connection.
SignalR.Transports.LongPollingTransport Information: 0 : End(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Globalization\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Globalization.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
The thread 0x2ca0 has exited with code 0 (0x0).
The thread 0x151c has exited with code 0 (0x0).
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
</code>```

答:
The issue was the target framework for httpRuntime in web.config.

It was set to <httpRuntime/>. Changing it to <httpRuntime targetFramework="4.7.1"/> allows websockets to be successfully negotiated.

I finally found the answer here.

ContentLicense: CC BY-SA 3.0

Body:
I've created a new webservice using SignalR.Core which properly negotiates to use WebSockets.  I also added it to an existing website, but it fails to negotiate both WebSockets and ServerSentEvents, so will always downgrade to use LongPolling.

Both projects target .NET v4.7.1, running on IIS Express 10.  The client is a UWP app using the SignalR.Client library.

Does anyone know what I'm missing?

Client:

08:46:25.9067539 - null - ChangeState(Disconnected, Connecting)
08:46:28.4516671 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - WS Connecting to: ws://192.168.0.84:8080/signalr/connect?clientProtocol=1.4&transport=webSockets&connectionData=[{"Name":"SyncHub"}]&connectionToken=GsZKYTf9rwH3NqngtHe5f6eUEcHRqlGYsBDkC2g43FOZs8zP%2FJg%2Fhld1fdm9iO91yPBoxNIqY7N%2FlnlJDCSfFwK8YTnJNztxRVS5aUPt9G4KrIYEpMNNwyucyHILDMqr
08:46:28.6707519 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - Auto: Failed to connect to using transport webSockets. System.Exception: Internal server error (500). (Exception from HRESULT: 0x801901F4)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.Client.Transports.WebSocketTransport.<OpenWebSocket>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.Client.Transports.WebSocketTransport.<StartWebSocket>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNet.SignalR.Client.Transports.WebSocketTransport.<Start>d__14.MoveNext()
08:46:28.7516001 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - SSE: GET http://192.168.0.84:8080/signalr/connect?clientProtocol=1.4&transport=serverSentEvents&connectionData=[{"Name":"SyncHub"}]&connectionToken=GsZKYTf9rwH3NqngtHe5f6eUEcHRqlGYsBDkC2g43FOZs8zP%2FJg%2Fhld1fdm9iO91yPBoxNIqY7N%2FlnlJDCSfFwK8YTnJNztxRVS5aUPt9G4KrIYEpMNNwyucyHILDMqr
08:46:33.7643871 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - Auto: Failed to connect to using transport serverSentEvents. System.TimeoutException: Transport timed out trying to connect
08:46:33.7763838 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - LP Connect: http://192.168.0.84:8080/signalr/connect?clientProtocol=1.4&transport=longPolling&connectionData=[{"Name":"SyncHub"}]&connectionToken=GsZKYTf9rwH3NqngtHe5f6eUEcHRqlGYsBDkC2g43FOZs8zP%2FJg%2Fhld1fdm9iO91yPBoxNIqY7N%2FlnlJDCSfFwK8YTnJNztxRVS5aUPt9G4KrIYEpMNNwyucyHILDMqr
08:46:33.9198908 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - LP: OnMessage({"C":"d-555200CA-B,0|C,0|D,2","S":1,"M":[]})
08:46:33.9484163 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - LP Poll: http://192.168.0.84:8080/signalr/poll?clientProtocol=1.4&transport=longPolling&connectionData=[{"Name":"SyncHub"}]&connectionToken=GsZKYTf9rwH3NqngtHe5f6eUEcHRqlGYsBDkC2g43FOZs8zP%2FJg%2Fhld1fdm9iO91yPBoxNIqY7N%2FlnlJDCSfFwK8YTnJNztxRVS5aUPt9G4KrIYEpMNNwyucyHILDMqr&messageId=d-555200CA-B%2C0%7CC%2C0%7CD%2C2
08:46:34.0659311 - 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 - ChangeState(Connecting, Connected)

Server:

SignalR.PerformanceCounterManager Error: 0 : Performance counter failed to load: System.InvalidOperationException: The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
   at System.Diagnostics.PerformanceCounter.InitializeImpl()
   at System.Diagnostics.PerformanceCounter..ctor(String categoryName, String counterName, String instanceName, Boolean readOnly)

...

SignalR.Transports.TransportHeartBeat Information: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 is New.
SignalR.Transports.ServerSentEventsTransport Verbose: 0 : Sending outgoing message. Connection id: 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341, transport: ServerSentEventsTransport, message: data: {"C":"d-555200CA-B,0|C,0|D,1","S":1,"M":[]}

SignalR.Transports.ServerSentEventsTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.ServerSentEventsTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.TransportHeartBeat Verbose: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 exists. Closing previous connection.
SignalR.Transports.ServerSentEventsTransport Information: 0 : End(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.ServerSentEventsTransport Verbose: 0 : Cancel(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.ServerSentEventsTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.ServerSentEventsTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
Client Connected: 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341
SignalR.Transports.TransportHeartBeat Verbose: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 exists. Closing previous connection.
SignalR.Transports.LongPollingTransport Information: 0 : End(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Diagnostics.Debug\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Diagnostics.Debug.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
SignalR.HubDispatcher Verbose: 0 : Sending hub invocation result to connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 using transport LongPollingTransport
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'Microsoft.AspNet.SignalR.Hubs.TypedClientBuilder'.
SignalR.Transports.LongPollingTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Collections.Concurrent\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Collections.Concurrent.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
SignalR.Transports.TransportHeartBeat Verbose: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 exists. Closing previous connection.
SignalR.Transports.LongPollingTransport Information: 0 : End(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Information: 0 : CompleteRequest (1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Threading\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Threading.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
SignalR.Transports.TransportHeartBeat Verbose: 0 : Connection 1cf03bfa-cfa6-45b2-b3f7-a342c17c8341 exists. Closing previous connection.
SignalR.Transports.LongPollingTransport Information: 0 : End(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/1/ROOT-1-131551227438578638): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Globalization\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Globalization.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
The thread 0x2ca0 has exited with code 0 (0x0).
The thread 0x151c has exited with code 0 (0x0).
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.TransportHeartBeat Verbose: 0 : KeepAlive(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)
SignalR.Transports.LongPollingTransport Verbose: 0 : DrainWrites(1cf03bfa-cfa6-45b2-b3f7-a342c17c8341)


问:
tflearn DNN gives zero loss
I am using pandas to extract my data. To get an idea of my data I replicated an example dataset...

```<code>data = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
</code>```

which yields a dataset of shape=(100,4)...

```<code>    A   B   C   D
0  75  38  81  58
1  36  92  80  79
2  22  40  19  3
   ...    ...
</code>```

I am using tflearn so I will need a target label as well. So I created a target label by extracting one of the columns from data and then dropped it out of the data variable (I also converted everything to numpy arrays)...

```<code># Target label used for training
labels = np.array(data['A'].values, dtype=np.float32)

# Reshape target label from (100,) to (100, 1)
labels = np.reshape(labels, (-1, 1))

# Data for training minus the target label.
data = np.array(data.drop('A', axis=1).values, dtype=np.float32)
</code>```

Then I take the data and the labels and feed it into the DNN...

```<code># Deep Neural Network.
net = tflearn.input_data(shape=[None, 3])
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 1, activation='softmax')
net = tflearn.regression(net)

# Define model.
model = tflearn.DNN(net)
model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)
</code>```

This seems like it should work, but the output I get is as follows...

Notice that the loss remains at 0, so I am definitely doing something wrong. I don't really know what form my data should be in. How can I get my training to work?

答:
Your actual output is in range 0 to 100 while the activation softmax in  the outermost layer outputs in range [0, 1]. You need to fix that. Also the default loss for tflearn.regression is categorical cross entropy which is used for classification problems and makes no sense in your scenario. You should try L2 loss. The reason you are getting zero error in this setting is that your network predicts 0 for all training examples and if you fit that value in formula for sigmoid cross entropy, loss indeed is zero. Here is its formula , where t[i] denotes the actual probabilities (which doesnt make sense in your problem) and o[i] is the predicted probabilities.

Here is more reasoning about why default choice of loss function is not suitable for your case

Title: tflearn DNN gives zero loss

Body:
I am using pandas to extract my data. To get an idea of my data I replicated an example dataset...

data = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

which yields a dataset of shape=(100,4)...

    A   B   C   D
0  75  38  81  58
1  36  92  80  79
2  22  40  19  3
   ...    ...

I am using tflearn so I will need a target label as well. So I created a target label by extracting one of the columns from data and then dropped it out of the data variable (I also converted everything to numpy arrays)...

# Target label used for training
labels = np.array(data['A'].values, dtype=np.float32)

# Reshape target label from (100,) to (100, 1)
labels = np.reshape(labels, (-1, 1))

# Data for training minus the target label.
data = np.array(data.drop('A', axis=1).values, dtype=np.float32)

Then I take the data and the labels and feed it into the DNN...

# Deep Neural Network.
net = tflearn.input_data(shape=[None, 3])
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 32)
net = tflearn.fully_connected(net, 1, activation='softmax')
net = tflearn.regression(net)

# Define model.
model = tflearn.DNN(net)
model.fit(data, labels, n_epoch=10, batch_size=16, show_metric=True)

This seems like it should work, but the output I get is as follows...

Notice that the loss remains at 0, so I am definitely doing something wrong. I don't really know what form my data should be in. How can I get my training to work?


问:
CRLF tags attached upon FTP upload from a windows to Linux Server
I am uploading the files in a FTP folder from Windows server to a Linux server. Files come in different extensions but can be opened using notepad or notpad++.
I am getting issues that CR & CRLF are getting attached after FTP upload to Linux from Windows.

I am uploading a file from windows in the below format

This is the file after FTP Upload to Linux server. We can see many CR and CRLF tags getting attached, which shouldn't be the case.

I need the files in the below format in Linux (With only LF tags attached)

For FTP from windows to Linux, I am using the Batch Script as below..

```<code>open XXXXXXXXXX.net
UID
PASSWORD
cd METS
cd MARVELRAIL
binary
mput E:\METS+_BULK_UPLOAD\BULK_FOLDERS\OUT\DISCH\*.*
quit
</code>```

Can you help me where I am going wrong and how to beat this issue...
Thank in advance.

答:
If you want the files to be converted to *nix line endings, do not use a binary mode, use an ascii mode.

The ascii mode is the default one, so removing binary command should be enough.

Or you can explicitly use ascii command.

Body:
I am uploading the files in a FTP folder from Windows server to a Linux server. Files come in different extensions but can be opened using notepad or notpad++.
I am getting issues that CR & CRLF are getting attached after FTP upload to Linux from Windows.

I am uploading a file from windows in the below format

This is the file after FTP Upload to Linux server. We can see many CR and CRLF tags getting attached, which shouldn't be the case.

I need the files in the below format in Linux (With only LF tags attached)

For FTP from windows to Linux, I am using the Batch Script as below..

open XXXXXXXXXX.net
UID
PASSWORD
cd METS
cd MARVELRAIL
binary
mput E:\METS+_BULK_UPLOAD\BULK_FOLDERS\OUT\DISCH\*.*
quit

Can you help me where I am going wrong and how to beat this issue...
Thank in advance.


问:
Make a div with background with lines in 50 degrees angle
I need to implement a background with inclined lines into a div or table. To represent that element is finished.
like this example: Background

How can acchive that with CSS?

I dont want an image as background, because i need change attributtes by JQuery and im ussing Bootstrap

答:
try this.

.wrapper {
  color: white;
  background: repeating-linear-gradient( -45deg, #333, #333 10px, #fff 10px, #fff 20px);
  height: 200px;
  width: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
try this.

.wrapper {
  color: white;
  background: repeating-linear-gradient( -45deg, #333, #333 10px, #fff 10px, #fff 20px);
  height: 200px;
  width: 200px;
}

<div class="wrapper"></div>


问:
Cannot set high resolution image(1920x1280) to image view on android 7.0
I run this app lot of devices. less than android 7 and more than android 7, that is fine. but when i run this app on samsung s6(android 7.0) it gives this error

Fatal Exception: java.lang.RuntimeException: Canvas: trying to draw
  too large(120422400bytes) bitmap.
         at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
         at android.graphics.Canvas.drawBitmap(Canvas.java:1420)
         at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:545)
         at android.view.View.getDrawableRenderNode(View.java:18591)
         at android.view.View.drawBackground(View.java:18527)
         at android.view.View.draw(View.java:18315)
         at android.view.View.updateDisplayListIfDirty(View.java:17302)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.updateDisplayListIfDirty(View.java:17297)
         at android.view.View.draw(View.java:18086)
         at android.view.ViewGroup.drawChild(ViewGroup.java:3966)
         at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3752)
         at android.view.View.draw(View.java:18327)
         at com.android.internal.policy.DecorView.draw(DecorView.java:919)
         at android.view.View.updateDisplayListIfDirty(View.java:17302)
         at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:692)
         at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:698)
         at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:806)
         at android.view.ViewRootImpl.draw(ViewRootImpl.java:3135)
         at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2931)
         at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2523)
         at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1522)
         at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7098)
         at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
         at android.view.Choreographer.doCallbacks(Choreographer.java:702)
         at android.view.Choreographer.doFrame(Choreographer.java:638)
         at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
         at android.os.Handler.handleCallback(Handler.java:751)
         at android.os.Handler.dispatchMessage(Handler.java:95)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6682)
         at java.lang.reflect.Method.invoke(Method.java)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

答:
it will throw OutOfMemory error if you try to show too large image in android ,you have to scale it down or resize ,look into this

How to Resize a Bitmap in Android?


问:
can a C++ function be defined using 'virtual inline'?
I see a C++  function being defined as below:

```<code>int virtual inline fun()
{
   return xxx;
}
</code>```

I wonder what it means?
anyone can explain it?

答:
It simply means the code doesn't compile.

Only non-static methods can be virtual. In your example fun is a free function so virtual cannot be applied to it.

Body:
I see a C++  function being defined as below:

int virtual inline fun()
{
   return xxx;
}

I wonder what it means?
anyone can explain it?


问:
Count hits of a specific file with PHP
I have 3 files

index.html

stream.pls

counter.php

How can I show in counter.php the total hits of stream.pls?
I want to see how many times stream.pls is opened/loaded.

I tried this but that's not working:

```<code><?php

define("COUNTER_START_VALUE", 0);
define("COUNTER_LOG", "stream.pls"); //name of file you want to use to save the counter value

/*************************************************************************************************/
function IncrementCounter()
{
   $create_file = !file_exists(COUNTER_LOG);

   if( !($fh = fopen(COUNTER_LOG, $create_file ? "x+b" : "r+b")) )
      return "Error";
   //do an flock here, maybe, I don't know :-)

   //Reading current value of counter:
   if($create_file)
      $count = COUNTER_START_VALUE;
   else
   {
      $count = (int)fread($fh, 9); //reads 9 digits (supposing max 1 billion count)
      rewind($fh);
   }

   //Writing new counter value:
   if(!fwrite($fh, ++$count))
      return "Error";
   if(!fclose($fh);)
      return "Error";

   return str_pad($count, 9, '0', STR_PAD_LEFT);
}

?>
</code>```

答:
I guess you want to display total number of visits to that file ,

Then don't be complicated , simply add variable named $counter as like you added it ,
and then increment it on every file open, or read ..

```<code> if($create_file)
      $count = COUNTER_START_VALUE;
 else {
      fread($fh, 9);
      rewind($fh);
      $count++;
 }
</code>```

or you can use same thing near fopen like ,

```<code>if( !($fh = fopen(COUNTER_LOG, $create_file ? "x+b" : "r+b")) )
      return "Error";
else
    $count++;
</code>```

and better if you declare the $counter at start of this function

```<code>function IncrementCounter()
{
   $create_file = !file_exists(COUNTER_LOG);
   $counter = COUNTER_START_VALUE;
 .
 .
 .
 .
</code>```

I hope this will solve your problem :) :) :)

Title: Count hits of a specific file with PHP

Body:
I have 3 files

index.html

stream.pls

counter.php

How can I show in counter.php the total hits of stream.pls?
I want to see how many times stream.pls is opened/loaded.

I tried this but that's not working:

<?php

define("COUNTER_START_VALUE", 0);
define("COUNTER_LOG", "stream.pls"); //name of file you want to use to save the counter value

/*************************************************************************************************/
function IncrementCounter()
{
   $create_file = !file_exists(COUNTER_LOG);

   if( !($fh = fopen(COUNTER_LOG, $create_file ? "x+b" : "r+b")) )
      return "Error";
   //do an flock here, maybe, I don't know :-)

   //Reading current value of counter:
   if($create_file)
      $count = COUNTER_START_VALUE;
   else
   {
      $count = (int)fread($fh, 9); //reads 9 digits (supposing max 1 billion count)
      rewind($fh);
   }

   //Writing new counter value:
   if(!fwrite($fh, ++$count))
      return "Error";
   if(!fclose($fh);)
      return "Error";

   return str_pad($count, 9, '0', STR_PAD_LEFT);
}

?>

Body:
I guess you want to display total number of visits to that file ,

Then don't be complicated , simply add variable named $counter as like you added it ,
and then increment it on every file open, or read ..

 if($create_file)
      $count = COUNTER_START_VALUE;
 else {
      fread($fh, 9);
      rewind($fh);
      $count++;
 }

or you can use same thing near fopen like ,

if( !($fh = fopen(COUNTER_LOG, $create_file ? "x+b" : "r+b")) )
      return "Error";
else
    $count++;

and better if you declare the $counter at start of this function

function IncrementCounter()
{
   $create_file = !file_exists(COUNTER_LOG);
   $counter = COUNTER_START_VALUE;
 .
 .
 .
 .

I hope this will solve your problem :) :) :)


问:
Unable to save and restore a trained TensorFlow Model
I just read the Deep MNIST for Experts tutorial and modified the  mnist_deep.py code to save the trained model using
saver = tf.train.Saver() before creating the session and
saver.save(sess, './mnist_deep_model', global_step=2000) after the for loop training the model. It appears to be correctly saved since I got the four following files in my working folder:

checkpoint

mnist_deep_model-2000.data-00000-of-00001

mnist_deep_model-2000.indexs

mnist_deep_model-2000.meta

I also modified the mnist_deep.py adding the two following functions to be able to test the model on individual test images, one by one:

```<code>def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)
</code>```

I also added at the end of the main function a loop in which I randomly choose one test image in the test set and try to apply the trained model to each of them with this function. It seems to work since I get the same accuracy in this test loop: 99.2%

Then I wrote a second program: mnist_deep_restore_trained_model.py (also based on the mnist_deep.py source code) trying to restore the previously saved trained model and apply test images to it expecting to get the same accuracy.

Of course, I removed of this program all the code required to create, train and test the model (the deepnn() function and all related functions, tensors creation: x = tf.placeholder(tf.float32, [None, 784]), y_conv, keep_prob = deepnn(x), loss, optimizer, and accuracy stuff...) and I simply restored the saved model this way: (once the session is open)

```<code>saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))
</code>```

I also removed the global variables initialization at the beginning of the session since the values of the global variables should have been restored from the trained model:

But, to be able to apply the model in order to identify the digit of a given test image (cf function identifyDigitInImage(sess, x, y_conv, keep_prob, image)), I still need to get the Tensor variables x, y_conv and keep_prob. So I added the following lines after having restored the model from disk:

```<code>graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
keep_prob = graph.get_tensor_by_name("keep_prob:0")
y_conv = graph.get_tensor_by_name("y_conv:0")
</code>```

Finally, I also added at the end of this second program the same test loop as in the mnist_deep.py expecting to get the same results from this restored model...

Unfortunately, I get an exception on the first call to get_tensor_by_name():

```<code>x = graph.get_tensor_by_name("x:0")
KeyError: "The name 'x:0' refers to a Tensor which does not exist. The operation 'x', does not exist in the graph."
</code>```

The other get_tensor_by_name() calls would also raise this same exception.

What am I doing wrong ? Why is that not possible to get these Tensors this way ?

Here is my full mnist_deep.py source code:

```<code># Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""A deep MNIST classifier using convolutional layers.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import tempfile
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.
  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.
  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  return y_conv, keep_prob

def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                            logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  #graph_location = tempfile.mkdtemp()
  #print('Saving graph to: %s' % graph_location)
  #train_writer = tf.summary.FileWriter(graph_location)
  #train_writer.add_graph(tf.get_default_graph())

  # Prepare a saver to save the trained model:
  saver = tf.train.Saver()

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Save the untrained model:
    saver.save(sess, './mnist_deep_model')

    # Train the model:
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    # Save the trained model:
    saver.save(sess, './mnist_deep_model', global_step=2000)

    # Display the test accuracy:
    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    # Now try to apply the model to randomly choosen test images, one by one:
    stop = False
    count = 0
    ok_count = 0
    while not stop:
        # Choosing a test image index:
        test_image_index = random.randint(0, len(mnist.test.images) - 1)
        test_image = mnist.test.images[test_image_index]

        # Applying the trained model to identify the digit from the test image:
        identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

        # Display the identified digit:
        print("The written digit on the given image has been identified as a {}".format(identified_digit))

        # Check the expected_digit from the test label of the choosen test image:
        expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

        # Display the expected digit:
        print("Actually, the digit is a {}".format(expected_digit))

        # Count the correctly identified digits:
        if identified_digit == expected_digit:
            ok_count += 1

        # Stop the loop after 10000 iterations
        count += 1
        stop = count == 10000

        # Display the measured accuracy during the test loop:
    print("2nd Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
</code>```

And here my full mnist_deep_restore_trained_model.py source code:

```<code># Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================

"""A deep MNIST classifier using convolutional layers.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  with tf.Session() as sess:

    # Restoring the trained model previously saved:
    saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # Trying to get back some required tensors variables from the restored graph:
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("x:0")
    # This call fails with the following exception:
    # KeyError: "The name 'x:0' refers to a Tensor which does not exist. The operation 'x', does not exist in the graph."
    keep_prob = graph.get_tensor_by_name("keep_prob:0")
    y_conv = graph.get_tensor_by_name("y_conv:0")

    # Now try to apply the model to randomly choosen test images, one by one:
    stop = False
    count = 0
    ok_count = 0
    while not stop:
      # Choosing a test image index:
      test_image_index = random.randint(0, len(mnist.test.images) - 1)
      test_image = mnist.test.images[test_image_index]

      # Applying the trained model to identify the digit from the test image:
      identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

      # Display the identified digit:
      print("The written digit on the given image has been identified as a {}".format(identified_digit))

      # Check the expected_digit from the test label of the choosen test image:
      expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

      # Display the expected digit:
      print("Actually, the digit is a {}".format(expected_digit))

      # Count the correctly identified digits:
      if identified_digit == expected_digit:
        ok_count += 1

      # Stop the loop after 10000 iterations
      count += 1
      stop = count == 10000

    # Display the measured accuracy during the test loop:
    print("Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
</code>```

答:
Thanks for your help Maxim. It's working fine now.

Here is my fixed mnist_deep.py code:

```<code># Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import tempfile
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.
  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.
  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32, name='keep_prob')
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.add(tf.matmul(h_fc1_drop, W_fc2), b_fc2, name='y_conv')
  return y_conv, keep_prob

def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784], name = 'x')

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10], name = 'y_')

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                            logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Train the model:
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    # Save the trained model:
    saver = tf.train.Saver()
    saver.save(sess, './mnist_deep_model', global_step=2000)

    # Display the test accuracy:
    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    # Now try to apply the model to randomly choosen test images, one by one:
    count = 0
    ok_count = 0
    while count < 10000:
        # Choosing a test image index:
        test_image_index = random.randint(0, len(mnist.test.images) - 1)
        test_image = mnist.test.images[test_image_index]

        # Applying the trained model to identify the digit from the test image:
        identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

        # Display the identified digit:
        print("The written digit on the given image has been identified as a {}".format(identified_digit))

        # Check the expected_digit from the test label of the choosen test image:
        expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

        # Display the expected digit:
        print("Actually, the digit is a {}".format(expected_digit))

        # Count the correctly identified digits:
        if identified_digit == expected_digit:
            ok_count += 1

        # Stop the loop after 10000 iterations
        count += 1

        # Display the measured accuracy during the test loop:
    print("2nd Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
</code>```

And the corresponding fixed mnist_deep_restore_train_model.py code:

```<code># Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  with tf.Session() as sess:

    # Restoring the trained model previously saved:
    saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # Trying to get back some required tensors variables from the restored graph:
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("x:0")
    keep_prob = graph.get_tensor_by_name("dropout/keep_prob:0")
    y_conv = graph.get_tensor_by_name("fc2/y_conv:0")

    # Now try to apply the model to randomly choosen test images, one by one:
    count = 0
    ok_count = 0
    while count < 10000:
      # Choosing a test image index:
      test_image_index = random.randint(0, len(mnist.test.images) - 1)
      test_image = mnist.test.images[test_image_index]

      # Applying the trained model to identify the digit from the test image:
      identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

      # Display the identified digit:
      print("The written digit on the given image has been identified as a {}".format(identified_digit))

      # Check the expected_digit from the test label of the choosen test image:
      expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

      # Display the expected digit:
      print("Actually, the digit is a {}".format(expected_digit))

      # Count the correctly identified digits:
      if identified_digit == expected_digit:
        ok_count += 1

      # Stop the loop after 10000 iterations
      count += 1

    # Display the measured accuracy during the test loop:
    print("Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
</code>```

Body:
I just read the Deep MNIST for Experts tutorial and modified the  mnist_deep.py code to save the trained model using
saver = tf.train.Saver() before creating the session and
saver.save(sess, './mnist_deep_model', global_step=2000) after the for loop training the model. It appears to be correctly saved since I got the four following files in my working folder:

checkpoint

mnist_deep_model-2000.data-00000-of-00001

mnist_deep_model-2000.indexs

mnist_deep_model-2000.meta

I also modified the mnist_deep.py adding the two following functions to be able to test the model on individual test images, one by one:

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

I also added at the end of the main function a loop in which I randomly choose one test image in the test set and try to apply the trained model to each of them with this function. It seems to work since I get the same accuracy in this test loop: 99.2%

Then I wrote a second program: mnist_deep_restore_trained_model.py (also based on the mnist_deep.py source code) trying to restore the previously saved trained model and apply test images to it expecting to get the same accuracy.

Of course, I removed of this program all the code required to create, train and test the model (the deepnn() function and all related functions, tensors creation: x = tf.placeholder(tf.float32, [None, 784]), y_conv, keep_prob = deepnn(x), loss, optimizer, and accuracy stuff...) and I simply restored the saved model this way: (once the session is open)

saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
saver.restore(sess, tf.train.latest_checkpoint('./'))

I also removed the global variables initialization at the beginning of the session since the values of the global variables should have been restored from the trained model:

But, to be able to apply the model in order to identify the digit of a given test image (cf function identifyDigitInImage(sess, x, y_conv, keep_prob, image)), I still need to get the Tensor variables x, y_conv and keep_prob. So I added the following lines after having restored the model from disk:

graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
keep_prob = graph.get_tensor_by_name("keep_prob:0")
y_conv = graph.get_tensor_by_name("y_conv:0")

Finally, I also added at the end of this second program the same test loop as in the mnist_deep.py expecting to get the same results from this restored model...

Unfortunately, I get an exception on the first call to get_tensor_by_name():

x = graph.get_tensor_by_name("x:0")
KeyError: "The name 'x:0' refers to a Tensor which does not exist. The operation 'x', does not exist in the graph."

The other get_tensor_by_name() calls would also raise this same exception.

What am I doing wrong ? Why is that not possible to get these Tensors this way ?

Here is my full mnist_deep.py source code:

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""A deep MNIST classifier using convolutional layers.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import tempfile
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.
  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.
  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  return y_conv, keep_prob

def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                            logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  #graph_location = tempfile.mkdtemp()
  #print('Saving graph to: %s' % graph_location)
  #train_writer = tf.summary.FileWriter(graph_location)
  #train_writer.add_graph(tf.get_default_graph())

  # Prepare a saver to save the trained model:
  saver = tf.train.Saver()

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Save the untrained model:
    saver.save(sess, './mnist_deep_model')

    # Train the model:
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    # Save the trained model:
    saver.save(sess, './mnist_deep_model', global_step=2000)

    # Display the test accuracy:
    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    # Now try to apply the model to randomly choosen test images, one by one:
    stop = False
    count = 0
    ok_count = 0
    while not stop:
        # Choosing a test image index:
        test_image_index = random.randint(0, len(mnist.test.images) - 1)
        test_image = mnist.test.images[test_image_index]

        # Applying the trained model to identify the digit from the test image:
        identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

        # Display the identified digit:
        print("The written digit on the given image has been identified as a {}".format(identified_digit))

        # Check the expected_digit from the test label of the choosen test image:
        expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

        # Display the expected digit:
        print("Actually, the digit is a {}".format(expected_digit))

        # Count the correctly identified digits:
        if identified_digit == expected_digit:
            ok_count += 1

        # Stop the loop after 10000 iterations
        count += 1
        stop = count == 10000

        # Display the measured accuracy during the test loop:
    print("2nd Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

And here my full mnist_deep_restore_trained_model.py source code:

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================

"""A deep MNIST classifier using convolutional layers.
See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  with tf.Session() as sess:

    # Restoring the trained model previously saved:
    saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # Trying to get back some required tensors variables from the restored graph:
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("x:0")
    # This call fails with the following exception:
    # KeyError: "The name 'x:0' refers to a Tensor which does not exist. The operation 'x', does not exist in the graph."
    keep_prob = graph.get_tensor_by_name("keep_prob:0")
    y_conv = graph.get_tensor_by_name("y_conv:0")

    # Now try to apply the model to randomly choosen test images, one by one:
    stop = False
    count = 0
    ok_count = 0
    while not stop:
      # Choosing a test image index:
      test_image_index = random.randint(0, len(mnist.test.images) - 1)
      test_image = mnist.test.images[test_image_index]

      # Applying the trained model to identify the digit from the test image:
      identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

      # Display the identified digit:
      print("The written digit on the given image has been identified as a {}".format(identified_digit))

      # Check the expected_digit from the test label of the choosen test image:
      expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

      # Display the expected digit:
      print("Actually, the digit is a {}".format(expected_digit))

      # Count the correctly identified digits:
      if identified_digit == expected_digit:
        ok_count += 1

      # Stop the loop after 10000 iterations
      count += 1
      stop = count == 10000

    # Display the measured accuracy during the test loop:
    print("Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

Body:
Thanks for your help Maxim. It's working fine now.

Here is my fixed mnist_deep.py code:

# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import tempfile
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.
  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.
  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32, name='keep_prob')
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.add(tf.matmul(h_fc1_drop, W_fc2), b_fc2, name='y_conv')
  return y_conv, keep_prob

def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784], name = 'x')

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10], name = 'y_')

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                            logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Train the model:
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    # Save the trained model:
    saver = tf.train.Saver()
    saver.save(sess, './mnist_deep_model', global_step=2000)

    # Display the test accuracy:
    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    # Now try to apply the model to randomly choosen test images, one by one:
    count = 0
    ok_count = 0
    while count < 10000:
        # Choosing a test image index:
        test_image_index = random.randint(0, len(mnist.test.images) - 1)
        test_image = mnist.test.images[test_image_index]

        # Applying the trained model to identify the digit from the test image:
        identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

        # Display the identified digit:
        print("The written digit on the given image has been identified as a {}".format(identified_digit))

        # Check the expected_digit from the test label of the choosen test image:
        expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

        # Display the expected digit:
        print("Actually, the digit is a {}".format(expected_digit))

        # Count the correctly identified digits:
        if identified_digit == expected_digit:
            ok_count += 1

        # Stop the loop after 10000 iterations
        count += 1

        # Display the measured accuracy during the test loop:
    print("2nd Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

And the corresponding fixed mnist_deep_restore_train_model.py code:

# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys
import random

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def indexMax(list):
  """indexMax returns the index of the max element of the list."""
  return list.index(max(list))

def identifyDigitInImage(sess, x, y_conv, keep_prob, image):
  """identifyDigitInImage apply the trained model to given image to identify the represented digit."""
  result = sess.run(y_conv, {x:[image], keep_prob: 1.0})[0].tolist()
  return indexMax(result)

def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  with tf.Session() as sess:

    # Restoring the trained model previously saved:
    saver = tf.train.import_meta_graph('./mnist_deep_model-2000.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))

    # Trying to get back some required tensors variables from the restored graph:
    graph = tf.get_default_graph()
    x = graph.get_tensor_by_name("x:0")
    keep_prob = graph.get_tensor_by_name("dropout/keep_prob:0")
    y_conv = graph.get_tensor_by_name("fc2/y_conv:0")

    # Now try to apply the model to randomly choosen test images, one by one:
    count = 0
    ok_count = 0
    while count < 10000:
      # Choosing a test image index:
      test_image_index = random.randint(0, len(mnist.test.images) - 1)
      test_image = mnist.test.images[test_image_index]

      # Applying the trained model to identify the digit from the test image:
      identified_digit = identifyDigitInImage(sess, x, y_conv, keep_prob, test_image)

      # Display the identified digit:
      print("The written digit on the given image has been identified as a {}".format(identified_digit))

      # Check the expected_digit from the test label of the choosen test image:
      expected_digit = indexMax(mnist.test.labels[test_image_index].tolist())

      # Display the expected digit:
      print("Actually, the digit is a {}".format(expected_digit))

      # Count the correctly identified digits:
      if identified_digit == expected_digit:
        ok_count += 1

      # Stop the loop after 10000 iterations
      count += 1

    # Display the measured accuracy during the test loop:
    print("Test accuracy = {}%".format(100 * (ok_count / count)))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)


问:
How do I select a node within a template string in html?
Create an element and pass it an innerHTML string.

let mydiv = document.createElement('div');
mydiv.innerHTML = "

Intro

Hello Example

";
console.log(mydiv.getElementByID("greet"))```
</div>
</div>
</p>

<p>.. How do I get the element with id='greet'?</p>

```mydiv.getElementbyID('greet')   //doesn't work.
```

答:
```<code>mydiv.querySelector('#greet')
</code>```

This is one very subtle difference between these selectors. With query selector, we can query string templates. Inspired from here.

Body:
Create an element and pass it an innerHTML string.

let mydiv = document.createElement('div');
mydiv.innerHTML = "

Intro

Hello Example

";
console.log(mydiv.getElementByID("greet"))

.. How do I get the element with id='greet'?

mydiv.getElementbyID('greet')   //doesn't work.

Body:
mydiv.querySelector('#greet')

This is one very subtle difference between these selectors. With query selector, we can query string templates. Inspired from here.


答:
Try the following way,</p>

```<code>for (var child = mydiv.firstChild; child; child = child.nextSibling) {
   if(child.id == "greet") {
      console.log(child);
   }
}
</code>```

Title: How do I select a node within a template string in html?

Body:
Try the following way,

for (var child = mydiv.firstChild; child; child = child.nextSibling) {
   if(child.id == "greet") {
      console.log(child);
   }
}


问:
MuleSoft: How to refer to file nested under resource folder
I am doing a Mulesoft project by Mule-Anypoint studio.

Recently I categorized my resource files (xml, csv, xsl..) into nested folders under "resources" folder. (ex: resources/FlowResources/flowA/resource-a.csv) and updated the components to corresponding path. Everything works fine but when deploying to CloudHub throws following error:

Your application has failed with exception com.mulesoft.mmc.agent.v3.dto.DeploymentException: Unable to load FlowResources/flowA/resource-a.csv. It works fine again if I move the files up front to resources folder.

Is it some kind of limitation when we deploy to CloudHub? Cannot locate file in nested resource folders?

答: Your project hierarchy should look like as follows :


问:
Chess - Avoiding Infinite Recursion when Preventing Check
I have an algorithm as follows to prevent a player from choosing a move that puts it into check:

Fake the move (by copying the board and working on the copied board)

Get all legal opponent moves after the move has been faked.

If one of the legal moves can attack the player's king, then the originally faked move cannot be chosen.

However, in step 2 (bolded), the program must check that whatever the other player does does not move the other player into check. This creates an infinite recursion that I'm not sure algorithmically how to avoid. What suggestions do people have for this situation?

答:
You can define another function which returns true if the player's piece can move to the cell of the opponent's king and false otherwise.

Now call this function for the opponent when you fake a move.


问:
select single item from a collection : Python
I created a utility function to return the expected single item from an generator expression

```<code>print one(name for name in ('bob','fred') if name=='bob')
</code>```

Is this a good way to go about it?

```<code>def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')
</code>```

答:
Here is my try  at the one() function. I would avoid the explicit .next() call and use a for loop instead.

```<code>def one(seq):
    counter = 0
    for elem in seq:
        result = elem
        counter += 1
        if counter > 1:
            break
    if counter == 0:
        raise Exception('No values')
    elif counter > 1:
        raise Exception('Too many values')
    return result
</code>```

OwnerDisplayName: GHZ

Body:
I created a utility function to return the expected single item from an generator expression

print one(name for name in ('bob','fred') if name=='bob')

Is this a good way to go about it?

def one(g):
    try:
        val = g.next()
        try:
            g.next()
        except StopIteration:
            return val
        else:
            raise Exception('Too many values')
    except StopIteration:
        raise Exception('No values')

LastEditorDisplayName: nosklo

Body:
Here is my try  at the one() function. I would avoid the explicit .next() call and use a for loop instead.

def one(seq):
    counter = 0
    for elem in seq:
        result = elem
        counter += 1
        if counter > 1:
            break
    if counter == 0:
        raise Exception('No values')
    elif counter > 1:
        raise Exception('Too many values')
    return result

OwnerDisplayName: unbeknown

LastEditorDisplayName: unbeknown


问:
Risks of using performSelectorInBackground?
I have been doing some testing with ObjectiveResource (iOS->Rails bridge). Things seem to work, but the library is synchronous (or maybe not, but the mailing list that supports it is a mess).

I'm wondering what the pitfalls are to just running all calls in a performSelectorInBackground... in small tests it seems to work fine, but that's the case with many things that are wrong.

The only caveat I've noticed is that you have to create an Autorelease Pool in the method called by performSelectorInBackground (and then you should only call drain and not release?).

答:
performSelectorInBackground: uses threads behind the scenes, and the big thing with threads is that any piece of code touched by more than one is a minefield for race conditions and other subtle bugs. This obviously means drawing to the screen is off-limits outside the main thread. But there are a lot of other libraries that are also not threadsafe, and any code using those is also tainted.

Basically, thread-safety is something you have to intentionally put in your code or it's probably not there. ObjectiveResource doesn't make any claims to it, so already I would be nervous. Glancing at the source, it looks like it mainly uses the Foundation URL loading machinery, which is threadsafe IIRC. But the ObjectiveResource code itself is not. Just at a glance, all of the class methods use static variables, which means they're all subject to race conditions if you performSelectorInBackground: more than once with code that uses them.

It looks like the 1.1 branch on their Github has explicit support for async through a ConnectionManager class. Probably better off using that (though this is essentially unmaintained code, so caveat emptor).