问:
SDL2 window and fullscreen-window each on its own screen
I use macOS 10.12 with two screens. Now I want to create two windows with SDL2.0.5. One window (400x400pixel) on the one screen/monitor and the other window as a fullscreen-window on the second screen/monitor. This works well so far, but if I click/focus on the first window(400x400), the second window/screen fades to black and stays black as long the application is running.

Note: SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); does not help.

Is it possible to create such windows as described?

答:
This should be possible, but it might be a Mac-specific bug. I'll check this today, but if you don't hear back, please feel free to file a bug at https://bugzilla.libsdl.org/ about it!

Thanks,
--ryan.


来源: stackexchange

问:
Optomised Algorithm for keeping track of network packets (replay attack prevention)
I'm implementing a network server that processes udp packets. I want to  avoid replay attacks, where an attacker could copy udp packets, and replay them later in time. I way toying with idea that i could hash packet and store this value in a hash table. I can then do the same process everytime a packet is received then look it up in the hash table. If it's already exists then we reject the packet, however if we never seen it (the entry does not exist) we store it for future use.

Now, what hash algorithm would be suitable for this? Do i need something other than hash table? As there are a lot of udp packets being received i want this to work in O(1)!!!!!! ;-), is this possible?

Obviously the longer i 'remember' hashes, the more storage (state) i will need to allocate, can a hash table grow and shrink dynamically over time?

I maybe way off here, i may not need a hash table at all! i'm open to idea's!!

答:
Do you have control over the content of the packet? If so, add a hash to the content  and use that - which moves the hashing effort to the sender. You could also include a validity period so that a) you know you can discard any record of a packet after that time and b) a packet stored by an attacker becomes useless after that time. You would want to encrypt the time stamp in some way so the attacker can't just update the time stamp.

Other techniques can be found on Wikipedia

ContentLicense: CC BY-SA 2.5


问:
Form Submit 404 Not Found Error
Hi I am currently learning NodeJS and the Express framework, but I am having issue with when I try to submit the form it suppose to go the '/users/register' URL but it seems that my app.js is not finding the register.jade file although I have a register.jade under the view folder. Here is some of my codes:

register.jade:

```<code>extends layout

block content
    h1 Register
    p Please register using the form below
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/users/register', enctype='multipart/form-data') ...
</code>```

user.js:

```<code>router.post('/users/register', function(req, res, next) { ... });
</code>```

app.js:

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var local = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
...
app.use('/', index);
app.use('/users', users);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
</code>```

Error on my Git Bash:

Error from the browser:

Here is my folder structure:

I am not sure why it errors out 404, thank you in advance!

答:
As per the path mouting from your code, the url path in browser should be

localhost:3000/users/users/register

Either you can make change in

```<code>router.post('/users/register', function(req, res, next) { ... });
</code>```

to

```<code>router.post('/register', function(req, res, next) { ... });
</code>```

OR only make change in

```<code>app.use('/users', users);
</code>```

to

```<code>app.use(users);
</code>```

where your url path will be localhost:3000/users/register

ContentLicense: CC BY-SA 3.0

Title: Form Submit 404 Not Found Error

Body:
Hi I am currently learning NodeJS and the Express framework, but I am having issue with when I try to submit the form it suppose to go the '/users/register' URL but it seems that my app.js is not finding the register.jade file although I have a register.jade under the view folder. Here is some of my codes:

register.jade:

extends layout

block content
    h1 Register
    p Please register using the form below
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/users/register', enctype='multipart/form-data') ...

user.js:

router.post('/users/register', function(req, res, next) { ... });

app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var local = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
...
app.use('/', index);
app.use('/users', users);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

Error on my Git Bash:

Error from the browser:

Here is my folder structure:

I am not sure why it errors out 404, thank you in advance!

Body:
As per the path mouting from your code, the url path in browser should be

localhost:3000/users/users/register

Either you can make change in

router.post('/users/register', function(req, res, next) { ... });

to

router.post('/register', function(req, res, next) { ... });

OR only make change in

app.use('/users', users);

to

app.use(users);

where your url path will be localhost:3000/users/register


问:
How to parse a single TFrecord file
To read tfrecords:

```<code>reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(...)
</code>```

TFRecordReader reads examples from a file queue.
But how to read a single example from a particular file synchronically(without a queue). like

```<code>file_buf = tf.read_file(filename)
serialized_example = get_train_example(file_buf)
features = tf.parse_single_example(...)
</code>```

how to implement the get_train_example function

答:
Not sure if this exactly what you're looking for, but you can do it this way without a queue:</p>

```<code>tf_record = "path/to/my.tfrecord"
e = tf.python_io.tf_record_iterator(tf_record).next()
single_example = tf.parse_single_example(e, features=features)
</code>```

Title: How to parse a single TFrecord file

Body:
To read tfrecords:

reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(...)

TFRecordReader reads examples from a file queue.
But how to read a single example from a particular file synchronically(without a queue). like

file_buf = tf.read_file(filename)
serialized_example = get_train_example(file_buf)
features = tf.parse_single_example(...)

how to implement the get_train_example function

Body:
Not sure if this exactly what you're looking for, but you can do it this way without a queue:

tf_record = "path/to/my.tfrecord"
e = tf.python_io.tf_record_iterator(tf_record).next()
single_example = tf.parse_single_example(e, features=features)


问:
ScrollTop() function, scroll time
When function is called, the page scrolls up to the top, but I need to wait for as long as the animate time is set to, to be able to scroll down again. for example if I say

$('html, body').animate({ scrollTop: 0 }, 800);

It makes me wait for a while to be able to scroll down again, but if I write

$('html, body').animate({ scrollTop: 0 }, 10);

It scrolls up a lot faster, but I will be able to immediately scroll down again! How can I use 800 (so the animate acts cooler) but avoid waiting for scrolling down again?

```<code>$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.goToTop').fadeIn();
    } else {
        $('.goToTop').fadeOut();
    }
    $('#goToTop').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 800);
        return false;
    });
});
</code>```

答:
you can stop any ongoing animation using the following code .

```<code>$( 'html,body' ).stop();
</code>```

edit: the animation has to stop only if the scroll was triggered by a human. Heres a working fiddle https://jsfiddle.net/sjp3xngo/4/

Title: ScrollTop() function, scroll time

Body:
When function is called, the page scrolls up to the top, but I need to wait for as long as the animate time is set to, to be able to scroll down again. for example if I say

$('html, body').animate({ scrollTop: 0 }, 800);

It makes me wait for a while to be able to scroll down again, but if I write

$('html, body').animate({ scrollTop: 0 }, 10);

It scrolls up a lot faster, but I will be able to immediately scroll down again! How can I use 800 (so the animate acts cooler) but avoid waiting for scrolling down again?

$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('.goToTop').fadeIn();
    } else {
        $('.goToTop').fadeOut();
    }
    $('#goToTop').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 800);
        return false;
    });
});

Body:
you can stop any ongoing animation using the following code .

$( 'html,body' ).stop();

edit: the animation has to stop only if the scroll was triggered by a human. Heres a working fiddle https://jsfiddle.net/sjp3xngo/4/


问:
Python: How to call a method from another module?
I have 2 files written in python. main.py looks like this:

```<code>import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cats.cat.talk()
</code>```

and cats.py that looks like this:

```<code>class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self):
        dog.talk()
cat = Cat("pus")
cat.MakeDogTalk()
</code>```

as you can see, i am trying to make the dog talk from the cats module, is there some way to make this work? My real world app looks nothing like this btw...
of course,now i get this error:

```<code>line 9, in MakeDogTalk
dog.talk()
NameError: name 'dog' is not defined
</code>```

答:
Generally, you should try to minimize the amount of file-level code in a module. In other words, if you intend to import a file, the executable code in that file should be inside a function or class when possible. cat = Cat("pus") and cat.MakeDogTalk() aren't inside a function or class, so I'd move them to main.py.

dog isn't going to be visible inside MakeDogTalk, so I would pass dog as a parameter to either the Cat constructor, or the MakeDogTalk method.

Approach 1: passing the parameter into the constructor

```<code>import cats
#main.py
class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cat = cats.Cat("pus", dog)
cat.MakeDogTalk()
cat.talk()

#cats.py
class Cat():
    def __init__(self, name, dog):
        self.name = name
        self.dog = dog
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self):
        self.dog.talk()
</code>```

Approach 2: passing the parameter into the method

```<code>import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cat = cats.Cat("pus")
cat.MakeDogTalk(dog)
cat.talk()

#cats.py
class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self, dog):
        dog.talk()
</code>```

It would also be simple to keep all of your dog-based logic exclusive to main.py:

```<code>#main.py
import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cat = cats.Cat("pus")
dog.talk()
cat.talk()

#cats.py
class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
</code>```

... But I assume you have a good reason in your real code to have the Cat handle it.

If it's really absolutely necessary to keep cat = Cat("pus") inside cats.py, then you'll have to put it inside a function. If it stays at the file-level scope, then MakeDogTalk will execute before import cats finishes executing, which occurs before the Dog class even exists, so that's a no-go. This adds a small complication that cats.cat will no longer be accessible from main.py, but you can still retrieve the object by returning it from the function call.

```<code>#main.py
import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cat = cats.do_cat_thing(dog)
cat.talk()

#cats.py
class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self, dog):
        dog.talk()

def do_cat_thing(dog):
    cat = Cat("pus")
    cat.MakeDogTalk(dog)
    return cat
</code>```

It may also make sense to put the Dog class in its own file, too. Since the Cat class depends on the Dog class, the cats file should import the dogs file. This way, you can keep your cat = Cat("pus") in cats.py and at the file-level scope, if that's necessary for some reason.

```<code>#main.py
import cats

cats.cat.talk()

#cats.py
import dogs

class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self):
        dogs.dog.talk()

cat = Cat("pus")
cat.MakeDogTalk()

