问:
NodeJS Cannot find module 'io' ( socket.io with express 4.15.3)
I am new in NodeJS. I am trying to run simple chat application with express and socket.io module, but when I run application, on the page where I am using socket, on console I am getting this error, and can't understand the problem. on web page I am getting this (see attached image)

```<code>Error: Cannot find module 'io'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at new View (/Applications/XAMPP/xamppfiles/htdocs/NODE/express/node_modules/express/lib/view.js:80:30)
</code>```

Actually I have found this example in internet ( https://github.com/socketio/socket.io/tree/master/examples/chat ), and try to join it to my project.For view I am using EJS. All my JS and css files in public directory, I have copied socket.io.js from node_modules/socket.io-client/dist/socket.io.js to my javascript directory. Here is my code.

app.js

```<code>let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let expressValidator = require('express-validator');
let db = require('mysql');
let sessions = require('express-session');

let session;

let app = express();

let connection = db.createConnection({
    host:"localhost",
    user:'root',
    password:'',
    database:'oulala'
});

connection.connect((error)=>{
    if(error){
        console.log('Error')
    }else{
        console.log("connected");
    }
});

//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
    secret:'$%2878asd8783yuh3b129x831726375r367*&^%$#',
    resave:false,
    saveUninitialized:true
}))

//View engine
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));

app.use(express.static(__dirname + '/public'));

//Global Vars

app.use((req,res,next)=>{
    res.locals.errors = null;
    res.locals.isAuthenticated = false;
    next();
});

app.use(expressValidator({
    errorFormatter: (param,msg,value)=>{
        let namespace = param.split('.')
        , root = namespace.shift()
        , formParam = root;

        while(namespace.length){
            formParam+= '['+namespace.shift()+']';
        }
        return {
            param : formParam,
            msg   : msg,
            value : value
        }

    }
}));

app.get('/logout',(req,res)=>{
    req.session.destroy((error)=>{
        res.redirect('/');
    })
})

app.post('/login',(req,res) => {
    session = req.session;
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('password','Password is required').notEmpty();
    errors = req.validationErrors();
    if ( errors ) {
        res.render('login',{
            title:"Login",
            errors:errors
        });
    }else{
        if(req.body.username == 'admin' && req.body.password == 'admin'){
            session.uniqueID = req.body.username;
            isAuthenticated = true;
        }
        res.redirect('/');
    }
})

app.get('/:page?',(req,res) => {
    //res.send('Hello first page');
    //res.json(people);

    let page = req.params.page;
    if ( page ) {
        if ( page == 'posts' ){
            connection.query("SELECT * FROM members",(error,rows,fields)=>{
                if(error){
                    connection.release();
                    console.log('Error in the query - '+error);

                }else{
                    res.render(page,{
                        title:page,
                        users:rows
                    });
                }
            });

        }else{
            res.render(page,{
                title:page,
                user:authenticate
            });
        }

    }else{

        session = req.session;
        if(session.uniqueID){
            res.render('index',{
                title:"Index",
                user:authenticate
            });
        }else{
            res.render('login',{
                title:"Login",
                user:authenticate
            });
        }
    }

});

// get form submition, post request
app.post('/users/add',(req,res) => {
    //console.log(req.body.first_name); // req.body - request object

    req.checkBody('first_name','Fisrtname is required').notEmpty();
    req.checkBody('last_name','Lastname is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    errors = req.validationErrors();

    if ( errors ) {
        res.render('index',{
            title:"Customers",
            users:people,
            errors:errors
        });
    }else{
        var newUser = {
            first_name:req.body.first_name,
            last_name:req.body.last_name,
            email:req.body.email
        }

        people.push(newUser);

        res.render(page,{
            title:page,
            users:people,
            user:authenticate
        });
    }

});

app.listen(3000, () => {
    console.log('server started on port 3000....');
});

var server = require('http').createServer(app);
var io = require('socket.io')(server);

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
</code>```

client.js

```<code>$(function() {
  var FADE_TIME = 150; // ms
  var TYPING_TIMER_LENGTH = 400; // ms
  var COLORS = [
    '#e21400', '#91580f', '#f8a700', '#f78b00',
    '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
    '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
  ];

  // Initialize variables
  var $window = $(window);
  var $usernameInput = $('.usernameInput'); // Input for username
  var $messages = $('.messages'); // Messages area
  var $inputMessage = $('.inputMessage'); // Input message input box

  var $loginPage = $('.login.page'); // The login page
  var $chatPage = $('.chat.page'); // The chatroom page

  // Prompt for setting a username
  var username;
  var connected = false;
  var typing = false;
  var lastTypingTime;
  var $currentInput = $usernameInput.focus();

  var socket = io();

  function addParticipantsMessage (data) {
    var message = '';
    if (data.numUsers === 1) {
      message += "there's 1 participant";
    } else {
      message += "there are " + data.numUsers + " participants";
    }
    log(message);
  }

  // Sets the client's username
  function setUsername () {
    username = cleanInput($usernameInput.val().trim());

    // If the username is valid
    if (username) {
      $loginPage.fadeOut();
      $chatPage.show();
      $loginPage.off('click');
      $currentInput = $inputMessage.focus();

      // Tell the server your username
      socket.emit('add user', username);
    }
  }

  // Sends a chat message
  function sendMessage () {
    var message = $inputMessage.val();
    // Prevent markup from being injected into the message
    message = cleanInput(message);
    // if there is a non-empty message and a socket connection
    if (message && connected) {
      $inputMessage.val('');
      addChatMessage({
        username: username,
        message: message
      });
      // tell server to execute 'new message' and send along one parameter
      socket.emit('new message', message);
    }
  }

  // Log a message
  function log (message, options) {
    var $el = $('<li>').addClass('log').text(message);
    addMessageElement($el, options);
  }

  // Adds the visual chat message to the message list
  function addChatMessage (data, options) {
    // Don't fade the message in if there is an 'X was typing'
    var $typingMessages = getTypingMessages(data);
    options = options || {};
    if ($typingMessages.length !== 0) {
      options.fade = false;
      $typingMessages.remove();
    }

    var $usernameDiv = $('<span class="username"/>')
      .text(data.username)
      .css('color', getUsernameColor(data.username));
    var $messageBodyDiv = $('<span class="messageBody">')
      .text(data.message);

    var typingClass = data.typing ? 'typing' : '';
    var $messageDiv = $('<li class="message"/>')
      .data('username', data.username)
      .addClass(typingClass)
      .append($usernameDiv, $messageBodyDiv);

    addMessageElement($messageDiv, options);
  }

  // Adds the visual chat typing message
  function addChatTyping (data) {
    data.typing = true;
    data.message = 'is typing';
    addChatMessage(data);
  }

  // Removes the visual chat typing message
  function removeChatTyping (data) {
    getTypingMessages(data).fadeOut(function () {
      $(this).remove();
    });
  }

  // Adds a message element to the messages and scrolls to the bottom
  // el - The element to add as a message
  // options.fade - If the element should fade-in (default = true)
  // options.prepend - If the element should prepend
  //   all other messages (default = false)
  function addMessageElement (el, options) {
    var $el = $(el);

    // Setup default options
    if (!options) {
      options = {};
    }
    if (typeof options.fade === 'undefined') {
      options.fade = true;
    }
    if (typeof options.prepend === 'undefined') {
      options.prepend = false;
    }

    // Apply options
    if (options.fade) {
      $el.hide().fadeIn(FADE_TIME);
    }
    if (options.prepend) {
      $messages.prepend($el);
    } else {
      $messages.append($el);
    }
    $messages[0].scrollTop = $messages[0].scrollHeight;
  }

  // Prevents input from having injected markup
  function cleanInput (input) {
    return $('<div/>').text(input).text();
  }

  // Updates the typing event
  function updateTyping () {
    if (connected) {
      if (!typing) {
        typing = true;
        socket.emit('typing');
      }
      lastTypingTime = (new Date()).getTime();

      setTimeout(function () {
        var typingTimer = (new Date()).getTime();
        var timeDiff = typingTimer - lastTypingTime;
        if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
          socket.emit('stop typing');
          typing = false;
        }
      }, TYPING_TIMER_LENGTH);
    }
  }

  // Gets the 'X is typing' messages of a user
  function getTypingMessages (data) {
    return $('.typing.message').filter(function (i) {
      return $(this).data('username') === data.username;
    });
  }

  // Gets the color of a username through our hash function
  function getUsernameColor (username) {
    // Compute hash code
    var hash = 7;
    for (var i = 0; i < username.length; i++) {
       hash = username.charCodeAt(i) + (hash << 5) - hash;
    }
    // Calculate color
    var index = Math.abs(hash % COLORS.length);
    return COLORS[index];
  }

  // Keyboard events

  $window.keydown(function (event) {
    // Auto-focus the current input when a key is typed
    if (!(event.ctrlKey || event.metaKey || event.altKey)) {
      $currentInput.focus();
    }
    // When the client hits ENTER on their keyboard
    if (event.which === 13) {
      if (username) {
        sendMessage();
        socket.emit('stop typing');
        typing = false;
      } else {
        setUsername();
      }
    }
  });

  $inputMessage.on('input', function() {
    updateTyping();
  });

  // Click events

  // Focus input when clicking anywhere on login page
  $loginPage.click(function () {
    $currentInput.focus();
  });

  // Focus input when clicking on the message input's border
  $inputMessage.click(function () {
    $inputMessage.focus();
  });

  // Socket events

  // Whenever the server emits 'login', log the login message
  socket.on('login', function (data) {
    connected = true;
    // Display the welcome message
    var message = "Welcome to Socket.IO Chat – ";
    log(message, {
      prepend: true
    });
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'new message', update the chat body
  socket.on('new message', function (data) {
    addChatMessage(data);
  });

  // Whenever the server emits 'user joined', log it in the chat body
  socket.on('user joined', function (data) {
    log(data.username + ' joined');
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'user left', log it in the chat body
  socket.on('user left', function (data) {
    log(data.username + ' left');
    addParticipantsMessage(data);
    removeChatTyping(data);
  });

  // Whenever the server emits 'typing', show the typing message
  socket.on('typing', function (data) {
    addChatTyping(data);
  });

  // Whenever the server emits 'stop typing', kill the typing message
  socket.on('stop typing', function (data) {
    removeChatTyping(data);
  });

  socket.on('disconnect', function () {
    log('you have been disconnected');
  });

  socket.on('reconnect', function () {
    log('you have been reconnected');
    if (username) {
      socket.emit('add user', username);
    }
  });

  socket.on('reconnect_error', function () {
    log('attempt to reconnect has failed');
  });

});
</code>```

index.ejs

```<code><% include partials/header %>
    <h1><%= title %></h1>
    <ul class="pages">
    <li class="chat page">
      <div class="chatArea">
        <ul class="messages"></ul>
      </div>
      <input class="inputMessage" placeholder="Type here..."/>
    </li>
    <li class="login page">
      <div class="form">
        <h3 class="title">What's your nickname?</h3>
        <input class="usernameInput" type="text" maxlength="14" />
      </div>
    </li>
  </ul>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="/javascript/socket.io.js"></script>
    <script src="/javascript/client.js"></script>
<% include partials/footer %>
</code>```

package.json

```<code>{
  "name": "customerapp",
  "version": "1.0.0",
  "description": "Simple customer managment app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Anna Gabrielyan",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.6",
    "express": "^4.15.3",
    "express-session": "^1.15.3",
    "express-validator": "^3.2.0",
    "mysql": "^3.10.10",
    "oauth2-server": "^2.4.1",
    "socket.io": "^2.0.2"
  }
}
</code>```

答:
did you install socket.io using npm. if not try

```<code>npm install --save socket.io
</code>```

can you show me package.json,?

Body:
I am new in NodeJS. I am trying to run simple chat application with express and socket.io module, but when I run application, on the page where I am using socket, on console I am getting this error, and can't understand the problem. on web page I am getting this (see attached image)

Error: Cannot find module 'io'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at new View (/Applications/XAMPP/xamppfiles/htdocs/NODE/express/node_modules/express/lib/view.js:80:30)

Actually I have found this example in internet ( https://github.com/socketio/socket.io/tree/master/examples/chat ), and try to join it to my project.For view I am using EJS. All my JS and css files in public directory, I have copied socket.io.js from node_modules/socket.io-client/dist/socket.io.js to my javascript directory. Here is my code.

app.js

let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let expressValidator = require('express-validator');
let db = require('mysql');
let sessions = require('express-session');

let session;

let app = express();

let connection = db.createConnection({
    host:"localhost",
    user:'root',
    password:'',
    database:'oulala'
});

connection.connect((error)=>{
    if(error){
        console.log('Error')
    }else{
        console.log("connected");
    }
});

//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
    secret:'$%2878asd8783yuh3b129x831726375r367*&^%$#',
    resave:false,
    saveUninitialized:true
}))

//View engine
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));

app.use(express.static(__dirname + '/public'));

//Global Vars

app.use((req,res,next)=>{
    res.locals.errors = null;
    res.locals.isAuthenticated = false;
    next();
});

app.use(expressValidator({
    errorFormatter: (param,msg,value)=>{
        let namespace = param.split('.')
        , root = namespace.shift()
        , formParam = root;

        while(namespace.length){
            formParam+= '['+namespace.shift()+']';
        }
        return {
            param : formParam,
            msg   : msg,
            value : value
        }

    }
}));

app.get('/logout',(req,res)=>{
    req.session.destroy((error)=>{
        res.redirect('/');
    })
})

app.post('/login',(req,res) => {
    session = req.session;
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('password','Password is required').notEmpty();
    errors = req.validationErrors();
    if ( errors ) {
        res.render('login',{
            title:"Login",
            errors:errors
        });
    }else{
        if(req.body.username == 'admin' && req.body.password == 'admin'){
            session.uniqueID = req.body.username;
            isAuthenticated = true;
        }
        res.redirect('/');
    }
})

app.get('/:page?',(req,res) => {
    //res.send('Hello first page');
    //res.json(people);

    let page = req.params.page;
    if ( page ) {
        if ( page == 'posts' ){
            connection.query("SELECT * FROM members",(error,rows,fields)=>{
                if(error){
                    connection.release();
                    console.log('Error in the query - '+error);

                }else{
                    res.render(page,{
                        title:page,
                        users:rows
                    });
                }
            });

        }else{
            res.render(page,{
                title:page,
                user:authenticate
            });
        }

    }else{

        session = req.session;
        if(session.uniqueID){
            res.render('index',{
                title:"Index",
                user:authenticate
            });
        }else{
            res.render('login',{
                title:"Login",
                user:authenticate
            });
        }
    }

});

// get form submition, post request
app.post('/users/add',(req,res) => {
    //console.log(req.body.first_name); // req.body - request object

    req.checkBody('first_name','Fisrtname is required').notEmpty();
    req.checkBody('last_name','Lastname is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    errors = req.validationErrors();

    if ( errors ) {
        res.render('index',{
            title:"Customers",
            users:people,
            errors:errors
        });
    }else{
        var newUser = {
            first_name:req.body.first_name,
            last_name:req.body.last_name,
            email:req.body.email
        }

        people.push(newUser);

        res.render(page,{
            title:page,
            users:people,
            user:authenticate
        });
    }

});

app.listen(3000, () => {
    console.log('server started on port 3000....');
});

var server = require('http').createServer(app);
var io = require('socket.io')(server);

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});

client.js