#dogs.py
class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
</code>```

Body:
I have 2 files written in python. main.py looks like this:

import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cats.cat.talk()

and cats.py that looks like this:

class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self):
        dog.talk()
cat = Cat("pus")
cat.MakeDogTalk()

as you can see, i am trying to make the dog talk from the cats module, is there some way to make this work? My real world app looks nothing like this btw...
of course,now i get this error:

line 9, in MakeDogTalk
dog.talk()
NameError: name 'dog' is not defined

Body:
Generally, you should try to minimize the amount of file-level code in a module. In other words, if you intend to import a file, the executable code in that file should be inside a function or class when possible. cat = Cat("pus") and cat.MakeDogTalk() aren't inside a function or class, so I'd move them to main.py.

dog isn't going to be visible inside MakeDogTalk, so I would pass dog as a parameter to either the Cat constructor, or the MakeDogTalk method.

Approach 1: passing the parameter into the constructor

import cats
#main.py
class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cat = cats.Cat("pus", dog)
cat.MakeDogTalk()
cat.talk()

#cats.py
class Cat():
    def __init__(self, name, dog):
        self.name = name
        self.dog = dog
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self):
        self.dog.talk()

Approach 2: passing the parameter into the method

import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cat = cats.Cat("pus")
cat.MakeDogTalk(dog)
cat.talk()

#cats.py
class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self, dog):
        dog.talk()

It would also be simple to keep all of your dog-based logic exclusive to main.py:

#main.py
import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cat = cats.Cat("pus")
dog.talk()
cat.talk()

#cats.py
class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)

... But I assume you have a good reason in your real code to have the Cat handle it.

If it's really absolutely necessary to keep cat = Cat("pus") inside cats.py, then you'll have to put it inside a function. If it stays at the file-level scope, then MakeDogTalk will execute before import cats finishes executing, which occurs before the Dog class even exists, so that's a no-go. This adds a small complication that cats.cat will no longer be accessible from main.py, but you can still retrieve the object by returning it from the function call.

#main.py
import cats

class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")
cat = cats.do_cat_thing(dog)
cat.talk()

#cats.py
class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self, dog):
        dog.talk()

def do_cat_thing(dog):
    cat = Cat("pus")
    cat.MakeDogTalk(dog)
    return cat

It may also make sense to put the Dog class in its own file, too. Since the Cat class depends on the Dog class, the cats file should import the dogs file. This way, you can keep your cat = Cat("pus") in cats.py and at the file-level scope, if that's necessary for some reason.

#main.py
import cats

cats.cat.talk()

#cats.py
import dogs

class Cat():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("my name is "+self.name)
    def MakeDogTalk(self):
        dogs.dog.talk()

cat = Cat("pus")
cat.MakeDogTalk()

#dogs.py
class Dog():
    def __init__(self, name):
        self.name = name
    def talk(self):
        print("My name is "+self.name)

dog = Dog("Boxer")


问:
Handle single server and multiple clients in c++
I am totally new to socket programming.I'm trying to understand the different practices when it comes to socket programming and handling multiple connections.
I have achieved the following functionality so for.

server connect to multiple clients. c1,c2,c3......cn.

server send a time-slot to client.

server send message to client for transmitting message.(to transmit

message in limited duration)

client send message within limited time period

once first connected client is time over server send message to next
client for transmitting message and so.

Here is my working code.

Server.cpp

```<code>    #include "stdafx.h"
    #pragma comment(lib,"ws2_32.lib")
    #include <WinSock2.h>
    #include <string>
    #include <iostream>
    #include<conio.h>

    #define DEFAULT_NC_TIME  20
    #define MAX_CLIENTS 2
    SOCKET Connections[MAX_CLIENTS];
    int TotalConnections = 0;

    #include <vector>
    #include<time.h>

void wait ( int seconds )
{
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}
}

void ClientHandlerThread(int index) //index = the index in the SOCKET Connections array
    {
    int bufferlength; //Holds the length of the message a client sent
    while (true)
    {
        recv(Connections[index], (char*)&bufferlength, sizeof(int), NULL); //get buffer length
        char * buffer = new char[bufferlength+1]; //Allocate buffer
        buffer[bufferlength] = '\0';
        recv(Connections[index], buffer, bufferlength, NULL); //get buffer message from client
        std::cout << buffer << std::endl;
        delete[] buffer;
    }
    }

void emitMessageToClient(int indexOfClient, int ts){
        std::string buftest="You are ready to transmit Message.\n";
        int size = buftest.size(); //Get size of message in bytes and store it in int size
        send(Connections[indexOfClient], (char*)&ts, sizeof(int), NULL); //send Timeslot Duration to the client i
        send(Connections[indexOfClient], (char*)&size, sizeof(int), NULL); //send Size of message
        send(Connections[indexOfClient], buftest.c_str(), buftest.size(), NULL); //send Message
        }

int main()
    {
    //Winsock Startup
    WSAData wsaData;
    WORD DllVersion = MAKEWORD(2, 1);
    if (WSAStartup(DllVersion, &wsaData) != 0)
    {
        MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
        return 0;
    }

    SOCKADDR_IN addr;
    int addrlen = sizeof(addr);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    addr.sin_port = htons(1111);
    addr.sin_family = AF_INET;

    SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);
    bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
    listen(sListen, SOMAXCONN);

    SOCKET newConnection; //Socket to hold the client's connection
    int ConnectionCounter = 0; //# of client connections
    for (int i = 0; i < MAX_CLIENTS; i++)
    {

        newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
        if (newConnection == 0)
        {
            std::cout << "Failed to accept the client's connection." << std::endl;
        }
        else
        {
            std::cout << "Client "<<i<<" Connected!" << std::endl;
            Connections[i] = newConnection;
            TotalConnections += 1; //Increment total # of clients that have connected
        }
    }

    int ts = DEFAULT_NC_TIME / (TotalConnections + 1); // caculating time slot for each of connected node including server
    std::cout<<"\nPress any key to start transmission: ";
    getche();
    for(int i= 0; i < TotalConnections; i++){

        emitMessageToClient(i, ts);
        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(i), NULL, NULL);
        wait(ts);
        if(i == (TotalConnections - 1)){
           i = 0;
        }
    }
    system("pause");
    return 0;
}
</code>```

Client.cpp

```<code>        #include "stdafx.h"
    #pragma comment(lib,"ws2_32.lib") //Required for WinSock
    #include <WinSock2.h> //For win sockets
    #include <string> //For std::string
    #include <iostream> //For std::cout, std::endl, std::cin.getline
    #include <time.h>
    #include <vector>
    #include <conio.h>
    SOCKET Connection;//This client's connection to the server

    void wait ( int seconds )
    {
        clock_t endwait;
        endwait = clock () + seconds * CLOCKS_PER_SEC ;
        while (clock() < endwait) {}
    }

    void ClientThread()
    {
        int bufferlength; //Holds the length of the message we are receiving
        int ts; // holds timeslot duration for this client
        while (true)
        {
            recv(Connection, (char*)&ts, sizeof(int), NULL); //receive timeslot
            recv(Connection, (char*)&bufferlength, sizeof(int), NULL); //receive bufferlength
            char * buffer = new char[bufferlength+1];
            buffer[bufferlength] = '\0';
            recv(Connection, buffer, bufferlength, NULL);
            std::cout << buffer << std::endl; //print out buffer
            std::string userinput; //holds the user's chat message

            for (int n= ts; n>0; n--)
           {
            userinput = "First client sending message...";
            int bufferlength = userinput.size(); //Find buffer length
            send(Connection, (char*)&bufferlength, sizeof(int), NULL); //Send length of buffer
            send(Connection, userinput.c_str(), bufferlength, NULL); //Send buffer
            wait (1);
           }
            delete[] buffer; //Deallocate buffer
        }
    }

    int main()
    {
        //Winsock Startup
        WSAData wsaData;
        WORD DllVersion = MAKEWORD(2, 1);
        if (WSAStartup(DllVersion, &wsaData) != 0)
        {
            MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
            return 0;
        }

        SOCKADDR_IN addr;
        int sizeofaddr = sizeof(addr);
        addr.sin_addr.s_addr = inet_addr("127.0.0.1");
        addr.sin_port = htons(1111);
        addr.sin_family = AF_INET;

        Connection = socket(AF_INET, SOCK_STREAM, NULL);
        if (connect(Connection, (SOCKADDR*)&addr, sizeofaddr) != 0)
        {
            MessageBoxA(NULL, "Failed to Connect", "Error", MB_OK | MB_ICONERROR);
            return 0; //Failed to Connect
        }

        std::cout << "Connected!" << std::endl;
        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientThread, NULL, NULL, NULL);

        getche();
        return 0;
    }
</code>```

once server send message to all his connected clients.Server wants to send message again to his First client to transmit message again.(cyclically)

Problem

How can I achieve if server talk all his clients c1,c2,c3 to Cn and again talk to his first client C1.(cyclically) I have used this check

```<code> if(i == (TotalConnections - 1)){
       i = 0;
 }
</code>```

but it crash the program.

答:
By setting i back to 0 you create an infinite loop because i never gets large enough for the loop to end.

```<code>for(int i= 0; i < TotalConnections; i++) {

    emitMessageToClient(i, ts);
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(i), NULL, NULL);
    wait(ts);

    // This will create an infinite loop
    if(i == (TotalConnections - 1))
    {
        i = 0;
    }
}
</code>```

What you can do is wait until the loop has finished to re-visit the first connection:

```<code>for(int i= 0; i < TotalConnections; i++) {

    emitMessageToClient(i, ts);
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(i), NULL, NULL);
    wait(ts);
}

// now the loop is over, revisit the first connection
// if it exists
if(TotalConnections > 0) {

    emitMessageToClient(0, ts);
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(0), NULL, NULL);
    wait(ts);
}
</code>```

Body:
I am totally new to socket programming.I'm trying to understand the different practices when it comes to socket programming and handling multiple connections.
I have achieved the following functionality so for.

server connect to multiple clients. c1,c2,c3......cn.

server send a time-slot to client.

server send message to client for transmitting message.(to transmit

message in limited duration)

client send message within limited time period

once first connected client is time over server send message to next
client for transmitting message and so.

Here is my working code.

Server.cpp

    #include "stdafx.h"
    #pragma comment(lib,"ws2_32.lib")
    #include <WinSock2.h>
    #include <string>
    #include <iostream>
    #include<conio.h>

    #define DEFAULT_NC_TIME  20
    #define MAX_CLIENTS 2
    SOCKET Connections[MAX_CLIENTS];
    int TotalConnections = 0;

    #include <vector>
    #include<time.h>

void wait ( int seconds )
{
    clock_t endwait;
    endwait = clock () + seconds * CLOCKS_PER_SEC ;
    while (clock() < endwait) {}
}

void ClientHandlerThread(int index) //index = the index in the SOCKET Connections array
    {
    int bufferlength; //Holds the length of the message a client sent
    while (true)
    {
        recv(Connections[index], (char*)&bufferlength, sizeof(int), NULL); //get buffer length
        char * buffer = new char[bufferlength+1]; //Allocate buffer
        buffer[bufferlength] = '\0';
        recv(Connections[index], buffer, bufferlength, NULL); //get buffer message from client
        std::cout << buffer << std::endl;
        delete[] buffer;
    }
    }

void emitMessageToClient(int indexOfClient, int ts){
        std::string buftest="You are ready to transmit Message.\n";
        int size = buftest.size(); //Get size of message in bytes and store it in int size
        send(Connections[indexOfClient], (char*)&ts, sizeof(int), NULL); //send Timeslot Duration to the client i
        send(Connections[indexOfClient], (char*)&size, sizeof(int), NULL); //send Size of message
        send(Connections[indexOfClient], buftest.c_str(), buftest.size(), NULL); //send Message
        }

int main()
    {
    //Winsock Startup
    WSAData wsaData;
    WORD DllVersion = MAKEWORD(2, 1);
    if (WSAStartup(DllVersion, &wsaData) != 0)
    {
        MessageBoxA(NULL, "WinSock startup failed", "Error", MB_OK | MB_ICONERROR);
        return 0;
    }

    SOCKADDR_IN addr;
    int addrlen = sizeof(addr);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    addr.sin_port = htons(1111);
    addr.sin_family = AF_INET;

    SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);
    bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
    listen(sListen, SOMAXCONN);

    SOCKET newConnection; //Socket to hold the client's connection
    int ConnectionCounter = 0; //# of client connections
    for (int i = 0; i < MAX_CLIENTS; i++)
    {

        newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
        if (newConnection == 0)
        {
            std::cout << "Failed to accept the client's connection." << std::endl;
        }
        else
        {
            std::cout << "Client "<<i<<" Connected!" << std::endl;
            Connections[i] = newConnection;
            TotalConnections += 1; //Increment total # of clients that have connected
        }
    }

    int ts = DEFAULT_NC_TIME / (TotalConnections + 1); // caculating time slot for each of connected node including server
    std::cout<<"\nPress any key to start transmission: ";
    getche();
    for(int i= 0; i < TotalConnections; i++){

        emitMessageToClient(i, ts);
        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(i), NULL, NULL);
        wait(ts);
        if(i == (TotalConnections - 1)){
           i = 0;
        }
    }
    system("pause");
    return 0;
}

Client.cpp

        #include "stdafx.h"
    #pragma comment(lib,"ws2_32.lib") //Required for WinSock
    #include <WinSock2.h> //For win sockets
    #include <string> //For std::string
    #include <iostream> //For std::cout, std::endl, std::cin.getline
    #include <time.h>
    #include <vector>
    #include <conio.h>
    SOCKET Connection;//This client's connection to the server

    void wait ( int seconds )
    {
        clock_t endwait;
        endwait = clock () + seconds * CLOCKS_PER_SEC ;
        while (clock() < endwait) {}
    }

    void ClientThread()
    {
        int bufferlength; //Holds the length of the message we are receiving
        int ts; // holds timeslot duration for this client
        while (true)
        {
            recv(Connection, (char*)&ts, sizeof(int), NULL); //receive timeslot
            recv(Connection, (char*)&bufferlength, sizeof(int), NULL); //receive bufferlength
            char * buffer = new char[bufferlength+1];
            buffer[bufferlength] = '\0';
            recv(Connection, buffer, bufferlength, NULL);
            std::cout << buffer << std::endl; //print out buffer
            std::string userinput; //holds the user's chat message

            for (int n= ts; n>0; n--)
           {
            userinput = "First client sending message...";
            int bufferlength = userinput.size(); //Find buffer length
            send(Connection, (char*)&bufferlength, sizeof(int), NULL); //Send length of buffer
            send(Connection, userinput.c_str(), bufferlength, NULL); //Send buffer
            wait (1);
           }
            delete[] buffer; //Deallocate buffer
        }
    }

    int main()
    {
        //Winsock Startup
        WSAData wsaData;
        WORD DllVersion = MAKEWORD(2, 1);
        if (WSAStartup(DllVersion, &wsaData) != 0)
        {
            MessageBoxA(NULL, "Winsock startup failed", "Error", MB_OK | MB_ICONERROR);
            return 0;
        }

        SOCKADDR_IN addr;
        int sizeofaddr = sizeof(addr);
        addr.sin_addr.s_addr = inet_addr("127.0.0.1");
        addr.sin_port = htons(1111);
        addr.sin_family = AF_INET;

        Connection = socket(AF_INET, SOCK_STREAM, NULL);
        if (connect(Connection, (SOCKADDR*)&addr, sizeofaddr) != 0)
        {
            MessageBoxA(NULL, "Failed to Connect", "Error", MB_OK | MB_ICONERROR);
            return 0; //Failed to Connect
        }

        std::cout << "Connected!" << std::endl;
        CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientThread, NULL, NULL, NULL);

        getche();
        return 0;
    }

once server send message to all his connected clients.Server wants to send message again to his First client to transmit message again.(cyclically)

Problem

How can I achieve if server talk all his clients c1,c2,c3 to Cn and again talk to his first client C1.(cyclically) I have used this check

 if(i == (TotalConnections - 1)){
       i = 0;
 }

but it crash the program.

Body:
By setting i back to 0 you create an infinite loop because i never gets large enough for the loop to end.

for(int i= 0; i < TotalConnections; i++) {

    emitMessageToClient(i, ts);
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(i), NULL, NULL);
    wait(ts);

    // This will create an infinite loop
    if(i == (TotalConnections - 1))
    {
        i = 0;
    }
}

What you can do is wait until the loop has finished to re-visit the first connection:

for(int i= 0; i < TotalConnections; i++) {

    emitMessageToClient(i, ts);
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(i), NULL, NULL);
    wait(ts);
}

// now the loop is over, revisit the first connection
// if it exists
if(TotalConnections > 0) {

    emitMessageToClient(0, ts);
    CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)ClientHandlerThread, (LPVOID)(0), NULL, NULL);
    wait(ts);
}


问:
Loop for reading more than 1 query in a bash file
I need a loop in a Bash script (analysis-run.sh) for running many queries. As I have many queries I can't run them manually so I need a way to automate them. So far, I created a file inputs.txt with all my queries and at the end of the bash script file I added the following:

```<code>while read f ; do
  ./analysis-run.sh $f
done < imputs.txt
</code>```

With that loop, analysis-run is only running the first query of inputs.txt over and over again. I am really new to this, so any help would be appreciated.

The content of imputs.txt is:

bones

muscles

blood

saliva

and so on..

The content of analysis-run.sh is:

Execute this script as ./analysis-run.sh [query] [group]

query=$1

group=$2

if [ $group = "clean" ]; then

```<code>    cluster=A
</code>```

else

```<code>    cluster=B
</code>```

fi

adamo-obtain_bundance.py - query $query -ref combined_$cluster.$group.align -splits 1 -group $group

adamo-obtain_structure.py -i $query.combined_$query$group.csv -o $query.$group -cutoff 0.5 -group $group

答:
With that loop, analysis-run is only running the first query of inputs.txt over and over again.

The problem (probably) is that you need to quote $f:

```<code>while read -r f ; do
  ./analysis-run.sh "$f"
done < samples.txt
</code>```

Without the quotes, the line read from samples.txt will be subject to word splitting and glob expansion.

Read http://tldp.org/LDP/abs/html/quotingvar.html

And run your scripts though ShellCheck

Body:
I need a loop in a Bash script (analysis-run.sh) for running many queries. As I have many queries I can't run them manually so I need a way to automate them. So far, I created a file inputs.txt with all my queries and at the end of the bash script file I added the following:

while read f ; do
  ./analysis-run.sh $f
done < imputs.txt

With that loop, analysis-run is only running the first query of inputs.txt over and over again. I am really new to this, so any help would be appreciated.

The content of imputs.txt is:

bones

muscles

blood

saliva

and so on..

The content of analysis-run.sh is:

Execute this script as ./analysis-run.sh [query] [group]

query=$1

group=$2

if [ $group = "clean" ]; then

    cluster=A

else

    cluster=B

fi

adamo-obtain_bundance.py - query $query -ref combined_$cluster.$group.align -splits 1 -group $group

adamo-obtain_structure.py -i $query.combined_$query$group.csv -o $query.$group -cutoff 0.5 -group $group

Body:
With that loop, analysis-run is only running the first query of inputs.txt over and over again.

The problem (probably) is that you need to quote $f:

while read -r f ; do
  ./analysis-run.sh "$f"
done < samples.txt

Without the quotes, the line read from samples.txt will be subject to word splitting and glob expansion.

Read http://tldp.org/LDP/abs/html/quotingvar.html

And run your scripts though ShellCheck


问:
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/derby/derda/NetworkServerControl < Unsupported major.minor 49.0 >
I set the Environment Variable both System Path to DERBY_HOME\bin and User variable name DERBY_HOME and value to where I kept the bin.Then using the cmd I enter the command startNetworkServer.bat but it is throwing the exception mentioned.

my derby version is 10.10.2.0

JDK version jdk1.7.0_07

JRE version jre7

I searched related exception but my JDK and JRE version are same.

How I can correct when my system path variable points to JDK and JRE version 7 or 1.7 and in the installation their is no jdk or jre version 1.5 or 5.Do I need to use lower version od derby 10.8.1.2?

答:
my jdk version is jdk1.7.0_79

and jre version jre7

and the derby version that I am using is 10.12.1.1 and it is working for me.

earlier when I was using the derby version  10.13.1.1 I was also getting the same type of error

then I found in the following link
http://db.apache.org/derby/releases/release-10.13.1.1.cgi that  the derby version  10.13.1.1
supports Java SE 8 with JDBC 4.2 , and my jdk and jre version is jdk1.7.0_79 and jre7

So It seems due to version mismatch of jdk I was getting the error,So I downloaded the lower version of derby i.e 10.12.1.1
and it worked for me.

ContentLicense: CC BY-SA 4.0


问:
How to add css style to the all children of element at the same time?
Such as:

```<code><div class="mostOut">
    <div class="a">
        <h3 class="b"></h3>
        <div class="d"></div>
    </div>