$(function() {
  var FADE_TIME = 150; // ms
  var TYPING_TIMER_LENGTH = 400; // ms
  var COLORS = [
    '#e21400', '#91580f', '#f8a700', '#f78b00',
    '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
    '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
  ];

  // Initialize variables
  var $window = $(window);
  var $usernameInput = $('.usernameInput'); // Input for username
  var $messages = $('.messages'); // Messages area
  var $inputMessage = $('.inputMessage'); // Input message input box

  var $loginPage = $('.login.page'); // The login page
  var $chatPage = $('.chat.page'); // The chatroom page

  // Prompt for setting a username
  var username;
  var connected = false;
  var typing = false;
  var lastTypingTime;
  var $currentInput = $usernameInput.focus();

  var socket = io();

  function addParticipantsMessage (data) {
    var message = '';
    if (data.numUsers === 1) {
      message += "there's 1 participant";
    } else {
      message += "there are " + data.numUsers + " participants";
    }
    log(message);
  }

  // Sets the client's username
  function setUsername () {
    username = cleanInput($usernameInput.val().trim());

    // If the username is valid
    if (username) {
      $loginPage.fadeOut();
      $chatPage.show();
      $loginPage.off('click');
      $currentInput = $inputMessage.focus();

      // Tell the server your username
      socket.emit('add user', username);
    }
  }

  // Sends a chat message
  function sendMessage () {
    var message = $inputMessage.val();
    // Prevent markup from being injected into the message
    message = cleanInput(message);
    // if there is a non-empty message and a socket connection
    if (message && connected) {
      $inputMessage.val('');
      addChatMessage({
        username: username,
        message: message
      });
      // tell server to execute 'new message' and send along one parameter
      socket.emit('new message', message);
    }
  }

  // Log a message
  function log (message, options) {
    var $el = $('
').addClass('log').text(message);
    addMessageElement($el, options);
  }

  // Adds the visual chat message to the message list
  function addChatMessage (data, options) {
    // Don't fade the message in if there is an 'X was typing'
    var $typingMessages = getTypingMessages(data);
    options = options || {};
    if ($typingMessages.length !== 0) {
      options.fade = false;
      $typingMessages.remove();
    }

    var $usernameDiv = $('')
      .text(data.username)
      .css('color', getUsernameColor(data.username));
    var $messageBodyDiv = $('')
      .text(data.message);

    var typingClass = data.typing ? 'typing' : '';
    var $messageDiv = $('
')
      .data('username', data.username)
      .addClass(typingClass)
      .append($usernameDiv, $messageBodyDiv);

    addMessageElement($messageDiv, options);
  }

  // Adds the visual chat typing message
  function addChatTyping (data) {
    data.typing = true;
    data.message = 'is typing';
    addChatMessage(data);
  }

  // Removes the visual chat typing message
  function removeChatTyping (data) {
    getTypingMessages(data).fadeOut(function () {
      $(this).remove();
    });
  }

  // Adds a message element to the messages and scrolls to the bottom
  // el - The element to add as a message
  // options.fade - If the element should fade-in (default = true)
  // options.prepend - If the element should prepend
  //   all other messages (default = false)
  function addMessageElement (el, options) {
    var $el = $(el);

    // Setup default options
    if (!options) {
      options = {};
    }
    if (typeof options.fade === 'undefined') {
      options.fade = true;
    }
    if (typeof options.prepend === 'undefined') {
      options.prepend = false;
    }

    // Apply options
    if (options.fade) {
      $el.hide().fadeIn(FADE_TIME);
    }
    if (options.prepend) {
      $messages.prepend($el);
    } else {
      $messages.append($el);
    }
    $messages[0].scrollTop = $messages[0].scrollHeight;
  }

  // Prevents input from having injected markup
  function cleanInput (input) {
    return $('
').text(input).text();
  }

  // Updates the typing event
  function updateTyping () {
    if (connected) {
      if (!typing) {
        typing = true;
        socket.emit('typing');
      }
      lastTypingTime = (new Date()).getTime();

      setTimeout(function () {
        var typingTimer = (new Date()).getTime();
        var timeDiff = typingTimer - lastTypingTime;
        if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
          socket.emit('stop typing');
          typing = false;
        }
      }, TYPING_TIMER_LENGTH);
    }
  }

  // Gets the 'X is typing' messages of a user
  function getTypingMessages (data) {
    return $('.typing.message').filter(function (i) {
      return $(this).data('username') === data.username;
    });
  }

  // Gets the color of a username through our hash function
  function getUsernameColor (username) {
    // Compute hash code
    var hash = 7;
    for (var i = 0; i < username.length; i++) {
       hash = username.charCodeAt(i) + (hash << 5) - hash;
    }
    // Calculate color
    var index = Math.abs(hash % COLORS.length);
    return COLORS[index];
  }

  // Keyboard events

  $window.keydown(function (event) {
    // Auto-focus the current input when a key is typed
    if (!(event.ctrlKey || event.metaKey || event.altKey)) {
      $currentInput.focus();
    }
    // When the client hits ENTER on their keyboard
    if (event.which === 13) {
      if (username) {
        sendMessage();
        socket.emit('stop typing');
        typing = false;
      } else {
        setUsername();
      }
    }
  });

  $inputMessage.on('input', function() {
    updateTyping();
  });

  // Click events

  // Focus input when clicking anywhere on login page
  $loginPage.click(function () {
    $currentInput.focus();
  });

  // Focus input when clicking on the message input's border
  $inputMessage.click(function () {
    $inputMessage.focus();
  });

  // Socket events

  // Whenever the server emits 'login', log the login message
  socket.on('login', function (data) {
    connected = true;
    // Display the welcome message
    var message = "Welcome to Socket.IO Chat – ";
    log(message, {
      prepend: true
    });
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'new message', update the chat body
  socket.on('new message', function (data) {
    addChatMessage(data);
  });

  // Whenever the server emits 'user joined', log it in the chat body
  socket.on('user joined', function (data) {
    log(data.username + ' joined');
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'user left', log it in the chat body
  socket.on('user left', function (data) {
    log(data.username + ' left');
    addParticipantsMessage(data);
    removeChatTyping(data);
  });

  // Whenever the server emits 'typing', show the typing message
  socket.on('typing', function (data) {
    addChatTyping(data);
  });

  // Whenever the server emits 'stop typing', kill the typing message
  socket.on('stop typing', function (data) {
    removeChatTyping(data);
  });

  socket.on('disconnect', function () {
    log('you have been disconnected');
  });

  socket.on('reconnect', function () {
    log('you have been reconnected');
    if (username) {
      socket.emit('add user', username);
    }
  });

  socket.on('reconnect_error', function () {
    log('attempt to reconnect has failed');
  });

});

index.ejs

<% include partials/header %>

<%= title %>

      <input class="inputMessage" placeholder="Type here..."/>

What's your nickname?

        <input class="usernameInput" type="text" maxlength="14" />

<% include partials/footer %>

package.json

{
  "name": "customerapp",
  "version": "1.0.0",
  "description": "Simple customer managment app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Anna Gabrielyan",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.6",
    "express": "^4.15.3",
    "express-session": "^1.15.3",
    "express-validator": "^3.2.0",
    "mysql": "^3.10.10",
    "oauth2-server": "^2.4.1",
    "socket.io": "^2.0.2"
  }
}

Body:
did you install socket.io using npm. if not try

npm install --save socket.io

can you show me package.json,?


来源: stackexchange

问:
How to get required combinations from different rows of column in python
I am trying to get the different required combinations out from dataframe column with few rows.It is something like below:
I have following values in one of the columns of my df

```<code>Oy
On
G1
G2
A1
A2
A3
A4
R1
R2
R3
L1
L2
A5
A6
</code>```

Here oy,on belong to group 1,

```<code>G1,g2 - group 2,
A1 to a4 - group 3,
R1 to r3 - group 4,
L1,l2 - group 5,
A5,a6 - group 6
</code>```

Now I am trying all the combinations from each value of the each group ranging from 1 value to all like below:

```<code>Oy
Oy g1
Oy g1 a1
Oy g1 a1 r1
Oy g1 a1 r1 l1
Oy g1 a1 r1 l1 a5
</code>```

This will be for all possible combinations.note that within group combination is not desirable like g1 and g2 cannot come in same combination.

I know that this is possible with for loops with some if conditions.But looking for more efficient and elegant solution.

答:
I think you may want to itertools.product on the various groupings.
To get the groups you could do

```<code>first_letter = df[col].str[0].str.lower()
groups = df[col].groupby(first_letter).unique()
</code>```

(col here is the name of the column describe above).

This gives a mapping from the first letter (lowercase) to an array of the unique values starting with that letter (lower or upper case). Then you can do itertools.product(*groups) to get all six-tuples containing one member from each group.
To get all combinations of, say, the g and o groups, you can do itertools.product(*groups[['g', 'o']])

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get the different required combinations out from dataframe column with few rows.It is something like below:
I have following values in one of the columns of my df

Oy
On
G1
G2
A1
A2
A3
A4
R1
R2
R3
L1
L2
A5
A6

Here oy,on belong to group 1,

G1,g2 - group 2,
A1 to a4 - group 3,
R1 to r3 - group 4,
L1,l2 - group 5,
A5,a6 - group 6

Now I am trying all the combinations from each value of the each group ranging from 1 value to all like below:

Oy
Oy g1
Oy g1 a1
Oy g1 a1 r1
Oy g1 a1 r1 l1
Oy g1 a1 r1 l1 a5

This will be for all possible combinations.note that within group combination is not desirable like g1 and g2 cannot come in same combination.

I know that this is possible with for loops with some if conditions.But looking for more efficient and elegant solution.

Body:
I think you may want to itertools.product on the various groupings.
To get the groups you could do

first_letter = df[col].str[0].str.lower()
groups = df[col].groupby(first_letter).unique()

(col here is the name of the column describe above).

This gives a mapping from the first letter (lowercase) to an array of the unique values starting with that letter (lower or upper case). Then you can do itertools.product(*groups) to get all six-tuples containing one member from each group.
To get all combinations of, say, the g and o groups, you can do itertools.product(*groups[['g', 'o']])


问:
Convert Column from String to Int - Alter Script MSSQL
Can you change a column from a varchar to an int.

I have a table with a zipcode column and I want the zips to be ints instead of varchars.

答:
```<code>ALTER TABLE [TableName]
ALTER COLUMN ZipCode INT
</code>```

ContentLicense: CC BY-SA 2.5


问:
Angular 2 Router Link with multiple parameters
I have a route like this

```<code>   path: 'projects/:id/settings'
</code>```

And in my header.component.html I want to have a link to this page

```<code><a routerLink="['projects', progectId,'settings']" routerLinkActive="active">cool link</a>
</code>```

I have a project.component, where when I click on some project I go on the project page. And then I need have a possibility go to projects/:id/settings or another similar route.

How can I pass progectId variable from projects.component?

Or maybe somebody knows another way to implement this.

答:
I had the same issue for this kind of route you should use routerLink like this:

```<code><a routerLink="/projects/{{progectId}}/settings" routerLinkActive="active">cool link</a>
</code>```

and change your route path in routing module like this:

```<code>{ path: ':id/settings', component: YourComponent}
</code>```

for additional information to get projectId you should follow these step:

Inject ActivatedRoute object in your component constructor.

Define a variable called projectId in your component.

Get params by activatedRoute object in ngOnInit() method.

Finally you should get projectId in your html like this: {{projectId}}

```<code>import {Router, ActivatedRoute, Params} from '@angular/router';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})

export class YourComponent implements OnInit {

  private projectId: string;

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
     this.activatedRoute.params.subscribe((params: Params) => {
     this.projectId = params['id'];
  });
 }}
</code>```

Body:
I have a route like this

   path: 'projects/:id/settings'

And in my header.component.html I want to have a link to this page

cool link

I have a project.component, where when I click on some project I go on the project page. And then I need have a possibility go to projects/:id/settings or another similar route.

How can I pass progectId variable from projects.component?

Or maybe somebody knows another way to implement this.

Body:
I had the same issue for this kind of route you should use routerLink like this:

<a routerLink="/projects/{{progectId}}/settings" routerLinkActive="active">cool link</a>

and change your route path in routing module like this:

{ path: ':id/settings', component: YourComponent}

for additional information to get projectId you should follow these step:

Inject ActivatedRoute object in your component constructor.

Define a variable called projectId in your component.

Get params by activatedRoute object in ngOnInit() method.

Finally you should get projectId in your html like this: {{projectId}}

import {Router, ActivatedRoute, Params} from '@angular/router';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})

export class YourComponent implements OnInit {

  private projectId: string;

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
     this.activatedRoute.params.subscribe((params: Params) => {
     this.projectId = params['id'];
  });
 }}


问:
Flagging/updating values based on other values in the same table
Disclaimer - I'm very very new to the world of MySQL and databases/PHP. However, I've been thrown into a last minute position of damage control to try and get a database issue resolved.

Background: This site has an upload feature where a CSV can be uploaded (using one consistent template) and is inserted into a DB table called 'staging'. There are quite a few columns but for now it's just one table. The data is displayed on the front end in a datatable for the user/admin to view.

This person wants the database to preform QA/QC checks on some of the data with a MYSQL statement and I'm unsure how to do so. I'm thinking of a potential UPDATE statement but either way I would need this to be done in a trigger after upload that won't conflict with the actual upload.

As an example of what would need to be done:

One of the checks is against two columns in the database: 'lowSideMIUNumberDepart' and 'lowSideMIUNumberArrive'. Sometimes, the numbers in those two fields match and sometimes they don't. There's another column called 'miu'that depends on those columns. So, if the numbers match, 'miu' should say "NO" and if they are different it should say "YES".

Thes YES and NO are already in the CSV but it needs to check to make sure it's right. I need to find a way to check so that if the numbers match but 'miu' says YES, it can either flag the discrepency or change it to the appropriate value.

There are other issues like this, but they all follow this type of pattern so I'm hoping that if I figure it out for one set of QA I can apply the same practice to the other 7 sets.

Any help or ideas on getting this to work will be much appreciated.

答:
Take a look at the triggers documenation:

Trigger Syntax and Examples

You could build a trigger that simply updates mui to the correct value on insert:

```<code>CREATE TRIGGER update_miu AFTER INSERT ON staging
       FOR EACH ROW
       SET miu = IF(NEW.lowSideMIUNumberArrive = NEW.lowSideMIUNumberDepart,"YES","NO");
</code>```

Body:
Take a look at the triggers documenation:

Trigger Syntax and Examples

You could build a trigger that simply updates mui to the correct value on insert:

CREATE TRIGGER update_miu AFTER INSERT ON staging
       FOR EACH ROW
       SET miu = IF(NEW.lowSideMIUNumberArrive = NEW.lowSideMIUNumberDepart,"YES","NO");


问:
How to create Dialog Box with Radio Buttons and return Value
I have a List of Objects. What I want to do:

Build a Dialog Box which shows a Radio Button for each element in the given List and returning the selected element/value by clicking on OK-Button.

Thanks in Advance.

答:
Here is a quick example of creating your own form and getting a value from it.

Form1.cs:

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frmTest frmTest = new frmTest();

        DialogResult dr = frmTest.ShowDialog();

        if(dr == System.Windows.Forms.DialogResult.OK)
        {
            string value = frmTest.GetValue();
            MessageBox.Show(value);
        }
    }
}
</code>```

Form1 View:

```<code>public partial class frmTest : Form
{
    private string _value { get; set; }
    public frmTest()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        this.Close();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
        this.Close();
    }

    private void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton radioButton = (RadioButton)sender;

        this._value = radioButton.Text; // Assign the radio button text as value Ex: AAA
    }

    public string GetValue()
    {
        return this._value;
    }
}
</code>```

You have to make sure that all radio buttons are using radioButton_CheckedChanged for the CheckedChanged event.

Form2 View:

Output:

Body:
Here is a quick example of creating your own form and getting a value from it.

Form1.cs:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frmTest frmTest = new frmTest();

        DialogResult dr = frmTest.ShowDialog();

        if(dr == System.Windows.Forms.DialogResult.OK)
        {
            string value = frmTest.GetValue();
            MessageBox.Show(value);
        }
    }
}

Form1 View:

public partial class frmTest : Form
{
    private string _value { get; set; }
    public frmTest()
    {
        InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        this.Close();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
        this.Close();
    }

    private void radioButton_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton radioButton = (RadioButton)sender;

        this._value = radioButton.Text; // Assign the radio button text as value Ex: AAA
    }

    public string GetValue()
    {
        return this._value;
    }
}

You have to make sure that all radio buttons are using radioButton_CheckedChanged for the CheckedChanged event.

Form2 View:

Output:


问:
Laravel: Interface 'Psr\Http\Message\UriInterface' not found
I am facing this error when trying to call a function that connects to an api.

The full error is:

```<code>Symfony\Component\Debug\Exception\FatalErrorException: Interface 'Psr\Http\Message\UriInterface' not found in /path/to/project/vendor/guzzlehttp/psr7/src/Uri.php:13
</code>```

Cannot find much help on forums.

EDIT

Actually this is all the error I get, see this screenshot:

Even in the logs that are generated in /storage/logs, I only get this message:

```<code>[2017-06-08 03:03:35] local.ERROR: Symfony\Component\Debug\Exception\FatalErrorException: Interface 'Psr\Http\Message\UriInterface' not found in /path/to/project/vendor/guzzlehttp/psr7/src/Uri.php:13
Stack trace:
#0 {main}
</code>```

答: Is your composer version up to date? Have you tried composer dump-autoload -o?

Body:
I am facing this error when trying to call a function that connects to an api.

The full error is:

Symfony\Component\Debug\Exception\FatalErrorException: Interface 'Psr\Http\Message\UriInterface' not found in /path/to/project/vendor/guzzlehttp/psr7/src/Uri.php:13

Cannot find much help on forums.

EDIT

Actually this is all the error I get, see this screenshot:

Even in the logs that are generated in /storage/logs, I only get this message:

[2017-06-08 03:03:35] local.ERROR: Symfony\Component\Debug\Exception\FatalErrorException: Interface 'Psr\Http\Message\UriInterface' not found in /path/to/project/vendor/guzzlehttp/psr7/src/Uri.php:13
Stack trace:
#0 {main}


问:
How do I convert a JSON string to a function in javascript?
How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function.  However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

```<code>json = { "one": 700, "two": "function(e){alert(e);}" }
</code>```

Then in my code:

```<code>parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})
</code>```

答:
Looking for a way to not use eval this is the best I could come up with. Use the Function constructor to create a function from a string.

```<code>var parsed = JSON.parse('{"one":"700", "two":"function(){return 0;}" }');
var func = new Function('return ' + parsed.two)(); // return parsed.two function
alert(typeof func); // function
alert(func()) // 0
</code>```

Body:
How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function.  However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

json = { "one": 700, "two": "function(e){alert(e);}" }

Then in my code:

parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})

Body:
Looking for a way to not use eval this is the best I could come up with. Use the Function constructor to create a function from a string.

var parsed = JSON.parse('{"one":"700", "two":"function(){return 0;}" }');
var func = new Function('return ' + parsed.two)(); // return parsed.two function
alert(typeof func); // function
alert(func()) // 0


问:
Angular ng-disabled is not working in IE browser
I don't know why ng-disabled is not working in IE but it is wotking in chrome,firefox. Here i am checking condition if data is 0 i making button disabled.

HTML Code:

```<code><span ng-if="appDetails.buildsummary.buildcount<=0"><button class="disabled" disabled>0 builds</button></span>
</code>```

Please help me out.

Thanks in advance.

答:
Check if Internet Explorer is set to display intranet sites in compability mode. It can give all sorts of weird behaviour.
Hit the ALT-key and find it under Tools.</p>

Body:
I don't know why ng-disabled is not working in IE but it is wotking in chrome,firefox. Here i am checking condition if data is 0 i making button disabled.

HTML Code:

<span ng-if="appDetails.buildsummary.buildcount<=0"><button class="disabled" disabled>0 builds</button>

Please help me out.

Thanks in advance.


问:
Reactjs sliding animation sliding panel
I have a dripdrowns...once d last drop down is selected I'll be displaying some content, for that toggling I want to add some beautiful animations. Is there any react related things to implement this?</p>

答:
sidebarToggle(e) {
    e.preventDefault();
    document.body.classList.toggle('sidebar-hidden');
  }

  ☰```

You can do like this
It will show button and on clicking that button will toggle sidebar kind of animation from the left

Title: Reactjs sliding animation sliding panel

Body:
sidebarToggle(e) {
    e.preventDefault();
    document.body.classList.toggle('sidebar-hidden');
  }

  <a className="nav-link navbar-toggler sidebar-toggler" onClick={this.sidebarToggle} href="#">&#9776;</a>

You can do like this
It will show button and on clicking that button will toggle sidebar kind of animation from the left


问:
eclipse perspective messed up, reset not helping
I somehow messed up my perspective then I clicked reset perspective. This gives me back the package manager on the left. problems/javadoc/declarations on the bottom. Task list and outline as 2 separate windows on the right and a big empty space in the middle where the code is supposed to be. When I open up some code it ends up  in the bottom window and there's that big hole where the code window used to go. I can drag and drop the code into that empty space, but when I try to drag the code window bigger to fill up the entire space it won't let me past a certain point. I'm left with a gap above the coding window that's bothering me. It seems Eclipse is leaving that space for me to drag other perspectives into, however dragging more perspectives into that empty space doesn't make it go away, it's still the same size. How do I get rid of this space?</p>

答:
Close eclipse if it's open

Navigate to your workspace folder

Further navigate down into .metadata then .plugins (These are hidden files, use terminal or look up how to show hidden files in your OS)