</div>
</code>```

And how can I apply css style to the children of "moustOut" at the same time.E.g:

with one click event.the css('opacity',1) could apply to the "a","b","d" at the same time.Or ,exclude "b" .

答: You can use rgba to set opacity per element. Check out http://www.css3.info/preview/rgba/</p>

Body:
Such as:

And how can I apply css style to the children of "moustOut" at the same time.E.g:

with one click event.the css('opacity',1) could apply to the "a","b","d" at the same time.Or ,exclude "b" .


问:
Trick to loop/autorefresh docker ps view like top/htop in bash
Is it possible - and if yes, how - to have a self-refreshing view of current Docker containers printed by "docker ps" alike top/htop utilities?</p>

答:
Use watch:

```<code>watch docker ps
</code>```

See man watch

Body:
Use watch:

watch docker ps

See man watch


问:
How can I post form to mysqli without using an action page
I don't wanna use an action page. I wanna post on the same page.

These are my codes. But there is an error called "Undefined index: baslik on line 5 and aciklama on line 6

```<code><?php

include("baglan.php");

$site_basligi = mysqli_real_escape_string($conn, $_POST['baslik']);
$site_aciklamasi = mysqli_real_escape_string($conn, $_POST['aciklama']);

$ayarsql = "UPDATE ayar SET baslik='$site_basligi', aciklama='$site_aciklamasi' WHERE durum='1'";

if($conn->query($ayarsql)){
echo "Güncelleme başarılı";
}
?>

<form action="" method="post">

Site Başlığı: <input type="text" name="baslik" ><br><br>
Açıklama: <input type="text" name="aciklama"><br><br>

<input type="submit">

</form>
</code>```

答:
I can see the form IS submitting to the same page.
You just should wrap the PHP code in if condition</p>

```<code><?php
include("baglan.php");
if(!empty($_POST['baslik'])) { // This is the new if condition
    $site_basligi    = mysqli_real_escape_string($conn, $_POST['baslik']  );
    $site_aciklamasi = mysqli_real_escape_string($conn, $_POST['aciklama']);
    $ayarsql = "UPDATE ayar SET baslik='$site_basligi', aciklama='$site_aciklamasi' WHERE durum='1'";
    if($conn->query($ayarsql)) {
        echo "Güncelleme başarılı";
    }
}
?>
<form action="" method="post">
    Site Başlığı: <input type="text" name="baslik" ><br><br>
    Açıklama:     <input type="text" name="aciklama"><br><br>
    <input type="submit">
</form>
</code>```

Body:
I don't wanna use an action page. I wanna post on the same page.

These are my codes. But there is an error called "Undefined index: baslik on line 5 and aciklama on line 6

<?php

include("baglan.php");

$site_basligi = mysqli_real_escape_string($conn, $_POST['baslik']);
$site_aciklamasi = mysqli_real_escape_string($conn, $_POST['aciklama']);

$ayarsql = "UPDATE ayar SET baslik='$site_basligi', aciklama='$site_aciklamasi' WHERE durum='1'";

if($conn->query($ayarsql)){
echo "Güncelleme başarılı";
}
?>

<form action="" method="post">

Site Başlığı: <input type="text" name="baslik" >

Açıklama: <input type="text" name="aciklama">

<input type="submit">

</form>

Body:
I can see the form IS submitting to the same page.
You just should wrap the PHP code in if condition

<?php
include("baglan.php");
if(!empty($_POST['baslik'])) { // This is the new if condition
    $site_basligi    = mysqli_real_escape_string($conn, $_POST['baslik']  );
    $site_aciklamasi = mysqli_real_escape_string($conn, $_POST['aciklama']);
    $ayarsql = "UPDATE ayar SET baslik='$site_basligi', aciklama='$site_aciklamasi' WHERE durum='1'";
    if($conn->query($ayarsql)) {
        echo "Güncelleme başarılı";
    }
}
?>
<form action="" method="post">
    Site Başlığı: <input type="text" name="baslik" ><br><br>
    Açıklama:     <input type="text" name="aciklama"><br><br>
    <input type="submit">
</form>


问:
How to assign public port to port 5900 in docker-compose
I have below YAML file :

seleniumhub:

image: selenium/hub

ports:
 - 4444:4444
```

<p>firefoxnode:</p>

<pre class="lang-yaml prettyprint-override"><code>image: selenium/node-firefox-debug

ports:
 - 4577

links:
 - seleniumhub:hub

expose:
 - "5900"
</code>```

chromenode:

image : selenium/node-chrome-debug

ports:
 - 4578

links:
 - seleniumhub:hub

expose:
 - "5900"
```

<hr>

<p>docker ps:</p>

```time="2017-04-01T17:57:44+03:00" level=info msg="Unable to use system certificate pool: crypto/x509: system root pool is not available on Windows"

CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                               NAMES
9d2ccb193b54        selenium/node-firefox-debug   "/opt/bin/entry_po..."   6 seconds ago       Up 5 seconds        5900/tcp, 0.0.0.0:32785->4577/tcp   dockercompose_firefoxnode_1
4be6223fe043        selenium/node-chrome-debug    "/opt/bin/entry_po..."   6 seconds ago       Up 5 seconds        5900/tcp, 0.0.0.0:32784->4578/tcp   dockercompose_chromenode_1
7d95d3e73016        selenium/hub                  "/opt/bin/entry_po..."   7 seconds ago       Up 6 seconds        0.0.0.0:4444->4444/tcp              dockercompose_seleniumhub_1
```

<hr>

<p>But whenever I run below command in Docker quick start terminal:</p>

```docker port 9d2ccb193b54 5900
```

I got below:

Error: No public port '5900/tcp' published for 9d2ccb193b54

and I'm not able to connect to the node machines through VNC

答:
for firefoxnode try this configuration:

```<code>image: selenium/node-firefox-debug

ports:
 - 4577
 - 5900

links:
 - seleniumhub:hub

expose:
 - "5900"
</code>```

expose does not publish port to the host machine and only accessible to linked services. It works for inter-container communication. ports will expose that port to host machine.

Body:
I have below YAML file :

seleniumhub:

image: selenium/hub

ports:
 - 4444:4444

firefoxnode:

image: selenium/node-firefox-debug

ports:
 - 4577

links:
 - seleniumhub:hub

expose:
 - "5900"

chromenode:

image : selenium/node-chrome-debug

ports:
 - 4578

links:
 - seleniumhub:hub

expose:
 - "5900"

docker ps:

time="2017-04-01T17:57:44+03:00" level=info msg="Unable to use system certificate pool: crypto/x509: system root pool is not available on Windows"

CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                               NAMES
9d2ccb193b54        selenium/node-firefox-debug   "/opt/bin/entry_po..."   6 seconds ago       Up 5 seconds        5900/tcp, 0.0.0.0:32785->4577/tcp   dockercompose_firefoxnode_1
4be6223fe043        selenium/node-chrome-debug    "/opt/bin/entry_po..."   6 seconds ago       Up 5 seconds        5900/tcp, 0.0.0.0:32784->4578/tcp   dockercompose_chromenode_1
7d95d3e73016        selenium/hub                  "/opt/bin/entry_po..."   7 seconds ago       Up 6 seconds        0.0.0.0:4444->4444/tcp              dockercompose_seleniumhub_1

But whenever I run below command in Docker quick start terminal:

docker port 9d2ccb193b54 5900

I got below:

Error: No public port '5900/tcp' published for 9d2ccb193b54

and I'm not able to connect to the node machines through VNC

Body:
for firefoxnode try this configuration:

image: selenium/node-firefox-debug

ports:
 - 4577
 - 5900

links:
 - seleniumhub:hub

expose:
 - "5900"

expose does not publish port to the host machine and only accessible to linked services. It works for inter-container communication. ports will expose that port to host machine.


答:
```<code><?php

include("baglan.php");
// check for post request here
if(isset($_POST['baslik']) && $_POST['baslik'] != "") {
$site_basligi = mysqli_real_escape_string($conn, $_POST['baslik']);
$site_aciklamasi = mysqli_real_escape_string($conn, $_POST['aciklama']);

$ayarsql = "UPDATE ayar SET baslik='$site_basligi', aciklama='$site_aciklamasi' WHERE durum='1'";

if($conn->query($ayarsql)){
echo "Güncelleme başarılı";
}
}
?>

<form action="" method="post">

Site Başlığı: <input type="text" name="baslik" ><br><br>
Açıklama: <input type="text" name="aciklama"><br><br>

<input type="submit">

</form>
</code>```

Title: How can I post form to mysqli without using an action page


问:
djagno, rest_framework..TypeError: object() takes no parameters
I am a beginner in django.
I do not know why this is an error. Please help me. ㅠ^ㅠ

```<code>TypeError: object() takes no parameters
</code>```

Following is my code:

```<code>class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
    content = JSONRenderer().render(data)
    kwargs['content_type'] = 'application/json'
    super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def mood_list(request):
    if request.method == 'GET':
        mood = Mood.objects.all()
        serializer = MoodSerializer(mood, many=True)
        return JSONRenderer(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = MoodSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)
</code>```

答:
Remove data parameter in JSONParser class. **kwargs already exists. You can access to data parameter with kwargs as kwargs['data'] or kwargs.get('data') as it is a python dictionary.

Also, change the return  statement as return JSONParser(data=serializers.errors, status=400).

Body:
I am a beginner in django.
I do not know why this is an error. Please help me. ㅠ^ㅠ

TypeError: object() takes no parameters

Following is my code:

class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
    content = JSONRenderer().render(data)
    kwargs['content_type'] = 'application/json'
    super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def mood_list(request):
    if request.method == 'GET':
        mood = Mood.objects.all()
        serializer = MoodSerializer(mood, many=True)
        return JSONRenderer(serializer.data)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = MoodSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.errors, status=400)


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

Body:
TRS-80 graphics

POKE 15360, 191

OwnerDisplayName: edg


问:
System.Management access denied
I was using some code to try to count the number of processors in .NET 2.0:

```<code>internal static int GetNumberOfProcessors()
{
    List<string> list = new List<string>();
    ManagementClass mgmt = new ManagementClass("Win32_Processor");
    foreach (ManagementObject obj in mgmt.GetInstances())
    {
        string item = obj.Properties["SocketDesignation"].Value.ToString();
        if (!list.Contains(item))
        {
            list.Add(item);
        }
    }
    return list.Count;
}
</code>```

and it blew up like this:

```<code>[ManagementException: Access denied ]
   System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode) +377984
   System.Management.ManagementScope.InitializeGuts(Object o) +654
   System.Management.ManagementScope.Initialize() +162
   System.Management.ManagementObject.Initialize(Boolean getObject) +492
   System.Management.ManagementClass.GetInstances(EnumerationOptions options) +122
   System.Management.ManagementClass.GetInstances() +6
</code>```

This code runs fine locally on cassini, but blows up on our beta server. Anyone have any idea what to do about this?

答:
Ok, I hate answering my own question, but I found this: http://support.microsoft.com/kb/317012
and it does seem to work.

You have to specifically modify your CIMV2 permissions, and I had to do it for the specific user, not ASPNET. Once this is on, you can use the System.Management code to count processors etc.

I really don't like how obscure this was. Microsoft needs to update those exceptions. When the System.Management class fails like that it should give detailed info on which permissions need activated for the code to work.

Title: System.Management access denied

Body:
I was using some code to try to count the number of processors in .NET 2.0:

internal static int GetNumberOfProcessors()
{
    List<string> list = new List<string>();
    ManagementClass mgmt = new ManagementClass("Win32_Processor");
    foreach (ManagementObject obj in mgmt.GetInstances())
    {
        string item = obj.Properties["SocketDesignation"].Value.ToString();
        if (!list.Contains(item))
        {
            list.Add(item);
        }
    }
    return list.Count;
}

and it blew up like this:

[ManagementException: Access denied ]
   System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode) +377984
   System.Management.ManagementScope.InitializeGuts(Object o) +654
   System.Management.ManagementScope.Initialize() +162
   System.Management.ManagementObject.Initialize(Boolean getObject) +492
   System.Management.ManagementClass.GetInstances(EnumerationOptions options) +122
   System.Management.ManagementClass.GetInstances() +6

This code runs fine locally on cassini, but blows up on our beta server. Anyone have any idea what to do about this?


问:
not able to toggle Switch
At the moment I am programming an application based on Xamarin. My goal is to toggle the switch based on values in a table. Problem is, Xamarin is not noticing my x:Name toggle_true connected to my switch.

Here is my script in xaml:

```<code><ListView x:Name="defineBuildingItems">
            <ListView.ItemTemplate>
                <DataTemplate>

                    <ViewCell>

                            <StackLayout Orientation="Horizontal">
                            <StackLayout Orientation="Vertical">
                                <Label  Text="{Binding defineDescription}"  x:Name="Current_item"/>

                            </StackLayout>

                                <Switch BindingContext ="{Binding defineId}" HorizontalOptions="EndAndExpand"
                                        Toggled="Handle_Toggled"  x:Name="toggled_true"/>

                            </StackLayout>

                    </ViewCell>

                </DataTemplate>
            </ListView.ItemTemplate>
            </ListView>
</code>```

Here is my c# code in code behind:

```<code>    var currentQuestions = _define.Where(s => DefineId.Contains(s.defineId));

        //Remember what building was defined like last time defineBuilding was proceeded.
        foreach (DefineTable i in currentQuestions)
        {

            toggled_true.IsToggled = true;

        }

        defineBuildingItems.ItemsSource = posts;
        base.OnAppearing();
    }
</code>```

Notice how it recognizes the x:Name defineBuildingItems. The error i get on toggled_true is: The name toggled_true does not exist in the current namespace. Is there something I am doing wrong or missing?

答:
Access to control by name  inside datatemplate not working. You must using binding. This is simply example:

Model:

```<code> public class Data
 {
     public bool IsToggled {get;set;}
     ....
 }
</code>```

Code behind:

```<code>public YourPage
{
  BindingContext = this;
}
 ....
private List<Data> _items;
public List<Data> Items
{
   get { return _items;}
   set
     {
        _items = value;
        OnPropertyChanged();
     }
}
</code>```

Your xaml:

```<code><ListView x:Name="defineBuildingItems" ItemSources={Binding Items}>
    <ListView.ItemTemplate>
        <DataTemplate>

            <ViewCell>

                    <StackLayout Orientation="Horizontal">
                    <StackLayout Orientation="Vertical">
                        <Label  Text="{Binding defineDescription}"      />

                    </StackLayout>

                        <Switch IsToggled ="{Binding IsToggled, Mode =TwoWay}" HorizontalOptions="EndAndExpand" />

                    </StackLayout>

            </ViewCell>

        </DataTemplate>
    </ListView.ItemTemplate>
    </ListView>
</code>```

Title: not able to toggle Switch

Body:
At the moment I am programming an application based on Xamarin. My goal is to toggle the switch based on values in a table. Problem is, Xamarin is not noticing my x:Name toggle_true connected to my switch.

Here is my script in xaml:

<ListView x:Name="defineBuildingItems">
            <ListView.ItemTemplate>
                <DataTemplate>

                    <ViewCell>

                            <StackLayout Orientation="Horizontal">
                            <StackLayout Orientation="Vertical">

                            </StackLayout>

                                <Switch BindingContext ="{Binding defineId}" HorizontalOptions="EndAndExpand"
                                        Toggled="Handle_Toggled"  x:Name="toggled_true"/>

                            </StackLayout>

                    </ViewCell>

                </DataTemplate>
            </ListView.ItemTemplate>
            </ListView>

Here is my c# code in code behind:

    var currentQuestions = _define.Where(s => DefineId.Contains(s.defineId));

        //Remember what building was defined like last time defineBuilding was proceeded.
        foreach (DefineTable i in currentQuestions)
        {

            toggled_true.IsToggled = true;

        }

        defineBuildingItems.ItemsSource = posts;
        base.OnAppearing();
    }

Notice how it recognizes the x:Name defineBuildingItems. The error i get on toggled_true is: The name toggled_true does not exist in the current namespace. Is there something I am doing wrong or missing?

Body:
Access to control by name  inside datatemplate not working. You must using binding. This is simply example:

Model:

 public class Data
 {
     public bool IsToggled {get;set;}
     ....
 }

Code behind:

public YourPage
{
  BindingContext = this;
}
 ....
private List<Data> _items;
public List<Data> Items
{
   get { return _items;}
   set
     {
        _items = value;
        OnPropertyChanged();
     }
}

Your xaml:

<ListView x:Name="defineBuildingItems" ItemSources={Binding Items}>
    <ListView.ItemTemplate>
        <DataTemplate>

            <ViewCell>

                    <StackLayout Orientation="Horizontal">
                    <StackLayout Orientation="Vertical">
                        <Label  Text="{Binding defineDescription}"      />

                    </StackLayout>

                        <Switch IsToggled ="{Binding IsToggled, Mode =TwoWay}" HorizontalOptions="EndAndExpand" />

                    </StackLayout>

            </ViewCell>

        </DataTemplate>
    </ListView.ItemTemplate>
    </ListView>


答:
You are not checking if the POST data actually exists, so when you first load the page there is no $_POST

do something like

```<code>if (isset($_POST)){
</code>```

//your php code here

}

Body:
You are not checking if the POST data actually exists, so when you first load the page there is no $_POST

do something like

if (isset($_POST)){

//your php code here

}


问:
Using Recursion to determine if input is prime
Ive tried to search for similar questions to see if the answer might be on this site to no avail.
Im currently trying to write a program that determines if the user input is a prime number using a recursive method. The problem is it will not compile do to the variable "n" already being defined in the scope. I dont quite see what the compiler means.
Heres is my code</p>

```<code>/**
 * Created on 3/26/2017.
 **/
import java.util.Scanner;
public class PrimeNumberRecursion {
    public static void main(String[] n) {
        //Variables declared
        Scanner userInput = new Scanner(System.in);
        int n;
        int div = 2;
        //Program is introduced
        System.out.println(" Prime Number Recursion Program");
        System.out.println("*********************************");
        //User is prompted for a number
        System.out.print("Please enter a number: ");
        n = userInput.nextInt();
        //Conditional statement prints result
        if(isPrime(n,div) == 1){System.out.println(n +" is a prime number");}
        else{System.out.println(n +" is not a prime number");}
    }
    //User input is passed to isPrime recursive method
    public static int isPrime(int n, int div) {
        if(n == 1) {return 1;}
        else if(n % div == 0) {return -1;}
        else if(n == div) {return -1;}
        else{return isPrime(n, ++div);}
    }
}
</code>```

答:
If you start at 2 you only need to check up to the square root of n for better efficiency. Also as already stated any number below 2 is not prime. </p>

```<code>public static boolean isPrime(int n, int div) {
    if ( n < 2 || Math.sqrt(n) > div) {
        return false;
    } else if (n % div == 0) {
        return true;
    } else {
        return isPrime(n, ++div);
    }
}
</code>```

Body:
Ive tried to search for similar questions to see if the answer might be on this site to no avail.
Im currently trying to write a program that determines if the user input is a prime number using a recursive method. The problem is it will not compile do to the variable "n" already being defined in the scope. I dont quite see what the compiler means.
Heres is my code

/**
 * Created on 3/26/2017.
 **/
import java.util.Scanner;
public class PrimeNumberRecursion {
    public static void main(String[] n) {
        //Variables declared
        Scanner userInput = new Scanner(System.in);
        int n;
        int div = 2;
        //Program is introduced
        System.out.println(" Prime Number Recursion Program");
        System.out.println("*********************************");
        //User is prompted for a number
        System.out.print("Please enter a number: ");
        n = userInput.nextInt();
        //Conditional statement prints result
        if(isPrime(n,div) == 1){System.out.println(n +" is a prime number");}
        else{System.out.println(n +" is not a prime number");}
    }
    //User input is passed to isPrime recursive method
    public static int isPrime(int n, int div) {
        if(n == 1) {return 1;}
        else if(n % div == 0) {return -1;}
        else if(n == div) {return -1;}
        else{return isPrime(n, ++div);}
    }
}

Body:
If you start at 2 you only need to check up to the square root of n for better efficiency. Also as already stated any number below 2 is not prime.