Delete the org.eclipse.e4.workbench folder

Restart Eclipse

If it still doesn't look right click Window > New Window

If it still isn't fixed please let me know in the comments (it might be time to reinstall Eclipse)


问:
Android: What is the fastest way to load several bitmaps/thumbs via http?
I need to know : What is the fastest way to download several thumbs in a row, lets say 10 images. It seems like the built-in browser does this in a very clever way.

I have Google'd and found that most developers are using the HttpUrlConnection class to download a jpeg to display it in a ImageView, inside an ListAdapter etc.

Some developers implements the download by using DefaultHttpClient class as it has better support for timeouts etc. In fact Google recommends to use the Apache Http client, and not the native Java HttpUrlConnection. That said, both startegies mentioned works fine, but thay are very slow compared to how the build in browser on my HTC desire download thumbnails. The built in browser seems to download images about 5x-10x faster then when try to download the same bitmaps with my own code. And yes, I always do the download/http work on a separate worker thread (not GUI thread).

Do anybody know how the built-in browser is downloading thumbs, or at least what is the fastest way to download several images from a server ?

I have tried using this code:

```<code>DefaultHttpClient client = new DefaultHttpClient();
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, SO_TIMEOUT);
client.setParams(httpParameters);
client.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
    @Override
    public long getKeepAliveDuration(HttpResponse response, HttpContext context)
    {
        return 5000;
    }
});
</code>```

Now, i use this connection to fetch several bitmaps / thumbs in a for-loop:

```<code>public static Bitmap downloadBitmap(String url, DefaultHttpClient client){

  HttpResponse response = null;
  HttpGet get = new HttpGet(url);
  try {
      response = client.execute(get);
      return BitmapFactory.decodeStream(response.getEntity().getContent());
  }
  catch (ClientProtocolException e1) {
      e1.printStackTrace();
  }
  catch (IllegalStateException e){
      e.printStackTrace();
  }
  catch (IOException e1) {
      e1.printStackTrace();
  }

  return null;
}
</code>```

I created a testpage.html with 10 bitmaps and loaded it with the built-in browser. The browser renders the page with all the thumbs within 1 seconds. And I'm sure they are not cached in the browser, as i randomize the 10 images for every page-refresh.

When i try to make a simple activity that downloads and displays the same thumbs, its a lot slower.

I hope the Google Android Team picks up this and includes it in one of their video speaks on the next developer conference.

They should define a best-practise for this, as it seems that every developer tries to solve this "download-bitmap" use-case their own way, when we in fact are all trying to do the same thing.

I have also tested using the same DefaultHttpClient object to fetch several images by calling execute() with diffrent urls (HttpGet objects), but its still far from the speed to the built-in browser. I see that my requests has sat the connection keep-alive flag, but it does not seem to make any difference.

答: I'd use threads to download multiple images at once. This should help put your code on par with the browser.</p>

Body:
I need to know : What is the fastest way to download several thumbs in a row, lets say 10 images. It seems like the built-in browser does this in a very clever way.

I have Google'd and found that most developers are using the HttpUrlConnection class to download a jpeg to display it in a ImageView, inside an ListAdapter etc.

Some developers implements the download by using DefaultHttpClient class as it has better support for timeouts etc. In fact Google recommends to use the Apache Http client, and not the native Java HttpUrlConnection. That said, both startegies mentioned works fine, but thay are very slow compared to how the build in browser on my HTC desire download thumbnails. The built in browser seems to download images about 5x-10x faster then when try to download the same bitmaps with my own code. And yes, I always do the download/http work on a separate worker thread (not GUI thread).

Do anybody know how the built-in browser is downloading thumbs, or at least what is the fastest way to download several images from a server ?

I have tried using this code:

DefaultHttpClient client = new DefaultHttpClient();
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, SO_TIMEOUT);
client.setParams(httpParameters);
client.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
    @Override
    public long getKeepAliveDuration(HttpResponse response, HttpContext context)
    {
        return 5000;
    }
});

Now, i use this connection to fetch several bitmaps / thumbs in a for-loop:

public static Bitmap downloadBitmap(String url, DefaultHttpClient client){

  HttpResponse response = null;
  HttpGet get = new HttpGet(url);
  try {
      response = client.execute(get);
      return BitmapFactory.decodeStream(response.getEntity().getContent());
  }
  catch (ClientProtocolException e1) {
      e1.printStackTrace();
  }
  catch (IllegalStateException e){
      e.printStackTrace();
  }
  catch (IOException e1) {
      e1.printStackTrace();
  }

  return null;
}

I created a testpage.html with 10 bitmaps and loaded it with the built-in browser. The browser renders the page with all the thumbs within 1 seconds. And I'm sure they are not cached in the browser, as i randomize the 10 images for every page-refresh.

When i try to make a simple activity that downloads and displays the same thumbs, its a lot slower.

I hope the Google Android Team picks up this and includes it in one of their video speaks on the next developer conference.

They should define a best-practise for this, as it seems that every developer tries to solve this "download-bitmap" use-case their own way, when we in fact are all trying to do the same thing.

I have also tested using the same DefaultHttpClient object to fetch several images by calling execute() with diffrent urls (HttpGet objects), but its still far from the speed to the built-in browser. I see that my requests has sat the connection keep-alive flag, but it does not seem to make any difference.


问:
Preloading participant instances and issuing corresponding identities
What is a best practice or pattern that could be followed around the initial creation of participant instances and issuing corresponding identities for a deployed business network?  Is the expectation there will be some sort of bootstrapped config or transaction that will preload participants...or will that be the responsibility of an admin / regulator to do this AFTER the network is deployed...or something all together different???  The docs talk about an existing participant (https://hyperledger.github.io/composer/managing/participantsandidentities.html) but how did that existing participant get loaded into the network?</p>

答:
We are tracking this requirement using this issue:
https://github.com/hyperledger/composer/issues/670</p>


问:
How to get json object array from deep nested json array?
This is my json, I wanted to get 'products' arrays object.

```<code>{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }
</code>```

I am able to save categories in my db like this.

```<code>  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }
</code>```

Here is a Category Model class:

```<code>public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}
</code>```

I am using retrofit library to get data. Here is the method I am using to save categories array in my db.

```<code>@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}
</code>```

But how can I get product jsonArray from categories. Tried a lot but not able to find a method. Your help would be appreciated. Need to get products on the bases of categories. Kindly help. Thanks in advance.

Ashish I am using your method:

```<code> private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }
</code>```

答:
Step 1) Make your response with gson properties ..http://www.jsonschema2pojo.org/ will help to make gson class.

youSource type: JSON , Annotation style: GSON And add getter setter
  method.

Step 2) Now you have all the class with gson annotation.

Step 3) Now json

```<code> Gson gson = new GsonBuilder().create();
 JSONArray mainData = response.getJSONArray("Categories");
 ArrayList<YourMasterClass> responseAsArrayList =
                      gson.fromJson(mainData.toString(), new TypeToken<List<YourMasterClass>>() {
                    }.getType());
</code>```

Step 4) After getting all the data in arraylist now your logic will in play.

Here i have just write assume arraylist name so please replace your gson class.

```<code>for(int i =0;i<responseAsArrayList.size();i++)
{
      for(int j = 0; responseAsArrayList.get(i).getProductArray().size();j++)
      {
          // Here you will get your Product object
      }

}
</code>```

Body:
This is my json, I wanted to get 'products' arrays object.

{
       "Categories":[
          {
             "id":6,
             "status":"1",
             "parent_id":"0",
             "name":"Bottom Wear",
             "name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
             "picture":null,
             "description":"gents bottom wear",
             "slug":"bottom-wear",
             "created_at":"2017-06-05 21:08:28",
             "updated_at":"2017-06-05 21:08:28",
             "deleted_at":null,
             "product":[
                {
                   "id":2,
                   "status":"1",
                   "name":"Pants",
                   "name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
                   "dryclean_price":"9",
                   "washing_price":"6",
                   "press":"4",
                   "sw_dryclean_price":"9",
                   "sw_washing_price":"6",
                   "sw_press":"4",
                   "picture":null,
                   "created_at":"2017-04-19 21:32:04",
                   "updated_at":"2017-06-05 21:18:04",
                   "deleted_at":null,
                   "pivot":{
                      "category_id":"6",
                      "product_id":"2"
                   }
                },
                {
                   "id":8,
                   "status":"1",
                   "parent_id":"0",
                   "name":"Undergarments",
                   "name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
                   "picture":null,
                   "description":"Undergarments",
                   "slug":"undergarments",
                   "created_at":"2017-06-05 21:22:09",
                   "updated_at":"2017-06-05 21:22:09",
                   "deleted_at":null,
                   "product":[
                      {
                         "id":23,
                         "status":"1",
                         "name":"Underwear",
                         "name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-04-19 21:35:31",
                         "updated_at":"2017-06-05 21:23:42",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"23"
                         }
                      },
                      {
                         "id":34,
                         "status":"1",
                         "name":"Socks",
                         "name_ar":"\u062c\u0648\u0627\u0631\u0628",
                         "dryclean_price":"5",
                         "washing_price":"3",
                         "press":"2",
                         "sw_dryclean_price":"5",
                         "sw_washing_price":"3",
                         "sw_press":"2",
                         "picture":null,
                         "created_at":"2017-06-05 21:26:14",
                         "updated_at":"2017-06-05 21:26:14",
                         "deleted_at":null,
                         "pivot":{
                            "category_id":"8",
                            "product_id":"34"
                         }
                      }
                   ]
                }
             ]
          }
       ]
    }

I am able to save categories in my db like this.

  protected final String CategoryTable = "category_table";
    protected final String D_ID = "category_id";
    protected final String D_SERVER_ID = "categoryserver_id";
    protected final String D_JSON = "category_json";

 public boolean insertCategory(Category model) {
        ContentValues cv = new ContentValues();
        database = this.getWritableDatabase();
        cv.put(D_SERVER_ID, model.getId());
        cv.put(D_JSON, new Gson().toJson(model));
        int res = (int) database.insert(CategoryTable, null, cv);
        database.close();
        if (res > 0) {
            return true;
        } else {
            return false;
        }
    }

  public Collection<Category> getAllCategories() {
        database = this.getReadableDatabase();
        Gson gson = new Gson();
        ArrayList<Category> lst = new ArrayList<>();
        Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
        if (c.moveToFirst()) {
            do {
                Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
                if (obj != null)
                    lst.add(obj);
            } while (c.moveToNext());
        }
        return lst;
    }

Here is a Category Model class:

public class Category {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("parent_id")
    @Expose
    private String parentId;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("name_ar")
    @Expose
    private String nameAr;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("slug")
    @Expose
    private String slug;
    @SerializedName("created_at")
    @Expose
    private String createdAt;
    @SerializedName("updated_at")
    @Expose
    private String updatedAt;
    @SerializedName("deleted_at")
    @Expose
    private Object deletedAt;
    @SerializedName("product")
    @Expose
    private List<Product> product = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNameAr() {
        return nameAr;
    }

    public void setNameAr(String nameAr) {
        this.nameAr = nameAr;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getSlug() {
        return slug;
    }

    public void setSlug(String slug) {
        this.slug = slug;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public List<Product> getProduct() {
        return product;
    }

    public void setProduct(List<Product> product) {
        this.product = product;
    }

}

I am using retrofit library to get data. Here is the method I am using to save categories array in my db.

@Override
    public void onSuccess(Call call, Response response, int reqCode) {
        Loading.cancel();
        ProductsResponse productsResponse = (ProductsResponse) response.body();
        for (int i = 0; i < productsResponse.getCategories().size(); i++) {
            Category obj = productsResponse.getCategories().get(i);
            categories.add(obj);
            categoriesHandler.insertCategory(obj);
            categoriesHandler.insertLabel(obj.getName());
        }
        adapter.notifyDataSetChanged();
        loadSpinnerData();
}

But how can I get product jsonArray from categories. Tried a lot but not able to find a method. Your help would be appreciated. Need to get products on the bases of categories. Kindly help. Thanks in advance.

Ashish I am using your method:

 private void categorySelector(String str){
        Gson gson = new GsonBuilder().create();
        JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
        ArrayList<Category> responseAsArrayList =
                gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
                }.getType());
        for(int i =0;i<responseAsArrayList.size();i++)
        {
            for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
            {
                Category category =  responseAsArrayList.get(i);
                Product product = category.getProduct().get(j);
                products.add(product);
            }

        }

Body:
Step 1) Make your response with gson properties ..http://www.jsonschema2pojo.org/ will help to make gson class.

youSource type: JSON , Annotation style: GSON And add getter setter
  method.

Step 2) Now you have all the class with gson annotation.

Step 3) Now json

 Gson gson = new GsonBuilder().create();
 JSONArray mainData = response.getJSONArray("Categories");
 ArrayList<YourMasterClass> responseAsArrayList =
                      gson.fromJson(mainData.toString(), new TypeToken<List<YourMasterClass>>() {
                    }.getType());

Step 4) After getting all the data in arraylist now your logic will in play.

Here i have just write assume arraylist name so please replace your gson class.

for(int i =0;i<responseAsArrayList.size();i++)
{
      for(int j = 0; responseAsArrayList.get(i).getProductArray().size();j++)
      {
          // Here you will get your Product object
      }

}


问:
$_POST data is empty after submit
I'm having a contact form by html below:

```<code><form id="contactForm" action="http://voicemarketing.cmctelecom.vn/php/contact-form.php" method="POST">
<div class="row">
    <div class="form-group">
        <div class="col-md-6">
            <label>Your Name *</label>
            <input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>
        </div>
        <div class="col-md-6">
            <label>Your Company Name *</label>
            <input type="text" value="" data-msg-required="Please enter your company name." maxlength="100" class="form-control" name="companyname" id="companyname" required>
        </div>
    </div>
</div>
<div class="row">
    <div class="form-group">
        <div class="col-md-6">
            <label>Your phone number *</label>
            <input type="number" value="" data-msg-required="Please enter your phone number." maxlength="12" class="form-control" name="phonenumber" id="phonenumber" required>
        </div>
        <div class="col-md-6">
            <label>Your email address *</label>
            <input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>
        </div>
    </div>
</div>
<div class="row">
    <div class="form-group">
        <div class="col-md-12">
            <label>Message *</label>
            <textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message" required></textarea>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-md-12">
        <input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" data-loading-text="Loading...">
    </div>
</div>
</code>```