public static boolean isPrime(int n, int div) {
    if ( n < 2 || Math.sqrt(n) > div) {
        return false;
    } else if (n % div == 0) {
        return true;
    } else {
        return isPrime(n, ++div);
    }
}


问:
c# private boolean error inside method
Sorry for the noobish question and there is probably a very easy fix to this, but I am making an application and I am trying to return a boolean to be used in another method when a checkbox is ticked. Though here I receive an error after the first { saying } expected. Thanks in advance, P

```<code>    private void CheckImgur_Checked(object sender, RoutedEventArgs e)
    {
        private bool imgurChecked = true;
    }
</code>```

答:
I am trying to return a boolean to be used in another method

You can't return a value from an event handler. it's return type is void.

It seems like you meant to assign the value into some field of the class itself.

```<code>class MyTerrificClass
{
    private bool imgurChecked;

    private void CheckImgur_Checked(object sender, RoutedEventArgs e)
    {

        this.imgurChecked = true;
    }

    private void SomeOtherMethod()
    {
        // Use this.imgurChecked somewhere
    }
}
</code>```

And in any case local variable doesn't have an access (private/public) modifier.

Title: c# private boolean error inside method

Body:
Sorry for the noobish question and there is probably a very easy fix to this, but I am making an application and I am trying to return a boolean to be used in another method when a checkbox is ticked. Though here I receive an error after the first { saying } expected. Thanks in advance, P

    private void CheckImgur_Checked(object sender, RoutedEventArgs e)
    {
        private bool imgurChecked = true;
    }

Body:
I am trying to return a boolean to be used in another method

You can't return a value from an event handler. it's return type is void.

It seems like you meant to assign the value into some field of the class itself.

class MyTerrificClass
{
    private bool imgurChecked;

    private void CheckImgur_Checked(object sender, RoutedEventArgs e)
    {

        this.imgurChecked = true;
    }

    private void SomeOtherMethod()
    {
        // Use this.imgurChecked somewhere
    }
}

And in any case local variable doesn't have an access (private/public) modifier.


问:
How can I get rid of these mysterious grey boxes at the margins of a div element?
I am having a mysterious problem that did not exist yesterday (you know those?). For some reason, these grey boxes are appearing at the edges of an element that appears when a user hovers over its parent element. they appear to the right and bottom. Essentially, everything below the check and x images is a div with a class of .bottom. I have set to 50% of parent height and 100% of its width. These are react components, so it may be a tad hard to follow. The EventDetail component is nested in the Event component.

.eventcontainer {
 padding: 5px;
 width: 960px;
 margin: 20px auto;
}

.event {
  margin-top: 2%;
  width: 960px;
  border-color:#496DD9;
  border-style: dotted;
  font-size: 0.5em;
  height: 300px;
  position: relative;
  -webkit-transition: height 300ms ease-out;
}
.event:hover {
   height: 400px;
   -webkit-transition: height 300ms ease-in;
}

.event:hover .hidden {
  display: block;
  opacity: 1;
 -webkit-transition: opacity 300ms ease-in 200ms;
}

.hidden {
  opacity: 0;
  overflow: scroll;
  -webkit-transition: opacity 100ms ease-out;
}

.bottom {
  position: absolute;
  bottom: 0;
  padding-bottom: 2%;
  padding-left: 2%;
  font-size: 13px;
  width: 100%;
  height: 50%;
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const EventDetail = (props) => {
  const options = {
    color: '#DE5745',
    trailWidth: 1,
    strokeWidth: 10,
  };
  const containerStyle = {
    width: '100px',
    height: '20px',
  };

  const showUpdate = (e) => {
    e.preventDefault();
    props.dispatch(renderUpdate(props.id));
  };

  return (
    <div className=" bottom  hidden" >
      <p>Attendance</p>
      <div className="progressbar">
        <Line progress={(props.attending / props.capacity)} containerStyle={containerStyle} initialAnimate options={options} containerClassName={'.progressbar'} />
        <span>{props.attending}</span><span>/</span><span> {props.capacity}</span>
      </div>
      {/* <div>{props.attendeeHelperFunction(props.attendeeList)}</div>*/}
      <p>Description:</p>
      {props.description === '___' ? <p>The owner did not provide a description. So mysterious</p> : <p>{props.description}</p>}
      {window.localStorage.getItem('userid') === props.owner_id ?
        <div>
          <Update
            event_title={props.title}
            event_description={props.description}
            event_capacity={props.capacity}
            event_id={props.event_id}
          />
        </div>
        : null}
    </div>
  );
};</code>```

const Event = (props) => {
  const attendHandler = (e) => {
    e.preventDefault();
    props.dispatch(attendEvent(props.id))
    .then(() => {
      props.dispatch(fetchEvents());
    });
  };

  const flakeHandler = (e) => {
    e.preventDefault();
    props.dispatch(flakeEvent(props.id))
    .then(() => {
      props.dispatch(fetchEvents());
    })
    .catch(err => console.log(err));
  };

  return (

{props.title}

{props.date}

Hosted by: {props.owner}

{console.log('EVENT', renderEvents)}

      <EventDetail
        title={props.title}
        event_id={props.id}
        owner_id={props.owner_id}
        attending={props.attendees}
        capacity={props.capacity}
        description={props.description}
        attendeeList={props.attendeeList}
        attendeeHelperFunction={props.attendeeHelperFunction}
      />

  );
};```

答: They are scrollbars, duh! But if anyone ever stumbles onto this thread, here is a style generator for scroll bars https://mikethedj4.github.io/Webkit-Scrollbar-Generator/</p>

Body:
I am having a mysterious problem that did not exist yesterday (you know those?). For some reason, these grey boxes are appearing at the edges of an element that appears when a user hovers over its parent element. they appear to the right and bottom. Essentially, everything below the check and x images is a div with a class of .bottom. I have set to 50% of parent height and 100% of its width. These are react components, so it may be a tad hard to follow. The EventDetail component is nested in the Event component.

.eventcontainer {
 padding: 5px;
 width: 960px;
 margin: 20px auto;
}

.event {
  margin-top: 2%;
  width: 960px;
  border-color:#496DD9;
  border-style: dotted;
  font-size: 0.5em;
  height: 300px;
  position: relative;
  -webkit-transition: height 300ms ease-out;
}
.event:hover {
   height: 400px;
   -webkit-transition: height 300ms ease-in;
}

.event:hover .hidden {
  display: block;
  opacity: 1;
 -webkit-transition: opacity 300ms ease-in 200ms;
}

.hidden {
  opacity: 0;
  overflow: scroll;
  -webkit-transition: opacity 100ms ease-out;
}

.bottom {
  position: absolute;
  bottom: 0;
  padding-bottom: 2%;
  padding-left: 2%;
  font-size: 13px;
  width: 100%;
  height: 50%;
}

const EventDetail = (props) => {
  const options = {
    color: '#DE5745',
    trailWidth: 1,
    strokeWidth: 10,
  };
  const containerStyle = {
    width: '100px',
    height: '20px',
  };

  const showUpdate = (e) => {
    e.preventDefault();
    props.dispatch(renderUpdate(props.id));
  };

  return (

Attendance

        <Line progress={(props.attending / props.capacity)} containerStyle={containerStyle} initialAnimate options={options} containerClassName={'.progressbar'} />
        {props.attending}/ {props.capacity}

      {/*
{props.attendeeHelperFunction(props.attendeeList)}
*/}

Description:

      {props.description === '___' ?
The owner did not provide a description. So mysterious
 :
{props.description}
}
      {window.localStorage.getItem('userid') === props.owner_id ?

          <Update
            event_title={props.title}
            event_description={props.description}
            event_capacity={props.capacity}
            event_id={props.event_id}
          />

        : null}

  );
};

const Event = (props) => {
  const attendHandler = (e) => {
    e.preventDefault();
    props.dispatch(attendEvent(props.id))
    .then(() => {
      props.dispatch(fetchEvents());
    });
  };

  const flakeHandler = (e) => {
    e.preventDefault();
    props.dispatch(flakeEvent(props.id))
    .then(() => {
      props.dispatch(fetchEvents());
    })
    .catch(err => console.log(err));
  };

  return (

{props.title}

{props.date}

Hosted by: {props.owner}

{console.log('EVENT', renderEvents)}

      <EventDetail
        title={props.title}
        event_id={props.id}
        owner_id={props.owner_id}
        attending={props.attendees}
        capacity={props.capacity}
        description={props.description}
        attendeeList={props.attendeeList}
        attendeeHelperFunction={props.attendeeHelperFunction}
      />

  );
};


问:
How can I detect when a Socket.IO emit() was sent but not received by any .on() handler?
I've run into a common debugging problem where a socket.io .emit() is sent but there is no corresponding .on() to catch the emit, however this basically fails silently.

Is there a way on the server or client to detect when an emit was sent or an on was received but there was no handler for that event?

For my purposes I'm using TypeScript/ES6 with Socket.IO/Socket.IO-client v1.7.3

答:
I was able to accomplish this by having the socket.io listener hijack the onevent method of sockets as they connect and comparing the emit event name to the keys of the events the socket is listening for:

(Note: this is the server version, on the client you want to use _callbacks and remove the '$' at the beginning of each key)

```<code>io.on('connection', (socket)=>{
    var onevent = socket.onevent;
    var eventNames = Object.keys(socket._events);
    socket.onevent = function (packet) {
        onevent.call(this, packet);// original call

        var eventName = packet.data[0];

        if(eventNames.indexOf(eventName) == -1){
            console.error('No handler for emitted event: '+eventName);
        }
    };
});
</code>```

Body:
I was able to accomplish this by having the socket.io listener hijack the onevent method of sockets as they connect and comparing the emit event name to the keys of the events the socket is listening for:

(Note: this is the server version, on the client you want to use _callbacks and remove the '$' at the beginning of each key)

io.on('connection', (socket)=>{
    var onevent = socket.onevent;
    var eventNames = Object.keys(socket._events);
    socket.onevent = function (packet) {
        onevent.call(this, packet);// original call

        var eventName = packet.data[0];

        if(eventNames.indexOf(eventName) == -1){
            console.error('No handler for emitted event: '+eventName);
        }
    };
});


问:
Application Crashes on Thread Exit - C++
My application is crashing when it exits the thread function.  This is how my thread is initialized:

```<code>LPTHREAD_START_ROUTINE pThreadStart = (LPTHREAD_START_ROUTINE)NotifyWindowThreadFn;
void * pvThreadData = reinterpret_cast<void *>(_pobjSerialPort);

// Create the exit notify window thread event handle.
_hNotifyWindowThreadExitEvent = ::CreateEvent(
    NULL,                           // No security
    TRUE,                           // Create a manual-reset event object
    FALSE,                          // Initial state is non-signaled
    NULL                            // No name specified
    );

if ( _hNotifyWindowThreadExitEvent == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to get a handle for the exit message-only window event.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

// Create the notify window thread to begin execution on its own.
_hNotifyWindowThread = ::CreateThread(
    NULL,                           // No security attributes.
    0,                              // Use default initial stack size.
    pThreadStart,                   // Function to execute in new thread.
    pvThreadData,                   // Thread parameters.
    0,                              // Use default creation settings.
    NULL                            // Thread ID is not needed.
    );

if ( _hNotifyWindowThread == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to create handle for message-only window thread.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}
</code>```

This is the portion of my thread function that gets executed:

```<code>DWORD NotifyWindowThreadFn( void * pParam )
{
    static CNotifyWindow * pobjNotifyWindow = NULL;
    CSerialPort * pobjSerialPort = reinterpret_cast<CSerialPort *>(pParam);

    // Create notify window to handle surprize removal/insertion events...
    try
    {
        pobjNotifyWindow = new CNotifyWindow();
    }
    catch ( DWORD error )
    {
        return error;                // 1. PC gets here
    }
    catch ( long error )
    {
        return error;
    }
    catch ( ... )
    {
        return ERROR_CANNOT_MAKE;
    }

    /* Other stuff that is not executed due to return. */

}                                     // 2. PC then gets here
</code>```

When the application crashes, Visual Studio gives me this error message:

Windows has triggered a breakpoint in CppTestConsole.exe.

This may be due to a corruption of the heap, which indicates a bug in CppTestConsole.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while CppTestConsole.exe has focus.

The output window may have more diagnostic information.

The output window doesn't have anything especially useful.  Only...

The thread 'NotifyWindowThreadFn' (0x414) has exited with code 0 (0x0).

Then it shows that a bunch of DLLs are unloaded.  When I click the Break button, the PC is at the end of _CrtIsValidHeapPointer in dbgheap.c.  Does anyone have any ideas as to why my application is crashing when the thread exits?  Should I not be returning directly from within a threaded function?  Thanks.

答: you should declare and define you function as : DWORD WINAPI NotifyWindowThreadFn( void * pParam )

Body:
My application is crashing when it exits the thread function.  This is how my thread is initialized:

LPTHREAD_START_ROUTINE pThreadStart = (LPTHREAD_START_ROUTINE)NotifyWindowThreadFn;
void * pvThreadData = reinterpret_cast<void *>(_pobjSerialPort);

// Create the exit notify window thread event handle.
_hNotifyWindowThreadExitEvent = ::CreateEvent(
    NULL,                           // No security
    TRUE,                           // Create a manual-reset event object
    FALSE,                          // Initial state is non-signaled
    NULL                            // No name specified
    );

if ( _hNotifyWindowThreadExitEvent == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to get a handle for the exit message-only window event.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

// Create the notify window thread to begin execution on its own.
_hNotifyWindowThread = ::CreateThread(
    NULL,                           // No security attributes.
    0,                              // Use default initial stack size.
    pThreadStart,                   // Function to execute in new thread.
    pvThreadData,                   // Thread parameters.
    0,                              // Use default creation settings.
    NULL                            // Thread ID is not needed.
    );

if ( _hNotifyWindowThread == NULL )
{
    TRACE(_T("CreateNotifyWindow : Failed to create handle for message-only window thread.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
    return ::GetLastError();
}

This is the portion of my thread function that gets executed:

DWORD NotifyWindowThreadFn( void * pParam )
{
    static CNotifyWindow * pobjNotifyWindow = NULL;
    CSerialPort * pobjSerialPort = reinterpret_cast<CSerialPort *>(pParam);

    // Create notify window to handle surprize removal/insertion events...
    try
    {
        pobjNotifyWindow = new CNotifyWindow();
    }
    catch ( DWORD error )
    {
        return error;                // 1. PC gets here
    }
    catch ( long error )
    {
        return error;
    }
    catch ( ... )
    {
        return ERROR_CANNOT_MAKE;
    }

    /* Other stuff that is not executed due to return. */

}                                     // 2. PC then gets here

When the application crashes, Visual Studio gives me this error message:

Windows has triggered a breakpoint in CppTestConsole.exe.

This may be due to a corruption of the heap, which indicates a bug in CppTestConsole.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while CppTestConsole.exe has focus.

The output window may have more diagnostic information.

The output window doesn't have anything especially useful.  Only...

The thread 'NotifyWindowThreadFn' (0x414) has exited with code 0 (0x0).

Then it shows that a bunch of DLLs are unloaded.  When I click the Break button, the PC is at the end of _CrtIsValidHeapPointer in dbgheap.c.  Does anyone have any ideas as to why my application is crashing when the thread exits?  Should I not be returning directly from within a threaded function?  Thanks.


问:
Simple substitution in a file
I have a file test with the following contents

```<code>foo
bar
</code>```

I want to replace foo with bar.

I run perl -p -e 's/foo/bar/g' test but nothing happens.

I'm sure this has been done before, but any help would be appreciated.

答:
There is no issue to answer here.

File test.txt

```<code>foo
bar
</code>```

Shell command

```<code>$ perl -pe 's/foo/bar/g' test.txt
</code>```

output

```<code>bar
bar
</code>```

Title: Simple substitution in a file

Body:
I have a file test with the following contents

foo
bar

I want to replace foo with bar.

I run perl -p -e 's/foo/bar/g' test but nothing happens.

I'm sure this has been done before, but any help would be appreciated.

Body:
There is no issue to answer here.

File test.txt

foo
bar

Shell command

$ perl -pe 's/foo/bar/g' test.txt

output

bar
bar


问:
Tests react component (context.router - undefined)
I am testing react component with chai + karma + enzyme.

```<code>mount(
<Provider store={configureStore(mockContext, null)}>
  <Component {...props} />
</Provider>
)
</code>```

I am using in this component context.router.location. And i get error that this undefined. I try to pass context with the second parameter of mount like this:

```<code>mount(
<Provider store={configureStore(mockContext, null)}>
  <Component {...props} />
</Provider>,
    {
      context: {
        router: {
          location: { pathname: '' }
        }
      },
      childContextTypes: {
        router: React.PropTypes.object
      }
    })
</code>```

How can pass context in my component?

```<code>"react-router": "^3.0.2",
"enzyme": "^2.3.0",
</code>```

p.s. typescript:)

答:
You need to pass childContextTypes as a separate object and not as a child of context as

```<code>mount(
    <Provider store={configureStore(mockContext, null)}>
       <Component {...props} />
    </Provider>,
    {
      context: {
        router: {
          location: { pathname: '' }
        }
      },
      childContextTypes: {
          router: React.PropTypes.object
      }

    })
</code>```

Body:
I am testing react component with chai + karma + enzyme.

mount(
<Provider store={configureStore(mockContext, null)}>
  <Component {...props} />
</Provider>
)

I am using in this component context.router.location. And i get error that this undefined. I try to pass context with the second parameter of mount like this:

mount(
<Provider store={configureStore(mockContext, null)}>
  <Component {...props} />
</Provider>,
    {
      context: {
        router: {
          location: { pathname: '' }
        }
      },
      childContextTypes: {
        router: React.PropTypes.object
      }
    })

How can pass context in my component?

"react-router": "^3.0.2",
"enzyme": "^2.3.0",

p.s. typescript:)

Body:
You need to pass childContextTypes as a separate object and not as a child of context as

mount(
    <Provider store={configureStore(mockContext, null)}>
       <Component {...props} />
    </Provider>,
    {
      context: {
        router: {
          location: { pathname: '' }
        }
      },
      childContextTypes: {
          router: React.PropTypes.object
      }

    })


问:
How to make your desktop Java app looks like Open Office or Eclipse etc.?
How to make your desktop Java app looks like Open Office or Eclipse  etc ?
Installation process looks like any Windpws app. installation. There is no Java logo on the to on a app window. You run it by .exe file. How it is done? Is this jar->exe conversion?
Is there any free tool to do that?</p>

答:
I think it uses LookAndFeel, I let you read: http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

```<code>try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e){}
</code>```

EDIT: I didn't read the entire question ^^' Maybe it will be useful to someone...

Body:
I think it uses LookAndFeel, I let you read: http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e){}

EDIT: I didn't read the entire question ^^' Maybe it will be useful to someone...


问:
How to remember tkinter window position in python 3?
I have a tkinter gui and I would like it to retain the original window position and size upon relaunching.

Here is an answer that illustrates how to set a specific position and dimensions, but not a word about remembering the settings: How to specify where a Tkinter window opens?

Highly appreciate any help.

答:
The only way to remember settings from session to session is to write them into a file. So, get the root window geometry (it's a string) and write it into a file. If you want the function to be executed automatically as a hook, bind it to the "<Configure>" event:

```<code>def save_size(event):
  with open("myapp.conf", "w") as conf:
    conf.write(root.geometry()) # Assuming root is the root window

root.bind("<Configure>",save_size)
</code>```

You can later read the geometry from the file and restore it.

Body:
The only way to remember settings from session to session is to write them into a file. So, get the root window geometry (it's a string) and write it into a file. If you want the function to be executed automatically as a hook, bind it to the "<Configure>" event:

def save_size(event):
  with open("myapp.conf", "w") as conf:
    conf.write(root.geometry()) # Assuming root is the root window

root.bind("<Configure>",save_size)

You can later read the geometry from the file and restore it.


问:
Using UITabBar and UINavigationBar
I'm facing problem with using UITabBar and UINavigationBar at the same time. My intention is to have tabBar displaying my 3 tabs and navBar on each of these tabs displaying custom name and on some of these tabs additionally displaying some buttons (such as Add button).

I created view controllers in AppDelegate's didFinishLaunchingWithOptions:

```<code>AAA *vc1 = [[AAA alloc] init];
BBB *vc2 = [[BBB alloc] init];
CCC *vc3 = [[CCC alloc] init];
</code>```

Created tabBar and populated it:

```<code>self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[vc1, vc2, vc3];
</code>```

Next I have added some titles and images to the tabBarItems of these view controllers which is all working fine, but than I wanted to display navigation bar on top of the application. So I created navigation controller, but I don't know what view controller I need to initiate it with. If I use vc1 and set navController as rootViewController, application displays vc1's view and shows navBar, but doesn't show tabBar.

```<code>UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc1];
self.window.rootViewController = navController;

//self.window.rootViewController = self.tabBarController;
</code>```

I tried to set tabBarController to init navController and set navController as rootViewController - in this case views, tabBar and navBAr display correctly, but I don't have navBarItems associated with views vc1, vc2, vc3.

This is how I created navBarItems (e.g. in AAA.m):

```<code>- (instancetype)init {
self = [super init];
if (self) {
    UINavigationItem *navItem = self.navigationItem;
    navItem.title = @"name";
}
return self;
}
</code>```

What do I need to do to make it work all together? Thanks.

EDIT:

I made some modification to the code and now navigation bar is visible, but only on the view controller set in UINavigationController's initWithRootViewController method. For example in following code I can see tab bar on every view and nav bar on the vc2 only. And my intention is to have tab bar and nav bar on every of these three vc.

```<code>UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc2];

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:vc1, navController, vc3, nil];

self.window.rootViewController = self.tabBarController;
</code>```

答:
add these line of code on every controller

```<code>[self.tabBarController setTitle:@"xyz"];
self.tabBarController.navigationController.navigationBarHidden=NO;
</code>```

Title: Using UITabBar and UINavigationBar

Body:
I'm facing problem with using UITabBar and UINavigationBar at the same time. My intention is to have tabBar displaying my 3 tabs and navBar on each of these tabs displaying custom name and on some of these tabs additionally displaying some buttons (such as Add button).

I created view controllers in AppDelegate's didFinishLaunchingWithOptions:

AAA *vc1 = [[AAA alloc] init];
BBB *vc2 = [[BBB alloc] init];
CCC *vc3 = [[CCC alloc] init];

Created tabBar and populated it:

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[vc1, vc2, vc3];

Next I have added some titles and images to the tabBarItems of these view controllers which is all working fine, but than I wanted to display navigation bar on top of the application. So I created navigation controller, but I don't know what view controller I need to initiate it with. If I use vc1 and set navController as rootViewController, application displays vc1's view and shows navBar, but doesn't show tabBar.

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc1];
self.window.rootViewController = navController;

//self.window.rootViewController = self.tabBarController;

I tried to set tabBarController to init navController and set navController as rootViewController - in this case views, tabBar and navBAr display correctly, but I don't have navBarItems associated with views vc1, vc2, vc3.

This is how I created navBarItems (e.g. in AAA.m):

- (instancetype)init {
self = [super init];
if (self) {
    UINavigationItem *navItem = self.navigationItem;
    navItem.title = @"name";
}
return self;
}

What do I need to do to make it work all together? Thanks.

EDIT:

I made some modification to the code and now navigation bar is visible, but only on the view controller set in UINavigationController's initWithRootViewController method. For example in following code I can see tab bar on every view and nav bar on the vc2 only. And my intention is to have tab bar and nav bar on every of these three vc.

UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc2];

self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:vc1, navController, vc3, nil];