I tried to get the value by $_POST

```<code>$fields = array(
0 => array(
    'text' => 'Name',
    'val' => $_POST['name']
),
1 => array(
    'text' => 'Email address',
    'val' => $_POST['email']

),
2 => array(
    'text' => 'Message',
    'val' => $_POST['message']

),
3 => array(
    'text' => 'Company',
    'val' => $_POST['companyname']
),
4 => array(
    'text' => 'Phone Number',
    'val' => $_POST['phonenumber']
));
</code>```

Like usual, I put $_POST['name of form']
but only name, email, message are working
and companyname, phonenumber return nothing.
I really can't figure what is the problem is

答: Declare your POST variable first on top and make sure that the name attribute is same with the POST VARIABLES.</p>

Title: $_POST data is empty after submit

Body:
I'm having a contact form by html below:

<form id="contactForm" action="http://voicemarketing.cmctelecom.vn/php/contact-form.php" method="POST">

            Your Name *
            <input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name" required>

            Your Company Name *
            <input type="text" value="" data-msg-required="Please enter your company name." maxlength="100" class="form-control" name="companyname" id="companyname" required>

            Your phone number *
            <input type="number" value="" data-msg-required="Please enter your phone number." maxlength="12" class="form-control" name="phonenumber" id="phonenumber" required>

            Your email address *
            <input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email" required>

            Message *
            <textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message" required></textarea>

        <input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" data-loading-text="Loading...">

I tried to get the value by $_POST

$fields = array(
0 => array(
    'text' => 'Name',
    'val' => $_POST['name']
),
1 => array(
    'text' => 'Email address',
    'val' => $_POST['email']

),
2 => array(
    'text' => 'Message',
    'val' => $_POST['message']

),
3 => array(
    'text' => 'Company',
    'val' => $_POST['companyname']
),
4 => array(
    'text' => 'Phone Number',
    'val' => $_POST['phonenumber']
));

Like usual, I put $_POST['name of form']
but only name, email, message are working
and companyname, phonenumber return nothing.
I really can't figure what is the problem is


问:
SASS - Passing collection to sass mixin as an argument
How to pass collection to a sass mixin ?

```<code>=media($type1, $size1: null)
  @if ($type1) and ($size1)
    @media ($type1: $size1)
      @content
  @elseif ($type1) and not ($size1)
    $collection: $type1
    @media (nth($collection, 1): nth($collection, 2)) <-- ERROR
      @content
  @else
    @error "Upsss...."
</code>```

Use case

```<code>$m: "36em"
$minw: "min-width
$tablet: ("type1": $minw, "size1": $m)

+media($tablet) <-- ERROR
  p
    font-size: 2em
</code>```

答:
Sorted. I had to use #{map-get($collection, $key-name)} function </p>

```<code>=media($type1, $size1: null)
  @if ($type1) and ($size1)
    @media ($type1: $size1)
      @content
  @elseif ($type1) and not ($size1)
    $collection: $type1
    @media (#{map-get($collection, "type1")}: #{map-get($collection, "size1")})
      @content
  @else
    @error "Upsss...."
</code>```

Body:
How to pass collection to a sass mixin ?

=media($type1, $size1: null)
  @if ($type1) and ($size1)
    @media ($type1: $size1)
      @content
  @elseif ($type1) and not ($size1)
    $collection: $type1
    @media (nth($collection, 1): nth($collection, 2)) <-- ERROR
      @content
  @else
    @error "Upsss...."

Use case

$m: "36em"
$minw: "min-width
$tablet: ("type1": $minw, "size1": $m)

+media($tablet) <-- ERROR
  p
    font-size: 2em

Body:
Sorted. I had to use #{map-get($collection, $key-name)} function

=media($type1, $size1: null)
  @if ($type1) and ($size1)
    @media ($type1: $size1)
      @content
  @elseif ($type1) and not ($size1)
    $collection: $type1
    @media (#{map-get($collection, "type1")}: #{map-get($collection, "size1")})
      @content
  @else
    @error "Upsss...."


问:
How to reset counter (global variable) when one of the conditions changes
How to reset counter (global variable) when one of the conditions changes. Basically, increase the counter by 1 until "type_name" is "Bar" if it changes to something else set the counter to 0. How can this be achieved for multiple type_names'. Thank you.</p>

```<code>type_name = "bar"
counter = 0

class Foo(object):
    """
    if type is different in the argument, reset counter to 0.
    Otherwise, increment the counter by 1.
    """

    def __init__(self, type_name):
        self.type_name = type_name
        self.counter = counter
        self.reset()

    def increament_counter(self):
        self.counter +=1

    def reset(self):
        if self.type_name != type_name:
            self.counter = 0

b = Foo("bar")
b.increament_counter()
b.increament_counter()
print b.counter

print "==============================="
c = Foo("taste")
c.reset()
print c.counter
c.increament_counter()
print c.counter

print "--------------------------"
d = Foo("bar")
d.increament_counter()
d.increament_counter()
print d.counter

print "--------------------------"
e = Foo("car")
e.increament_counter()
e.increament_counter()
print e.counter
</code>```

答:
What you are doing here is that you're not modifying the global variable, but you're modifying the counter in the class (self.counter)

What you need to do is, in your reset function, change the global count, and not the one in that's a property of the class object.

```<code>def reset(self):
    global counter
    if self.type_name != type_name:
        counter = 0
</code>```

Body:
How to reset counter (global variable) when one of the conditions changes. Basically, increase the counter by 1 until "type_name" is "Bar" if it changes to something else set the counter to 0. How can this be achieved for multiple type_names'. Thank you.

type_name = "bar"
counter = 0

class Foo(object):
    """
    if type is different in the argument, reset counter to 0.
    Otherwise, increment the counter by 1.
    """

    def __init__(self, type_name):
        self.type_name = type_name
        self.counter = counter
        self.reset()

    def increament_counter(self):
        self.counter +=1

    def reset(self):
        if self.type_name != type_name:
            self.counter = 0

b = Foo("bar")
b.increament_counter()
b.increament_counter()
print b.counter

print "==============================="
c = Foo("taste")
c.reset()
print c.counter
c.increament_counter()
print c.counter

print "--------------------------"
d = Foo("bar")
d.increament_counter()
d.increament_counter()
print d.counter

print "--------------------------"
e = Foo("car")
e.increament_counter()
e.increament_counter()
print e.counter

Body:
What you are doing here is that you're not modifying the global variable, but you're modifying the counter in the class (self.counter)

What you need to do is, in your reset function, change the global count, and not the one in that's a property of the class object.

def reset(self):
    global counter
    if self.type_name != type_name:
        counter = 0


问:
optimize for loop in java
I am trying to print a square using for loop.
can the below code be improvised to print the square only using for loop instead of swing</p>

```<code>public class TestProgram {

    public static void main(String[] args) {

        TestProgram test = new TestProgram();
        test.draw(15, 4);
    }

    public void draw(int x, int y) {
        // System.out.println(".");
        System.out.println();
        int i = 0;
        int j = 0;
        for (i = 0; i < x; i++) {

            System.out.print(".");

            // continue;
        }
        for (j = x; j > y; j--) {

            System.out.println(".");
            System.out.print("\t\t");
            System.out.println(".");

        }

        for (int k = 0; k <= x; k++) {
            System.out.print(".");
        }

    }

}
</code>```

答:
How about:</p>

```<code>public class TestProgram {
    public static void main(String[] args) {
        TestProgram test = new TestProgram();
        test.draw(15, 4);
    }

    public void draw(int x, int y) {
        System.out.println(generateLine(x, '.'));
        for (int i = 1; i< y-1; i++) {
            System.out.println("." + generateLine(x-2, ' ') + ".");
        }
        System.out.println(generateLine(x, '.'));
    }

    private String generateLine(int x, char character) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < x; i++) {
            stringBuilder.append(character);
        }
        return stringBuilder.toString();
    }
}
</code>```

Title: optimize for loop in java

Body:
I am trying to print a square using for loop.
can the below code be improvised to print the square only using for loop instead of swing

public class TestProgram {

    public static void main(String[] args) {

        TestProgram test = new TestProgram();
        test.draw(15, 4);
    }

    public void draw(int x, int y) {
        // System.out.println(".");
        System.out.println();
        int i = 0;
        int j = 0;
        for (i = 0; i < x; i++) {

            System.out.print(".");

            // continue;
        }
        for (j = x; j > y; j--) {

            System.out.println(".");
            System.out.print("\t\t");
            System.out.println(".");

        }

        for (int k = 0; k <= x; k++) {
            System.out.print(".");
        }

    }

}

Body:
How about:

public class TestProgram {
    public static void main(String[] args) {
        TestProgram test = new TestProgram();
        test.draw(15, 4);
    }

    public void draw(int x, int y) {
        System.out.println(generateLine(x, '.'));
        for (int i = 1; i< y-1; i++) {
            System.out.println("." + generateLine(x-2, ' ') + ".");
        }
        System.out.println(generateLine(x, '.'));
    }

    private String generateLine(int x, char character) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < x; i++) {
            stringBuilder.append(character);
        }
        return stringBuilder.toString();
    }
}