self.window.rootViewController = self.tabBarController;

Body:
add these line of code on every controller

[self.tabBarController setTitle:@"xyz"];
self.tabBarController.navigationController.navigationBarHidden=NO;


问:
FFmpeg batch script
I have this batch script running perfectly on Windows:

```<code>C:\ffmpeg\bin\ffmpeg -i http://ipaddress/stream -deinterlace -c:v libx264 -pix_fmt yuv420p -s 960x540 -preset superfast -vb 1200k -maxrate 1200k -r 30 -g 60 -bufsize 8000k  -c:a aac -b:a 64k -ar 44100 -ac 2 -f flv rtmp://ipaddress/live/
</code>```

Sometimes ffmpeg crashes, how can I edit the batch script or what can i add to the batch file to restart the stream.

Thanks advance!

答:
I don't know if the ffmpeg command can be restarted this way,

but I would limit the number of retries to avoid endless loops on fails:

```<code>@Echo off
Setlocal EnableDelayedExpansion
Set Retry=0
:loop
C:\ffmpeg\bin\ffmpeg.exe -i http://ipaddress/stream ^
  -deinterlace -c:v libx264 -pix_fmt yuv420p -s 960x540 -preset superfast ^
  -vb 1200k -maxrate 1200k -r 30 -g 60 -bufsize 8000k -c:a aac -b:a 64k ^
  -ar 44100 -ac 2 -f flv rtmp://ipaddress/live/ ^
  ||(Set /A "Retry+=1"&if !Retry! leq 3 Goto :loop)
</code>```

Title: FFmpeg batch script

Body:
I have this batch script running perfectly on Windows:

C:\ffmpeg\bin\ffmpeg -i http://ipaddress/stream -deinterlace -c:v libx264 -pix_fmt yuv420p -s 960x540 -preset superfast -vb 1200k -maxrate 1200k -r 30 -g 60 -bufsize 8000k  -c:a aac -b:a 64k -ar 44100 -ac 2 -f flv rtmp://ipaddress/live/

Sometimes ffmpeg crashes, how can I edit the batch script or what can i add to the batch file to restart the stream.

Thanks advance!

Body:
I don't know if the ffmpeg command can be restarted this way,

but I would limit the number of retries to avoid endless loops on fails:

@Echo off
Setlocal EnableDelayedExpansion
Set Retry=0
:loop
C:\ffmpeg\bin\ffmpeg.exe -i http://ipaddress/stream ^
  -deinterlace -c:v libx264 -pix_fmt yuv420p -s 960x540 -preset superfast ^
  -vb 1200k -maxrate 1200k -r 30 -g 60 -bufsize 8000k -c:a aac -b:a 64k ^
  -ar 44100 -ac 2 -f flv rtmp://ipaddress/live/ ^
  ||(Set /A "Retry+=1"&if !Retry! leq 3 Goto :loop)


问:
sequelizejs eager fetch many to many
I am trying to fetch eager on a join table in Nodejs with Sequelizejs v3 .

So, 1 Tag can belong to Many Images, and Many Images can have multiple tags.

Tag 1 - > M ImageTag M < - 1 Image

I am getting Unhandled rejection Error: Tag is not associated to ImageDetails when i tried to excute a query.

```<code>function getImagesFromAlbum(albumid, callback, errCallback){
  ImageDetails.findAll({where: { AlbumId: albumid }, include: [{model: Tag}]}).then((data) => {
    return callback(data)
  }).catch((err) => {
    return errCallback(err)
  })
}
</code>```

The expected return result should be the data according to the albumid, with the assiociate tags for that image

Here are the relationship joining

```<code>ImageDetails.belongsToMany(Tag, { as: { singular: "tag", plural: "tags" }, through: { model: ImageTag, unique: false }, foreignKey: "ImageId"})
Tag.belongsToMany(ImageDetails, { as: { singular: "image", plural: "images" }, through: { model: ImageTag, unique: false },  foreignKey: "TagId"})
</code>```

Here are the model designs

Tag Model

```<code>const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING
  }
}

const name = "Tag"
</code>```

ImageTag model (Join Table)

```<code>const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  }
}
const name = "ImageTag"
</code>```

ImageDetails model

```<code>import { Sequelize, db } from "../config/MySqlConfiguration"

const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  ImageLocation: {
    type: Sequelize.STRING
  },
  originalName: {
    type: Sequelize.STRING
  }
}

const name = "ImageDetails"
</code>```

*Note sequelize.define is purposely omitted.

答:
When defining relation between models with use of alias (as) in the belongsToMany, you need to remember to include this alias when eager loading models, so your query would look as follows

ImageDetails.findAll({
    where: { AlbumId: albumid },
    include: [{ model: Tag, as: 'tags' }]
}).then((data) => {
    return callback(data)
}).catch((err) => {
    return errCallback(err)
});
```

And what is the AlbumId you want to perform query on? According to your models definition, the ImageDetails model does not have such a field.

Title: sequelizejs eager fetch many to many

Body:
I am trying to fetch eager on a join table in Nodejs with Sequelizejs v3 .

So, 1 Tag can belong to Many Images, and Many Images can have multiple tags.

Tag 1 - > M ImageTag M < - 1 Image

I am getting Unhandled rejection Error: Tag is not associated to ImageDetails when i tried to excute a query.

function getImagesFromAlbum(albumid, callback, errCallback){
  ImageDetails.findAll({where: { AlbumId: albumid }, include: [{model: Tag}]}).then((data) => {
    return callback(data)
  }).catch((err) => {
    return errCallback(err)
  })
}

The expected return result should be the data according to the albumid, with the assiociate tags for that image

Here are the relationship joining

ImageDetails.belongsToMany(Tag, { as: { singular: "tag", plural: "tags" }, through: { model: ImageTag, unique: false }, foreignKey: "ImageId"})
Tag.belongsToMany(ImageDetails, { as: { singular: "image", plural: "images" }, through: { model: ImageTag, unique: false },  foreignKey: "TagId"})

Here are the model designs

Tag Model

const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING
  }
}

const name = "Tag"

ImageTag model (Join Table)

const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  }
}
const name = "ImageTag"

ImageDetails model

import { Sequelize, db } from "../config/MySqlConfiguration"

const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  ImageLocation: {
    type: Sequelize.STRING
  },
  originalName: {
    type: Sequelize.STRING
  }
}

const name = "ImageDetails"

*Note sequelize.define is purposely omitted.

Body:
When defining relation between models with use of alias (as) in the belongsToMany, you need to remember to include this alias when eager loading models, so your query would look as follows

ImageDetails.findAll({
    where: { AlbumId: albumid },
    include: [{ model: Tag, as: 'tags' }]
}).then((data) => {
    return callback(data)
}).catch((err) => {
    return errCallback(err)
});

And what is the AlbumId you want to perform query on? According to your models definition, the ImageDetails model does not have such a field.