问:
how to store values in Mongodb using mongoose in MeanStack
i am using angularjs db ismongodb with the help of mongoose .i create a simple entry form in mongoose schema but it's shows an  $http.post(...).success is not a function i don't know how to solve this anyone help how to solve this problem i am new in this technology

Html code

```<code><!DOCTYPE html>
<html ng-app="App">
<head>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>

    <script src="Controller/MongooseCrud.js"></script>
</head>

<body >

    <div ng-controller="MongooseController">

        <label for="email">Email: </label>
      <input type="email" name="email"  ng-model="user.email" /><br />
    <label for="name">Name: </label>
      <input type="text" name="name" ng-model="user.name" /><br />
    <label for="age">Age: </label>
      <input type="number" name="age" ng-model="user.age"/><br />
      <input type="Button"  value="submit" ng-click="AddNewDetails()">

    </div>

</body>
</html>
</code>```

Controller

```<code>var app = angular.module("App", [ ]);

app.controller('MongooseController', ['$scope', '$http' ,'$window', '$filter',

function ($scope, $http, $window, $filter) {

    $scope.AddNewDetails = function ( ) {

        $http.post('/AddNewDetails',  $scope.user).success(function (response) {

            console.log((response));
        }).error(function (err) {

        });
    };

}]);
</code>```

Server.js

```<code>var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema();
var bodyParser = require('body-parser');
var http = require('http');

app.use(express.static(__dirname + "/public"));

app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/crud');

var Schema = new mongoose.Schema({
    _id: String,
    name: String,
    age: Number
});

var user = mongoose.model('emp', Schema);

app.post('/AddNewDetails', function (req, res) {

    console.log(req.body);

    new user({
        email: req.body.email,
        name: req.body.name,
        age: req.body.age

    }).save(function (err, doc) {

        if (err) {
            res.json(err);
        }
        else {
            console.log(doc);
            res.send('Successfully inserted!');
        }
    });
});

app.listen(8082);
console.log("server running on port 8082");
</code>```

答:
Use service... In that you have to change the word post into create. It Will gives you the best result.

angular.module('yourApp').factory("yourService", function($http){

 return{
  create : function(insertData){
           return $http.post("http://localhost:yourHost/AddNewDetails/", insertData);
       }
});```

Body:
i am using angularjs db ismongodb with the help of mongoose .i create a simple entry form in mongoose schema but it's shows an  $http.post(...).success is not a function i don't know how to solve this anyone help how to solve this problem i am new in this technology

Html code

<!DOCTYPE html>

        Email:
      <input type="email" name="email"  ng-model="user.email" />

    Name:
      <input type="text" name="name" ng-model="user.name" />

    Age:
      <input type="number" name="age" ng-model="user.age"/>

      <input type="Button"  value="submit" ng-click="AddNewDetails()">

Controller

var app = angular.module("App", [ ]);

app.controller('MongooseController', ['$scope', '$http' ,'$window', '$filter',

function ($scope, $http, $window, $filter) {

    $scope.AddNewDetails = function ( ) {

        $http.post('/AddNewDetails',  $scope.user).success(function (response) {

            console.log((response));
        }).error(function (err) {

        });
    };

}]);

Server.js

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var Schema = mongoose.Schema();
var bodyParser = require('body-parser');
var http = require('http');

app.use(express.static(__dirname + "/public"));

app.use(bodyParser.json());
mongoose.connect('mongodb://localhost/crud');

var Schema = new mongoose.Schema({
    _id: String,
    name: String,
    age: Number
});

var user = mongoose.model('emp', Schema);

app.post('/AddNewDetails', function (req, res) {

    console.log(req.body);

    new user({
        email: req.body.email,
        name: req.body.name,
        age: req.body.age

    }).save(function (err, doc) {

        if (err) {
            res.json(err);
        }
        else {
            console.log(doc);
            res.send('Successfully inserted!');
        }
    });
});

app.listen(8082);
console.log("server running on port 8082");


问:
Best way of CSS override?
Could you please provide the best way of override and what is the advantages of this. For example.

1. example :

```<code>.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

.custom .ex1{
  font-size: 14px;
}
</code>```

2. example

```<code>.custom .ex1{
  font-size: 14px;
}
.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}
</code>```

Which is one best way overriding, example 1 or example 2. if any advantages?

答:
Suppose you have code like this -

.main-class{
      font-size:24px;
      color:red;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="main-class">Hi How are you?</p></code>```

Best way to override this CSS is to use a sub class which will override some properties of parent class like this -

.main-class{
      font-size:24px;
      color:red;
  }
.sub-class{
    font-size:14px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="main-class sub-class">Hi How are you?</p></code>```

Title: Best way of CSS override?

Body:
Could you please provide the best way of override and what is the advantages of this. For example.

1. example :

.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

.custom .ex1{
  font-size: 14px;
}

2. example

.custom .ex1{
  font-size: 14px;
}
.ex1{
  font-size: 12px;
  color: green;
  text-align: left;
}

Which is one best way overriding, example 1 or example 2. if any advantages?

Body:
Suppose you have code like this -

.main-class{
      font-size:24px;
      color:red;
  }

<p class="main-class">Hi How are you?</p>

Best way to override this CSS is to use a sub class which will override some properties of parent class like this -

.main-class{
      font-size:24px;
      color:red;
  }
.sub-class{
    font-size:14px;
 }

<p class="main-class sub-class">Hi How are you?</p>


问:
Is there a way to send email from Spotfire on a button click?
i am looking for an option to send email form a button click in spotfire text area using iron python

(or)

can we  implement same with the help of iron python and Automation Services.

(or)

Is there a way to get it done using R programming

```<code>import clr
clr.AddReference("Microsoft.Office.Interop.Outlook")
from System.Runtime.InteropServices import Marshal

mail= Marshal.GetActiveObject("Outlook.Application").CreateItem(0)
mail.Recipients.Add("abc@xyz.com")
mail.Subject = "subject here"
mail.Body = "Body here"
mail.Send();
</code>```

the above code is to send email , it is working fine within spotfire Client but not in web player.please help me out

答:
You can use the mailR package to trigger emails.This is what worked for me-</p>

```<code>sender <- "sender@gmail.com"
recipient<- "receiver1@gmail.com"
email <- send.mail(from = sender,to = recipients,subject="R-email",body =
"Body of the email",smtp = list(host.name = "smtp.gmail.com",
user.name="myuser@gmail.com",passwd="password",port=587,ssl=TRUE),authenticate
= TRUE,send = FALSE)
email$send()
</code>```

Body:
i am looking for an option to send email form a button click in spotfire text area using iron python

(or)

can we  implement same with the help of iron python and Automation Services.

(or)

Is there a way to get it done using R programming

import clr
clr.AddReference("Microsoft.Office.Interop.Outlook")
from System.Runtime.InteropServices import Marshal

mail= Marshal.GetActiveObject("Outlook.Application").CreateItem(0)
mail.Recipients.Add("abc@xyz.com")
mail.Subject = "subject here"
mail.Body = "Body here"
mail.Send();

the above code is to send email , it is working fine within spotfire Client but not in web player.please help me out

Body:
You can use the mailR package to trigger emails.This is what worked for me-

sender <- "sender@gmail.com"
recipient<- "receiver1@gmail.com"
email <- send.mail(from = sender,to = recipients,subject="R-email",body =
"Body of the email",smtp = list(host.name = "smtp.gmail.com",
user.name="myuser@gmail.com",passwd="password",port=587,ssl=TRUE),authenticate
= TRUE,send = FALSE)
email$send()