问:
Insert IGNORE with a multiple value entry statement; What happens on duplicate?
```<code>insert ignore into table (a,b) values (1,1),(1,2),(2,1),(2,2);
</code>```

if a is pk or is a unique key, can I can reliably count on all statements NOT violating pk or unique constraint to be entered - even if they are AFTER the "violating" entry? i.e.: Do the non-duplicates get inserted and only the duplicates get "ignored" - no matter where they fall within the sql statement?

答:
I did more research and found this answer to another StackOverflow question:

...and now some multiple row tests

Thanks to Paulus Maximus

Body:
insert ignore into table (a,b) values (1,1),(1,2),(2,1),(2,2);

if a is pk or is a unique key, can I can reliably count on all statements NOT violating pk or unique constraint to be entered - even if they are AFTER the "violating" entry? i.e.: Do the non-duplicates get inserted and only the duplicates get "ignored" - no matter where they fall within the sql statement?


来源: stackexchange

问:
Puzzle 8 Resolver in Python - I can't pass all tests
I have to do a 8 puzzle resolver with bfs, dfs and A* algorithms in python, but I have some issue(s). I can't pass all tests. Anyone can help me?

EDIT: I edited my code for working with a 1D array. It's work for:

```<code>python driver_3.py bfs 3,1,2,0,4,5,6,7,8
python driver_3.py bfs 1,2,5,3,4,0,6,7,8
</code>```

but with python driver_3.py bfs 6,1,8,4,0,2,7,3,5 seems doesn't find a solution. It runs for several minutes without finding a solution.

This is my code:

driver_3.py

```<code>import sys
from EightPuzzle import EightPuzzle as g

if __name__ == "__main__":
    method = sys.argv[1]
    board = list(map(int,sys.argv[2].split(',')))
    print("Start: ", board)
    game = g(board)

    if (method == 'bfs') | (method == 'dfs') | (method == 'ast') :
        game.resolve(alg=method)
    else:
        print('Method not allowed.')
</code>```

EightPuzzle.py

```<code>from Graph import Graph as Graph
from Node import Node
import time

class EightPuzzle(object):
    def __init__(self, initialState):
        self.graph = Graph(Node(initialState))
        self.actions = ['Up','Down', 'Left', 'Right']
        self.goal = [0,1,2,3,4,5,6,7,8]
        self.start_time = time.time()
        self.end_time = 0
        self.diff_time = 0
        self.ram = 0

    def get_graph(self):
        return self.graph

    def set_graph(self, other):
        self.graph = other

    def get_actions(self):
        return self.actions

    def set_actions(self, other):
        self.actions = other

    def get_goal(self):
        return self.goal

    def set_goal(self, other):
        self.goal = other

    def get_start_time(self):
        return self.start_time

    def set_start_time(self, other):
        self.ram = other

    def get_end_time(self):
        return self.end_time

    def set_end_time(self, other):
        self.end_time = other

    def set_diff_time(self):
        self.diff_time = self.end_time - self.start_time
        return None

    def get_diff_time(self):
        return self.diff_time

    def set_ram_usage(self):
        import sys
        if sys.platform == "win32":
            import psutil
            self.ram = psutil.Process().memory_info().rss
        else:
            # import resource
            # self.ram = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
            return False

    def get_ram(self):
        return self.ram

    def set_ram(self, other):
        self.ram = other

    def find_zero(self, node_state):
        return node_state.index(0)

    def move_up(self, node_state, zero):
        up = node_state[:]
        val = up[zero-3]
        up[zero-3] = 0
        up[zero] = val
        return up

    def move_down(self, node_state, zero):
        down = node_state[:]
        val = down[zero+3]
        down[zero+3] = 0
        down[zero] = val
        return down

    def move_left(self, node_state, zero):
        left = node_state[:]
        val = left[zero-1]
        left[zero-1] = 0
        left[zero] = val
        return left

    def move_right(self, node_state, zero):
        right = node_state[:]
        val = right[zero+1]
        right[zero+1] = 0
        right[zero] = val
        return right

    def find_neighbors(self, node):
        node_state = node.get_state()
        print("Node: ", node_state)
        zero = self.find_zero(node_state)
        neighbors = []
        if zero > 2:
            neighbors.append(Node(self.move_up(node_state, zero), parent=node, action="Up"))
        if zero < 6:
            neighbors.append(Node(self.move_down(node_state,zero), parent=node, action="Down"))
        if (zero != 0) & (zero != 3) & (zero != 6):
            neighbors.append(Node(self.move_left(node_state,zero), parent=node, action="Left"))
        if (zero != 2) & (zero != 5) & (zero != 8):
            neighbors.append(Node(self.move_right(node_state,zero), parent=node, action="Right"))

        return neighbors

    def success(self):
        self.end_time = time.time()
        self.set_diff_time()
        self.set_ram_usage()
        #self.output()
        return "Success"

    def bfs(self, goal):
        print("bfs")
        graph = self.get_graph()
        while len(graph.get_frontiers()) != 0:
            current_node = graph.frontiers.shift()
            graph.explored.append(current_node)

            if (current_node == goal):
                print("Explored ", str(len(graph.get_explored())-1))
                print("Solution found!: ", current_node)
                return "Done"

            neighbors = self.find_neighbors(current_node)
            current_node.set_neighbors(neighbors)

            for neighbor in neighbors:
                if (neighbor not in graph.get_frontiers()) & (neighbor not in graph.get_explored()):
                    graph.frontiers.append(neighbor)
        print("Solution Not Found")

    def dfs(self, goal):
        print("dfs")
        graph = self.get_graph()
        while len(graph.get_frontiers()) != 0:
            current_node = graph.frontiers.pop()
            graph.explored.append(current_node)

            if (current_node == goal):
                print("Explored ", str(len(graph.get_explored())-1))
                print("Solution found!: ", current_node)
                return "Done"

            neighbors = self.find_neighbors(current_node)
            current_node.set_neighbors(neighbors)

            for neighbor in neighbors:
                if (neighbor not in graph.get_frontiers()) & (neighbor not in graph.get_explored()):
                    graph.frontiers.prepend(neighbor)
        print("Solution Not Found")

    def ast(self, goal):
        print("ast")
        # TO DO
        print("Solution Not Found")

    # def output(self):
    #     with open("output.txt", "w") as f:
    #         f.write("path_to_goal: ", str(self.path))
    #         f.write("cost_of_path: ", str(len(self.cost_of_path)))
    #         f.write("node_expanded: ", str(len(self.explored)))
    #         f.write("max_search_depth: ", str(self.max_depth))
    #         f.write("running_time: ", str(self.diff_time))
    #         f.write("max_ram_usage: ", str(self.ram))
    #     f.closed
    #     return "Output Done"

    def resolve(self, alg):
        if alg == 'bfs':
            self.bfs(self.goal)
        elif alg == 'dfs':
            self.dfs(self.goal)
        elif alg == 'ast':
            self.ast(self.goal)
        return None
</code>```

Node.py

```<code>class Node(object):
    def __init__(self, state, parent=None, action="Root", path_cost=0):
        self.state = state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost
        self.depth = 0
        self.neighbors = []
        if parent:
            self.depth = parent.depth + 1
            self.path_cost = parent.path_cost + 1

    def __eq__(self,other):
        return self.state == other

    def __str__(self):
        return str(self.state)

    def __repr__(self):
        return str(self.state)

    def get_state(self):
        return self.state

    def set_state(self, new_state):
        self.state = new_state

    def get_parent(self):
        return self.parent

    def set_parent(self, new_parent):
        self.parent = new_parent

    def get_action(self):
        return self.action

    def set_action(self, other_action):
        self.action = other_action

    def get_path_cost(self):
        return self.path_cost

    def set_path_cost(self, other_path):
        self.path_cost = other_path

    def get_depth(self):
        return self.depth

    def set_depth(self, other_depth):
        self.depth = other_depth

    def get_neighbors(self):
        return self.neighbors

    def set_neighbors(self, other_neighbors):
        self.neighbors = other_neighbors
</code>```

Graph.py

```<code>from Frontiers import Frontiers

class Graph:
    def __init__(self, initialState):
        self.frontiers = Frontiers(initialState)
        self.explored = []
        self.path = []
        self.max_depth = 0
        self.cost_of_path = 0

    def get_frontiers(self):
        return self.frontiers

    def set_frontiers(self, other):
        self.frontiers = other

    def get_explored(self):
        return self.explored

    def set_explored(self, other):
        self.explored = other

    def get_path(self):
        return self.path

    def set_path(self, other):
        self.path = other

    def get_max_depth(self):
        return self.max_depth

    def set_max_depth(self, other):
        self.max_depth = other

    def get_cost_of_path(self):
        return self.cost_of_path

    def set_cost_of_path(self, other):
        self.cost_of_path = other
</code>```

Frontiers.py

```<code>class Frontiers(list):
    def __init__(self, initialState):
        self.state = [initialState]

    def __len__(self):
        return len(self.state)

    def __contains__(self,other):
          return True if other in self.state else False

    def __str__(self):
        return str(self.state)

    def __repr__(self):
        return str(self.state)

    def set_state(self,new_state):
        self.state = new_state

    def get_state(self):
        return self.state

    def append(self, other):
        #append element at the end of the frontiers
        self.set_state(self.get_state() + [other])

    def prepend(self, other):
        #append element at the beginning of the frontiers
        self.set_state([other] + self.get_state())

    def shift(self):
        #return first element of frontier state
        first = self.get_state()[0]
        if(len(self.get_state()) > 1):
            self.set_state(self.get_state()[1:])
        else:
            self.set_state([])
        return first

    def pop(self):
        #return last element of frontier state
        last = self.get_state()[-1]
        if(len(self.get_state()) > 1):
            self.set_state(self.get_state()[:-1])
        else:
            self.set_state([])
        return last
</code>```

答:
up = node_state[:]

This only copies the references to the lists in node_state.

> a = [[1,2],[3,4]]

> b = a[:]

>b

[[1, 2], [3, 4]]

> b[0][0] = 0

>a

[[0, 2], [3, 4]]

Here, changing one value in the inner list of b changes the corresponding value in a as well.

Instead do this: up = [list(row) for row in node_state]

> a = [[1,2],[3,4]]

> b = [list(r) for r in a]

>b

[[1, 2], [3, 4]]

> b[0][0] = 0

>a

[[1, 2], [3, 4]]

ContentLicense: CC BY-SA 3.0

Body:
I have to do a 8 puzzle resolver with bfs, dfs and A* algorithms in python, but I have some issue(s). I can't pass all tests. Anyone can help me?

EDIT: I edited my code for working with a 1D array. It's work for:

python driver_3.py bfs 3,1,2,0,4,5,6,7,8
python driver_3.py bfs 1,2,5,3,4,0,6,7,8

but with python driver_3.py bfs 6,1,8,4,0,2,7,3,5 seems doesn't find a solution. It runs for several minutes without finding a solution.

This is my code:

driver_3.py

import sys
from EightPuzzle import EightPuzzle as g

if __name__ == "__main__":
    method = sys.argv[1]
    board = list(map(int,sys.argv[2].split(',')))
    print("Start: ", board)
    game = g(board)

    if (method == 'bfs') | (method == 'dfs') | (method == 'ast') :
        game.resolve(alg=method)
    else:
        print('Method not allowed.')

EightPuzzle.py

from Graph import Graph as Graph
from Node import Node
import time

class EightPuzzle(object):
    def __init__(self, initialState):
        self.graph = Graph(Node(initialState))
        self.actions = ['Up','Down', 'Left', 'Right']
        self.goal = [0,1,2,3,4,5,6,7,8]
        self.start_time = time.time()
        self.end_time = 0
        self.diff_time = 0
        self.ram = 0

    def get_graph(self):
        return self.graph

    def set_graph(self, other):
        self.graph = other

    def get_actions(self):
        return self.actions

    def set_actions(self, other):
        self.actions = other

    def get_goal(self):
        return self.goal

    def set_goal(self, other):
        self.goal = other

    def get_start_time(self):
        return self.start_time

    def set_start_time(self, other):
        self.ram = other

    def get_end_time(self):
        return self.end_time

    def set_end_time(self, other):
        self.end_time = other

    def set_diff_time(self):
        self.diff_time = self.end_time - self.start_time
        return None

    def get_diff_time(self):
        return self.diff_time

    def set_ram_usage(self):
        import sys
        if sys.platform == "win32":
            import psutil
            self.ram = psutil.Process().memory_info().rss
        else:
            # import resource
            # self.ram = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
            return False

    def get_ram(self):
        return self.ram

    def set_ram(self, other):
        self.ram = other

    def find_zero(self, node_state):
        return node_state.index(0)

    def move_up(self, node_state, zero):
        up = node_state[:]
        val = up[zero-3]
        up[zero-3] = 0
        up[zero] = val
        return up

    def move_down(self, node_state, zero):
        down = node_state[:]
        val = down[zero+3]
        down[zero+3] = 0
        down[zero] = val
        return down

    def move_left(self, node_state, zero):
        left = node_state[:]
        val = left[zero-1]
        left[zero-1] = 0
        left[zero] = val
        return left

    def move_right(self, node_state, zero):
        right = node_state[:]
        val = right[zero+1]
        right[zero+1] = 0
        right[zero] = val
        return right

    def find_neighbors(self, node):
        node_state = node.get_state()
        print("Node: ", node_state)
        zero = self.find_zero(node_state)
        neighbors = []
        if zero > 2:
            neighbors.append(Node(self.move_up(node_state, zero), parent=node, action="Up"))
        if zero < 6:
            neighbors.append(Node(self.move_down(node_state,zero), parent=node, action="Down"))
        if (zero != 0) & (zero != 3) & (zero != 6):
            neighbors.append(Node(self.move_left(node_state,zero), parent=node, action="Left"))
        if (zero != 2) & (zero != 5) & (zero != 8):
            neighbors.append(Node(self.move_right(node_state,zero), parent=node, action="Right"))

        return neighbors

    def success(self):
        self.end_time = time.time()
        self.set_diff_time()
        self.set_ram_usage()
        #self.output()
        return "Success"

    def bfs(self, goal):
        print("bfs")
        graph = self.get_graph()
        while len(graph.get_frontiers()) != 0:
            current_node = graph.frontiers.shift()
            graph.explored.append(current_node)

            if (current_node == goal):
                print("Explored ", str(len(graph.get_explored())-1))
                print("Solution found!: ", current_node)
                return "Done"

            neighbors = self.find_neighbors(current_node)
            current_node.set_neighbors(neighbors)

            for neighbor in neighbors:
                if (neighbor not in graph.get_frontiers()) & (neighbor not in graph.get_explored()):
                    graph.frontiers.append(neighbor)
        print("Solution Not Found")

    def dfs(self, goal):
        print("dfs")
        graph = self.get_graph()
        while len(graph.get_frontiers()) != 0:
            current_node = graph.frontiers.pop()
            graph.explored.append(current_node)

            if (current_node == goal):
                print("Explored ", str(len(graph.get_explored())-1))
                print("Solution found!: ", current_node)
                return "Done"

            neighbors = self.find_neighbors(current_node)
            current_node.set_neighbors(neighbors)

            for neighbor in neighbors:
                if (neighbor not in graph.get_frontiers()) & (neighbor not in graph.get_explored()):
                    graph.frontiers.prepend(neighbor)
        print("Solution Not Found")

    def ast(self, goal):
        print("ast")
        # TO DO
        print("Solution Not Found")

    # def output(self):
    #     with open("output.txt", "w") as f:
    #         f.write("path_to_goal: ", str(self.path))
    #         f.write("cost_of_path: ", str(len(self.cost_of_path)))
    #         f.write("node_expanded: ", str(len(self.explored)))
    #         f.write("max_search_depth: ", str(self.max_depth))
    #         f.write("running_time: ", str(self.diff_time))
    #         f.write("max_ram_usage: ", str(self.ram))
    #     f.closed
    #     return "Output Done"

    def resolve(self, alg):
        if alg == 'bfs':
            self.bfs(self.goal)
        elif alg == 'dfs':
            self.dfs(self.goal)
        elif alg == 'ast':
            self.ast(self.goal)
        return None

Node.py

class Node(object):
    def __init__(self, state, parent=None, action="Root", path_cost=0):
        self.state = state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost
        self.depth = 0
        self.neighbors = []
        if parent:
            self.depth = parent.depth + 1
            self.path_cost = parent.path_cost + 1

    def __eq__(self,other):
        return self.state == other

    def __str__(self):
        return str(self.state)

    def __repr__(self):
        return str(self.state)

    def get_state(self):
        return self.state

    def set_state(self, new_state):
        self.state = new_state

    def get_parent(self):
        return self.parent

    def set_parent(self, new_parent):
        self.parent = new_parent

    def get_action(self):
        return self.action

    def set_action(self, other_action):
        self.action = other_action

    def get_path_cost(self):
        return self.path_cost

    def set_path_cost(self, other_path):
        self.path_cost = other_path

    def get_depth(self):
        return self.depth

    def set_depth(self, other_depth):
        self.depth = other_depth

    def get_neighbors(self):
        return self.neighbors

    def set_neighbors(self, other_neighbors):
        self.neighbors = other_neighbors

Graph.py

from Frontiers import Frontiers

class Graph:
    def __init__(self, initialState):
        self.frontiers = Frontiers(initialState)
        self.explored = []
        self.path = []
        self.max_depth = 0
        self.cost_of_path = 0

    def get_frontiers(self):
        return self.frontiers

    def set_frontiers(self, other):
        self.frontiers = other

    def get_explored(self):
        return self.explored

    def set_explored(self, other):
        self.explored = other

    def get_path(self):
        return self.path

    def set_path(self, other):
        self.path = other

    def get_max_depth(self):
        return self.max_depth

    def set_max_depth(self, other):
        self.max_depth = other

    def get_cost_of_path(self):
        return self.cost_of_path

    def set_cost_of_path(self, other):
        self.cost_of_path = other

Frontiers.py

class Frontiers(list):
    def __init__(self, initialState):
        self.state = [initialState]

    def __len__(self):
        return len(self.state)

    def __contains__(self,other):
          return True if other in self.state else False

    def __str__(self):
        return str(self.state)

    def __repr__(self):
        return str(self.state)

    def set_state(self,new_state):
        self.state = new_state

    def get_state(self):
        return self.state

    def append(self, other):
        #append element at the end of the frontiers
        self.set_state(self.get_state() + [other])

    def prepend(self, other):
        #append element at the beginning of the frontiers
        self.set_state([other] + self.get_state())

    def shift(self):
        #return first element of frontier state
        first = self.get_state()[0]
        if(len(self.get_state()) > 1):
            self.set_state(self.get_state()[1:])
        else:
            self.set_state([])
        return first

    def pop(self):
        #return last element of frontier state
        last = self.get_state()[-1]
        if(len(self.get_state()) > 1):
            self.set_state(self.get_state()[:-1])
        else:
            self.set_state([])
        return last


问:
Unhandled promise rejection in node.js while using mongooseSchema.pre('save') method
```<code>//This is the user model
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const userSchema = mongoose.Schema({
  email: {
    type: String,
    index: {
      unique: true
    }
  },
  password: {
    type: String
  }
});

userSchema.pre("save", function(next) {
  var user = this;
  if (!user.isModified("password")) {
    return next();
  }

  bcrypt.genSalt(saltRounds, function(err, salt) {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, salt, function(err, hashedPassword) {
      if (err) {
        return next(err)
      }
      user.password = hashedPassword;
      next();
    });
  });
});

userSchema.methods.checkPassword = function(guess, cb) {
  bcrypt.compare(guess, this.password, function(err, isMatch) {
    cb(err, isMatch);
  });
};
const User = mongoose.model('User', userSchema);
module.exports = User;

//The code below  is the /signup route
router.post('/signup', (req, res) => {
  User.findOne({
    email: req.body.email
  }, (err, user) => {
    if (err) {
      throw err;
    }

    if (user) {
      // handle case for user already exists!!
      res.json({
        success: false,
        message: 'An account with this email already exists'
      });
    } else {
      var newUser = new User({
        email: req.body.email,
        password: req.body.password
      });

      newUser.save((err) => {
        if (err) {
          return res.send(err);
        }
        let jwtData = {
          email: req.body.email
        };

        let token = jwt.sign(jwtData, jwtSecret);

        res.json({
          success: true,
          token: token
        });
      });
    }
  });
});
</code>```

when I make a post request to /signup route I got this error in nodejs version 8.1.2:

(node:8317) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: cb must be a function or
null to return a Promise

The route works fine if I remove the mongoose pre method.
But I want to hash the passwords.Please help me on this issue.Thanks

答:
Your pre-save callback takes a function called 'done' but you are calling 'next' instead.

It should be:

```<code>userSchema.pre("save", function(next) {
    ...
}
</code>```

Body:
//This is the user model
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const userSchema = mongoose.Schema({
  email: {
    type: String,
    index: {
      unique: true
    }
  },
  password: {
    type: String
  }
});

userSchema.pre("save", function(next) {
  var user = this;
  if (!user.isModified("password")) {
    return next();
  }

  bcrypt.genSalt(saltRounds, function(err, salt) {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, salt, function(err, hashedPassword) {
      if (err) {
        return next(err)
      }
      user.password = hashedPassword;
      next();
    });
  });
});

userSchema.methods.checkPassword = function(guess, cb) {
  bcrypt.compare(guess, this.password, function(err, isMatch) {
    cb(err, isMatch);
  });
};
const User = mongoose.model('User', userSchema);
module.exports = User;

//The code below  is the /signup route
router.post('/signup', (req, res) => {
  User.findOne({
    email: req.body.email
  }, (err, user) => {
    if (err) {
      throw err;
    }

    if (user) {
      // handle case for user already exists!!
      res.json({
        success: false,
        message: 'An account with this email already exists'
      });
    } else {
      var newUser = new User({
        email: req.body.email,
        password: req.body.password
      });

      newUser.save((err) => {
        if (err) {
          return res.send(err);
        }
        let jwtData = {
          email: req.body.email
        };

        let token = jwt.sign(jwtData, jwtSecret);

        res.json({
          success: true,
          token: token
        });
      });
    }
  });
});

when I make a post request to /signup route I got this error in nodejs version 8.1.2:

(node:8317) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: cb must be a function or
null to return a Promise

The route works fine if I remove the mongoose pre method.
But I want to hash the passwords.Please help me on this issue.Thanks

Body:
Your pre-save callback takes a function called 'done' but you are calling 'next' instead.

It should be:

userSchema.pre("save", function(next) {
    ...
}


问:
Is there a typical state machine implementation pattern?
We need to implement a simple state machine in C.

Is a standard switch statement the best way to go?

We have a current state (state) and a trigger for the transition.

```<code>
switch(state)
{
  case STATE_1:
     state = DoState1(transition);
     break;
  case STATE_2:
     state = DoState2(transition);
     break;
}
...
DoState2(int transition)
{
   // Do State Work
   ...
   if(transition == FROM_STATE_2) {
     // New state when doing STATE 2 -> STATE 2
   }
   if(transition == FROM_STATE_1) {
    // New State when moving STATE 1 -> STATE 2
   }
   return new_state;
}
</code>```

Is there a better way for simple state machines

EDIT:
  For C++, I think the Boost Statechart library might be the way to go.  However, it does not help with C.  Lets concentrate on the C use case.

答:
In Martin Fowler's UML Distilled, he states (no pun intended) in Chapter 10 State Machine Diagrams (emphasis mine):

A state diagram can be implemented in three main ways: nested switch, the State pattern, and
  state tables.

Let's use a simplified example of the states of a mobile phone's display:

Nested switch

Fowler gave an example of C# code, but I've adapted it to my example.

```<code>public void HandleEvent(PhoneEvent anEvent) {
    switch (CurrentState) {
    case PhoneState.ScreenOff:
        switch (anEvent) {
        case PhoneEvent.PressButton:
            if (powerLow) { // guard condition
                DisplayLowPowerMessage(); // action
                // CurrentState = PhoneState.ScreenOff;
            } else {
                CurrentState = PhoneState.ScreenOn;
            }
            break;
        case PhoneEvent.PlugPower:
            CurrentState = PhoneState.ScreenCharging;
            break;
        }
        break;
    case PhoneState.ScreenOn:
        switch (anEvent) {
        case PhoneEvent.PressButton:
            CurrentState = PhoneState.ScreenOff;
            break;
        case PhoneEvent.PlugPower:
            CurrentState = PhoneState.ScreenCharging;
            break;
        }
        break;
    case PhoneState.ScreenCharging:
        switch (anEvent) {
        case PhoneEvent.UnplugPower:
            CurrentState = PhoneState.ScreenOff;
            break;
        }
        break;
    }
}
</code>```

State pattern

Here's an implementation of my example with the GoF State pattern:

State Tables

Taking inspiration from Fowler, here's a table for my example:

```
Source State    Target State    Event         Guard        Action
--------------------------------------------------------------------------------------
ScreenOff       ScreenOff       pressButton   powerLow     displayLowPowerMessage
ScreenOff       ScreenOn        pressButton   !powerLow
ScreenOn        ScreenOff       pressButton
ScreenOff       ScreenCharging  plugPower
ScreenOn        ScreenCharging  plugPower
ScreenCharging  ScreenOff       unplugPower
```

Comparison

Nested switch keeps all the logic in one spot, but the code can be hard to read when there are a lot of states and transitions. It's possibly more secure and easier to validate than the other approaches (no polymorphism or interpreting).

The State pattern implementation potentially spreads the logic over several separate classes, which may make understanding it as a whole a problem. On the other hand, the small classes are easy to understand separately. The design is particularly fragile if you change the behavior by adding or removing transitions, as they're methods in the hierarchy and there could be lots of changes to the code. If you live by the design principle of small interfaces, you'll see this pattern doesn't really do so well. However, if the state machine is stable, then such changes won't be needed.

The state tables approach requires writing some kind of interpreter for the content (this might be easier if you have reflection in the language you're using), which could be a lot of work to do up front. As Fowler points out, if your table is separate from your code, you could modify the behavior of your software without recompiling. This has some security implications, however; the software is behaving based on the contents of an external file.

Edit (not really for C language)

There is a fluent interface (aka internal Domain Specific Language) approach, too, which is probably facilitated by languages that have first-class functions. The Stateless library exists and that blog shows a simple example with code. A Java implementation (pre Java8) is discussed. I was shown a Python example on GitHub as well.

OwnerDisplayName: Benoit

ContentLicense: CC BY-SA 2.5

Body:
We need to implement a simple state machine in C.

Is a standard switch statement the best way to go?

We have a current state (state) and a trigger for the transition.

switch(state)
{
  case STATE_1:
     state = DoState1(transition);
     break;
  case STATE_2:
     state = DoState2(transition);
     break;
}
...
DoState2(int transition)
{
   // Do State Work
   ...
   if(transition == FROM_STATE_2) {
     // New state when doing STATE 2 -> STATE 2
   }
   if(transition == FROM_STATE_1) {
    // New State when moving STATE 1 -> STATE 2
   }
   return new_state;
}

Is there a better way for simple state machines

EDIT:
  For C++, I think the Boost Statechart library might be the way to go.  However, it does not help with C.  Lets concentrate on the C use case.

LastEditorDisplayName: Benoit

Body:
In Martin Fowler's UML Distilled, he states (no pun intended) in Chapter 10 State Machine Diagrams (emphasis mine):

A state diagram can be implemented in three main ways: nested switch, the State pattern, and
  state tables.

Let's use a simplified example of the states of a mobile phone's display:

Nested switch

Fowler gave an example of C# code, but I've adapted it to my example.

public void HandleEvent(PhoneEvent anEvent) {
    switch (CurrentState) {
    case PhoneState.ScreenOff:
        switch (anEvent) {
        case PhoneEvent.PressButton:
            if (powerLow) { // guard condition
                DisplayLowPowerMessage(); // action
                // CurrentState = PhoneState.ScreenOff;
            } else {
                CurrentState = PhoneState.ScreenOn;
            }
            break;
        case PhoneEvent.PlugPower:
            CurrentState = PhoneState.ScreenCharging;
            break;
        }
        break;
    case PhoneState.ScreenOn:
        switch (anEvent) {
        case PhoneEvent.PressButton:
            CurrentState = PhoneState.ScreenOff;
            break;
        case PhoneEvent.PlugPower:
            CurrentState = PhoneState.ScreenCharging;
            break;
        }
        break;
    case PhoneState.ScreenCharging:
        switch (anEvent) {
        case PhoneEvent.UnplugPower:
            CurrentState = PhoneState.ScreenOff;
            break;
        }
        break;
    }
}

State pattern

Here's an implementation of my example with the GoF State pattern:

State Tables

Taking inspiration from Fowler, here's a table for my example:

Source State    Target State    Event         Guard        Action
--------------------------------------------------------------------------------------
ScreenOff       ScreenOff       pressButton   powerLow     displayLowPowerMessage
ScreenOff       ScreenOn        pressButton   !powerLow
ScreenOn        ScreenOff       pressButton
ScreenOff       ScreenCharging  plugPower
ScreenOn        ScreenCharging  plugPower
ScreenCharging  ScreenOff       unplugPower

Comparison

Nested switch keeps all the logic in one spot, but the code can be hard to read when there are a lot of states and transitions. It's possibly more secure and easier to validate than the other approaches (no polymorphism or interpreting).

The State pattern implementation potentially spreads the logic over several separate classes, which may make understanding it as a whole a problem. On the other hand, the small classes are easy to understand separately. The design is particularly fragile if you change the behavior by adding or removing transitions, as they're methods in the hierarchy and there could be lots of changes to the code. If you live by the design principle of small interfaces, you'll see this pattern doesn't really do so well. However, if the state machine is stable, then such changes won't be needed.

The state tables approach requires writing some kind of interpreter for the content (this might be easier if you have reflection in the language you're using), which could be a lot of work to do up front. As Fowler points out, if your table is separate from your code, you could modify the behavior of your software without recompiling. This has some security implications, however; the software is behaving based on the contents of an external file.

Edit (not really for C language)

There is a fluent interface (aka internal Domain Specific Language) approach, too, which is probably facilitated by languages that have first-class functions. The Stateless library exists and that blog shows a simple example with code. A Java implementation (pre Java8) is discussed. I was shown a Python example on GitHub as well.


问:
Extracting neural net weights using tensorflow's tf.contrib.learn.DNNClassifier
Is there a way to extract weight matrices from Tensorflow's tf.contrib.learn.DNNClassifier? I've tried to look up the Tensorflow site for an answer but I'm fairly new to this so I haven't found anything helpful so far. Sorry in advance if there is already explicit explanation for this in here that I wasn't able to find.

My code:

```<code># read the csv file to numpy array
df = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename="data.csv",
      target_dtype=np.int,
      features_dtype=np.float64)

X = df.data
Y = df.target
dimension = len(X)

feature_columns = [tf.contrib.layers.real_valued_column("", dimension=dimension)]

classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                                      hidden_units=[10,10],
                                                      n_classes=2,
                                                      activation_fn=tf.nn.sigmoid,
                                                      optimizer=tf.train.ProximalAdagradOptimizer(
                                                        learning_rate=0.1,
                                                        l2_regularization_strength=0.001))

#Fit model
classifier.fit(x=X, y=Y, steps=2000)
</code>```

答:
After some research I think I've come up with the answer:

```<code>classifier.get_variable_value(classifier.get_variable_names()[3])
</code>```

classifier.get_variable_names() prints a list of names

```<code>['dnn/binary_logistic_head/dnn/learning_rate',
'dnn/hiddenlayer_0/biases',
'dnn/hiddenlayer_0/biases//hiddenlayer_0/biases/part_0/Adagrad',
'dnn/hiddenlayer_0/weights',
'dnn/hiddenlayer_0/weights/hiddenlayer_0/weights/part_0/Adagrad',
'dnn/logits/biases',
'dnn/logits/biases/dnn/dnn/logits/biases/part_0/Adagrad',
'dnn/logits/weights',
'dnn/logits/weights/nn/dnn/logits/weights/part_0/Adagrad',
'global_step']
</code>```

And classifier.get_variable_names()[3] gets the fourth one, the weights for the first layer. The classifier in this case had one hidden layer with 10 neurons.

The 7th one 'dnn/logits/weights' gives the weights for the output layer.

Body:
Is there a way to extract weight matrices from Tensorflow's tf.contrib.learn.DNNClassifier? I've tried to look up the Tensorflow site for an answer but I'm fairly new to this so I haven't found anything helpful so far. Sorry in advance if there is already explicit explanation for this in here that I wasn't able to find.

My code:

# read the csv file to numpy array
df = tf.contrib.learn.datasets.base.load_csv_with_header(
      filename="data.csv",
      target_dtype=np.int,
      features_dtype=np.float64)

X = df.data
Y = df.target
dimension = len(X)

feature_columns = [tf.contrib.layers.real_valued_column("", dimension=dimension)]

classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,
                                                      hidden_units=[10,10],
                                                      n_classes=2,
                                                      activation_fn=tf.nn.sigmoid,
                                                      optimizer=tf.train.ProximalAdagradOptimizer(
                                                        learning_rate=0.1,
                                                        l2_regularization_strength=0.001))

#Fit model
classifier.fit(x=X, y=Y, steps=2000)

Body:
After some research I think I've come up with the answer:

classifier.get_variable_value(classifier.get_variable_names()[3])

classifier.get_variable_names() prints a list of names

['dnn/binary_logistic_head/dnn/learning_rate',
'dnn/hiddenlayer_0/biases',
'dnn/hiddenlayer_0/biases//hiddenlayer_0/biases/part_0/Adagrad',
'dnn/hiddenlayer_0/weights',
'dnn/hiddenlayer_0/weights/hiddenlayer_0/weights/part_0/Adagrad',
'dnn/logits/biases',
'dnn/logits/biases/dnn/dnn/logits/biases/part_0/Adagrad',
'dnn/logits/weights',
'dnn/logits/weights/nn/dnn/logits/weights/part_0/Adagrad',
'global_step']

And classifier.get_variable_names()[3] gets the fourth one, the weights for the first layer. The classifier in this case had one hidden layer with 10 neurons.

The 7th one 'dnn/logits/weights' gives the weights for the output layer.


问:
Best practices for developing scalable video transcoding server on Amazon Web Services?
What do people think are the most important issues when developing an application that is going to allow users to upload video and images to a server and have them transcoded by FFMPEG and stored in amazon S3? I have a couple of options;

1) install FFMPEG on the same server that handles file uploads, when a video is uploaded and stored on EC2 instance, call FFMPEG to convert it then when done, write the file to S3 bucket and dispose of the original.

How scalable is this? What happens when many users upload at the same time? How do I manage multiple processes at once? How do I know when to start another instance and load balance this configuration?

2) Have one server for processing uploads (updating database, renaming files etc) and one server for doing transcoding. Again what is the best way to manage multiple processes? should I be looking at Amazon SQS for this? Can I tell the transcoding server to get the file from the upload server or should I copy the file to the transcoding server? Should I just store all files on S3 and SQS can read from there. I am trying to have as little traffic as possible.

I am running a linux box as the upload server and have FFMPEG running on this.

Any advice on best practices for setting up such a configuration would be appreciated. Many thanks

答: You can check out Piper. It's an open source version of a product I originally built for a huge entertainment company to handle their video transcoding at scale. </p>


问:
Detect empty directory with Perl
What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

```<code>#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}
</code>```

These above, do not work properly to tell me that the folder is empty. Thanks!

Thanks all! I ended up using:

```<code>sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory";
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }
</code>```

答:
Using grep { ! /^[.][.]?\z/ } readdir $dir_h can be problematic for performance in case the check is done many times and some directories may have many files.

It would be better to short-circuit the moment a directory entry other than . or .. is found.

On Windows XP with ActiveState perl 5.10.1, the following sub seems to be twice as fast as the grep approach on my $HOME with 100 entries:

```<code>sub is_dir_empty {
    my ($dir) = @_;

    opendir my $h, $dir
        or die "Cannot open directory: '$dir': $!";

    while ( defined (my $entry = readdir $h) ) {
        return unless $entry =~ /^[.][.]?\z/;
    }

    return 1;
}
</code>```

Title: Detect empty directory with Perl

Body:
What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{
    die "\n$gAppsDir is not accessible or does not exist.\n";
}

These above, do not work properly to tell me that the folder is empty. Thanks!

Thanks all! I ended up using:

sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory";
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }

Body:
Using grep { ! /^[.][.]?\z/ } readdir $dir_h can be problematic for performance in case the check is done many times and some directories may have many files.

It would be better to short-circuit the moment a directory entry other than . or .. is found.

On Windows XP with ActiveState perl 5.10.1, the following sub seems to be twice as fast as the grep approach on my $HOME with 100 entries:

sub is_dir_empty {
    my ($dir) = @_;

    opendir my $h, $dir
        or die "Cannot open directory: '$dir': $!";

    while ( defined (my $entry = readdir $h) ) {
        return unless $entry =~ /^[.][.]?\z/;
    }

    return 1;
}


问:
Notification Service Extensions with NSLocalizedString
I am using Notification Serivce Extension to change the text coming from the server as per what I Want.

However, that was working good with normal strings. but when I used NSLocalizedString with it, it dosent show the localized string, instead it shows the field name of the string.

For example: inside the UNNotificationServiceExtension:

```<code>let CompanyViewLM = NSLocalizedString("Notifications.View", comment: "No Comment")
</code>```

and in Localizable.strings I put the following line:

```<code>Notifications.View = "I Viewed your profile";
</code>```

Noting that I put the same lines of code in a normal view controller and it works just fine.

答:
I Found by my self what was the problem.
The notification service target was working in the project without recognizing other files of the project.

To make it recognizes other files you must go to targets -> NotificationService -> Copy Bundle Resources -> add the files you want the notification service to work with.

In my case, I added the Localizable.strings file and it worked as a charm.

Body:
I am using Notification Serivce Extension to change the text coming from the server as per what I Want.

However, that was working good with normal strings. but when I used NSLocalizedString with it, it dosent show the localized string, instead it shows the field name of the string.

For example: inside the UNNotificationServiceExtension:

let CompanyViewLM = NSLocalizedString("Notifications.View", comment: "No Comment")

and in Localizable.strings I put the following line:

Notifications.View = "I Viewed your profile";

Noting that I put the same lines of code in a normal view controller and it works just fine.


问:
Q: Bash script infinite loop causing ffmpeg spam
Can't seem to figure this one out... I have a set up NGINX server with the excellent RTMP extension and everything is working fine. However, I'm trying to restream/push a copy of a couple specific streams that need to be streamed in another RTMP stream application (specifically, these streams are streamed to application "static" but in the current situation also need to be pushed over to "live"). The process of restreaming/pushing a stream in NGINX-RTMP is relatively simple, however, in my case I need to selectively push a couple of streams instead of every stream being streamed to the application "static".

Idea is to have NGINX-RTMP pass the stream name off to the bash script, which then does the restreaming without interrupting any other streams or services.

With some success, I've tried doing this by creating a bash scrip..

The relevant NGINX config bit that runs the bash script is:

```<code>exec_publish /etc/nginx/rtmp_conf.d/stream_id.sh $name;
</code>```

I tried it with an "if / else"

```<code>if [ $1 == "stream_name_1" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
elif [ $1 == "stream_name_2" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
elif [ $1 == "stream_name_3" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
elif [ $1 == "stream_name_4" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
else
        echo "FAIL" >> /etc/nginx/rtmp_conf.d/stream.log && echo date > /etc/nginx/rtmp_conf.d/stream.log
        exit
fi
</code>```

And I tried it with Switches

```<code>case "$1" in
        "stream_name_1")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
        ;;
        "stream_name_2")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
        ;;
        "stream_name_3")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
        ;;
        "stream_name_4")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
        ;;
        echo "FAIL " >> /etc/nginx/rtmp_conf.d/stream.log && echo date > /etc/nginx/rtmp_conf.d/stream.log
esac
</code>```

Problem with both is that they both end up spamming a ton of ffmpeg processes ... and I don't know why - I've tried changing the code but I either end up with ffmpeg not firing at all or spamming the server.

答:
Need more info.

What do ffmpegs say?

Have you checked the $1?

I would like to see the entire script.

Body:
Can't seem to figure this one out... I have a set up NGINX server with the excellent RTMP extension and everything is working fine. However, I'm trying to restream/push a copy of a couple specific streams that need to be streamed in another RTMP stream application (specifically, these streams are streamed to application "static" but in the current situation also need to be pushed over to "live"). The process of restreaming/pushing a stream in NGINX-RTMP is relatively simple, however, in my case I need to selectively push a couple of streams instead of every stream being streamed to the application "static".

Idea is to have NGINX-RTMP pass the stream name off to the bash script, which then does the restreaming without interrupting any other streams or services.

With some success, I've tried doing this by creating a bash scrip..

The relevant NGINX config bit that runs the bash script is:

exec_publish /etc/nginx/rtmp_conf.d/stream_id.sh $name;

I tried it with an "if / else"

if [ $1 == "stream_name_1" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
elif [ $1 == "stream_name_2" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
elif [ $1 == "stream_name_3" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
elif [ $1 == "stream_name_4" ]; then
        ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
else
        echo "FAIL" >> /etc/nginx/rtmp_conf.d/stream.log && echo date > /etc/nginx/rtmp_conf.d/stream.log
        exit
fi

And I tried it with Switches

case "$1" in
        "stream_name_1")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_1 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_0
        ;;
        "stream_name_2")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_2 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_1
        ;;
        "stream_name_3")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_3 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_2
        ;;
        "stream_name_4")
            ffmpeg -re -i rtmp://127.0.0.1:2000/static/stream_name_4 -vcodec libx264 -acodec copy -f flv rtmp://127.0.0.1:2000/live/live_3
        ;;
        echo "FAIL " >> /etc/nginx/rtmp_conf.d/stream.log && echo date > /etc/nginx/rtmp_conf.d/stream.log
esac

Problem with both is that they both end up spamming a ton of ffmpeg processes ... and I don't know why - I've tried changing the code but I either end up with ffmpeg not firing at all or spamming the server.


问:
Ionic Uncaught (in promise): invalid link
I have probably a problem with this.nav.push in Ionic. I have done a login/registration page but when I login, I get this error message. I have to add some code in login.ts and e.g home.ts (which is the main page) ?

Runtime Error

  Uncaught (in promise): invalid link: HomePage

Error: Uncaught (in promise): invalid link: HomePage
      at d (http://localhost:8100/build/polyfills.js:3:3991)
      at l (http://localhost:8100/build/polyfills.js:3:3244)
      at Object.reject (http://localhost:8100/build/polyfills.js:3:2600)
      at NavControllerBase._fireError (http://localhost:8100/build/main.js:45465:16)
      at NavControllerBase._failed (http://localhost:8100/build/main.js:45453:14)
      at http://localhost:8100/build/main.js:45508:59
      at t.invoke (http://localhost:8100/build/polyfills.js:3:11562)
      at Object.onInvoke (http://localhost:8100/build/main.js:4622:37)
      at t.invoke (http://localhost:8100/build/polyfills.js:3:11502)
      at n.run (http://localhost:8100/build/polyfills.js:3:6468)
      at http://localhost:8100/build/polyfills.js:3:3767
      at t.invokeTask (http://localhost:8100/build/polyfills.js:3:12256)
      at Object.onInvokeTask (http://localhost:8100/build/main.js:4613:37)
      at t.invokeTask (http://localhost:8100/build/polyfills.js:3:12177)
      at n.runTask (http://localhost:8100/build/polyfills.js:3:7153)

@edit: The problem occurs when I want login to my app. Here is the code to login.

login.ts

```<code>public login() {
    this.showLoading()
    this.auth.login(this.registerCredentials).subscribe(allowed => {
      if (allowed) {
       this.nav.push('HomePage');
      } else {
        this.showError("Access Denied");
      }
    },
      error => {
        this.showError(error);
      });
    }
</code>```

auth-service.ts ( here is public function which executes my login and where I have password and email which I need to type in login )

```<code>  public login(credentials) {
    if (credentials.email === null || credentials.password === null) {
      return Observable.throw("Please insert credentials");
    } else {
      return Observable.create(observer => {
        // At this point make a request to your backend to make a real check!
        let access = (credentials.password === "pass" && credentials.email === "email");
        this.currentUser = new User('Simon', 'saimon@devdactic.com');
        observer.next(access);
        observer.complete();
      });
    }
  }
</code>```

I don't know why this code is wrong. My home page in my app is home.ts and class is HomePage

答:
what you need to do is to add @IonicPage() before '@Component' and import 'IonicPage'  like this :
 import {NavController, IonicPage} from 'ionic-angular';

then you need to create a module for the homepage i.e in the home directory , create home.module.ts with the following contents

```<code>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';

@NgModule({
  declarations: [
    HomePage
  ],
  imports: [
    IonicPageModule.forChild(HomePage),
  ],
  exports: [
    HomePage
  ]
})
export class HomePageModule {}
</code>```

and reload the project

ContentLicense: CC BY-SA 4.0

Body:
I have probably a problem with this.nav.push in Ionic. I have done a login/registration page but when I login, I get this error message. I have to add some code in login.ts and e.g home.ts (which is the main page) ?

Runtime Error

  Uncaught (in promise): invalid link: HomePage

Error: Uncaught (in promise): invalid link: HomePage
      at d (http://localhost:8100/build/polyfills.js:3:3991)
      at l (http://localhost:8100/build/polyfills.js:3:3244)
      at Object.reject (http://localhost:8100/build/polyfills.js:3:2600)
      at NavControllerBase._fireError (http://localhost:8100/build/main.js:45465:16)
      at NavControllerBase._failed (http://localhost:8100/build/main.js:45453:14)
      at http://localhost:8100/build/main.js:45508:59
      at t.invoke (http://localhost:8100/build/polyfills.js:3:11562)
      at Object.onInvoke (http://localhost:8100/build/main.js:4622:37)
      at t.invoke (http://localhost:8100/build/polyfills.js:3:11502)
      at n.run (http://localhost:8100/build/polyfills.js:3:6468)
      at http://localhost:8100/build/polyfills.js:3:3767
      at t.invokeTask (http://localhost:8100/build/polyfills.js:3:12256)
      at Object.onInvokeTask (http://localhost:8100/build/main.js:4613:37)
      at t.invokeTask (http://localhost:8100/build/polyfills.js:3:12177)
      at n.runTask (http://localhost:8100/build/polyfills.js:3:7153)

@edit: The problem occurs when I want login to my app. Here is the code to login.

login.ts

public login() {
    this.showLoading()
    this.auth.login(this.registerCredentials).subscribe(allowed => {
      if (allowed) {
       this.nav.push('HomePage');
      } else {
        this.showError("Access Denied");
      }
    },
      error => {
        this.showError(error);
      });
    }

auth-service.ts ( here is public function which executes my login and where I have password and email which I need to type in login )

  public login(credentials) {
    if (credentials.email === null || credentials.password === null) {
      return Observable.throw("Please insert credentials");
    } else {
      return Observable.create(observer => {
        // At this point make a request to your backend to make a real check!
        let access = (credentials.password === "pass" && credentials.email === "email");
        this.currentUser = new User('Simon', 'saimon@devdactic.com');
        observer.next(access);
        observer.complete();
      });
    }
  }

I don't know why this code is wrong. My home page in my app is home.ts and class is HomePage

Body:
what you need to do is to add @IonicPage() before '@Component' and import 'IonicPage'  like this :
 import {NavController, IonicPage} from 'ionic-angular';

then you need to create a module for the homepage i.e in the home directory , create home.module.ts with the following contents

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';

@NgModule({
  declarations: [
    HomePage
  ],
  imports: [
    IonicPageModule.forChild(HomePage),
  ],
  exports: [
    HomePage
  ]
})
export class HomePageModule {}

and reload the project


问:
Static Control Background Color with C++
I am creating a basic GUI with the Windows API and I have run into an issue.  It starts with a main window that opens with a custom background color I set (RGB(230,230,230)).  It then displays text in the upper left corner with the static control.

```<code>settingstext = CreateWindow("STATIC",
                             "SETTINGS",
                             SS_LEFT | WS_CHILD,
                             12,
                             20,
                             100,
                             20,
                             hwnd,
                             NULL,
                             proginstance,
                             NULL);
ShowWindow(settingstext, 1);
</code>```

This works, but when the text is displayed I need a way to change the background of it to match the main window or else it just looks like it doesn't blend in.

My question is, how do I do this?  I currently use the method below and it works, but I wanted to know, is there a way to permanently set the background color somehow, right after the CreateWindow function for the static control without changing system colors, and just have it apply to that one control and not anything that sends the WM_CTLCOLORSTATIC message.  I have experimented around with using the GetDC function and SetBkColor function outside of the message loop but nothing works.

```<code>    case WM_CTLCOLORSTATIC:
    {
    HDC hdcStatic = (HDC) wParam;
    SetTextColor(hdcStatic, RGB(0,0,0));
    SetBkColor(hdcStatic, RGB(230,230,230));
    return (INT_PTR)CreateSolidBrush(RGB(230,230,230));
    }
</code>```

I want to do this because...

I don't want to fill up my message loop with functions that need to be called every time the window repaints.

Have the changes apply to only this static control.

I would be very thankful for any help that could be provided, at least pointing me in the right direction, thanks.

答: Have you considered subclassing the static window and doing owner draw?</p>

Body:
I am creating a basic GUI with the Windows API and I have run into an issue.  It starts with a main window that opens with a custom background color I set (RGB(230,230,230)).  It then displays text in the upper left corner with the static control.

settingstext = CreateWindow("STATIC",
                             "SETTINGS",
                             SS_LEFT | WS_CHILD,
                             12,
                             20,
                             100,
                             20,
                             hwnd,
                             NULL,
                             proginstance,
                             NULL);
ShowWindow(settingstext, 1);

This works, but when the text is displayed I need a way to change the background of it to match the main window or else it just looks like it doesn't blend in.

My question is, how do I do this?  I currently use the method below and it works, but I wanted to know, is there a way to permanently set the background color somehow, right after the CreateWindow function for the static control without changing system colors, and just have it apply to that one control and not anything that sends the WM_CTLCOLORSTATIC message.  I have experimented around with using the GetDC function and SetBkColor function outside of the message loop but nothing works.

    case WM_CTLCOLORSTATIC:
    {
    HDC hdcStatic = (HDC) wParam;
    SetTextColor(hdcStatic, RGB(0,0,0));
    SetBkColor(hdcStatic, RGB(230,230,230));
    return (INT_PTR)CreateSolidBrush(RGB(230,230,230));
    }

I want to do this because...

I don't want to fill up my message loop with functions that need to be called every time the window repaints.

Have the changes apply to only this static control.

I would be very thankful for any help that could be provided, at least pointing me in the right direction, thanks.


问:
Input not binding correctly with Vue.js
I'm still relatively new to Vue.js and am having an issue binding one of my inputs to my viewmodel.

Here is my JavaScript:

```<code>var viewModel = new Vue({
    el: "#InventoryContainer",
    data: {
        upcCode: "",
        component: {
            Name: ""
        }
    },
    methods: {
        upcEntered: function (e) {
            if (this.upcCode.length > 0){
                $.ajax({
                    url: "/Component/GetByUpc",
                    type: "GET",
                    data: {
                        upc: this.upcCode
                    }
                }).done(function (response) {
                    if (response.exists) {
                        $("#ComponentInformation").toggleClass("hidden");
                        this.component = response.component;
                    } else {
                        alert("No component found.");
                    }
                });
            }
        }
    }
});
</code>```

Here is my HTML:

```<code><div class="form-horizontal row">
    <div class="col-sm-12">
        <div class="form-group">
            <label class="control-label col-md-4">UPC Code</label>
            <div class="col-md-8">
                <input id="ComponentUPC" class="form-control" placeholder="Scan or enter UPC Code" v-on:blur="upcEntered" v-model="upcCode" />
            </div>
        </div>

        <div id="ComponentInformation" class="hidden">
            <input type="text" class="form-control" readonly v-model="component.Name" />
        </div>
    </div>
</div>
</code>```

Now the issue is that even when I enter a valid UPC code and I assign the component to my ViewModel, the input that is bound to component.Name does not update with the component name. And when I enter into the console viewModel.component.Name I can see that it returns "".

But if I put an alert in my ajax.done function after I've assigned the component and it looks like this alert(this.component.Name) it alerts the name of the component.

Any ideas of where I'm going wrong here?

答:
You cannot use that line
this.component = response.component;
because of the this-variable.

You should put the line
var self = this
before your ajax call and use self.component instead of this.component

Title: Input not binding correctly with Vue.js

Body:
I'm still relatively new to Vue.js and am having an issue binding one of my inputs to my viewmodel.

Here is my JavaScript:

var viewModel = new Vue({
    el: "#InventoryContainer",
    data: {
        upcCode: "",
        component: {
            Name: ""
        }
    },
    methods: {
        upcEntered: function (e) {
            if (this.upcCode.length > 0){
                $.ajax({
                    url: "/Component/GetByUpc",
                    type: "GET",
                    data: {
                        upc: this.upcCode
                    }
                }).done(function (response) {
                    if (response.exists) {
                        $("#ComponentInformation").toggleClass("hidden");
                        this.component = response.component;
                    } else {
                        alert("No component found.");
                    }
                });
            }
        }
    }
});

Here is my HTML:

            UPC Code

                <input id="ComponentUPC" class="form-control" placeholder="Scan or enter UPC Code" v-on:blur="upcEntered" v-model="upcCode" />

            <input type="text" class="form-control" readonly v-model="component.Name" />

Now the issue is that even when I enter a valid UPC code and I assign the component to my ViewModel, the input that is bound to component.Name does not update with the component name. And when I enter into the console viewModel.component.Name I can see that it returns "".

But if I put an alert in my ajax.done function after I've assigned the component and it looks like this alert(this.component.Name) it alerts the name of the component.

Any ideas of where I'm going wrong here?


问:
A function that uses recursion isn't working as expected
```<code>#include <iostream>
#include <vector>
using namespace std;

const int maxx = 6;
vector <int> nums {maxx};
string ops = "-----";

bool fillOps (int target, int n=maxx-1) {
    if (n == 0) {
        if (nums[n]==target) {
            cout << target << " GOOD " << endl;
            return true;
        } else {
            cout << target << " GOOD " << endl;
            return false;
        }
    }
    if (nums[n] != 0) {
        if (fillOps(target/nums[n], n-1)) {
            ops[n-1]='*';
            return true;
        }
    } else if (fillOps(target*nums[n], n-1)) {
        ops[n-1]='/';
        return true;
    } else if (fillOps(target+nums[n], n-1)) {
        ops[n-1]='-';
        return true;
    } else if (fillOps(target-nums[n], n-1)) {
        ops[n-1]='+';
        return true;
    } else
        return false;
}

int main() {
    ops=".....";
    for (int i=0; i<maxx; i++)
        cin >> nums[i];
    int target;
    cin >> target;

    if (fillOps(target))
        cout << ops;
    else
        cout << "No solution exists.";
}
</code>```

The user is expected to enter 5 integers and a target number. The program is supposed to return the operations that you have to perform in order to get to the target number.

Example Input:

7 3 100 7 25 9

881

Example Output:

*+*++

Another example of input:

100 6 3 75 50 25

952

Output of that:

+**-/

Another example of input:

3 8 7 6 3 1

250

Example of output for above example:

+*+*+

Note that operations go from left to right for this program, i.e.,

(((((3+8)*7)+6)*3)+1) = 250

This is a solution to a challenge that I found on reddit. I want to solve this using recursion. I tried my but it doesn't seem to work properly. I've been banging my head around this problem for a a couple of weeks.

Thank you and have a nice day.

答:
Make sure that every path has a return. Do not calculate in reverse order, this overs complicates the algorithm. See my following code and read the comments:

```<code>const int maxx = 5;
std::vector <int> nums(maxx); // <-- vector with 5 elements
std::string ops = "-----";

bool fillOps (int target, int current, int n=maxx-1) {

    if (n == 0) {
        // end of recursion path : do no output here becaus it is too early
        return current == target;
    }

    int i = maxx - n;
    if (nums[i] != 0 &&                           // <-- test divison by zero
        target % nums[n] == 0 &&                  // <-- test division has no rest
        fillOps(target, current/nums[i], n-1) ) { // <-- and fillOps in same condition
        ops[i-1]='/';
        return true;
    } else if (fillOps(target, current*nums[i], n-1)) {
        ops[i-1]='*';
        return true;
    } else if (fillOps(target, current-nums[i], n-1)) {
        ops[i-1]='-';
        return true;
    } else if (fillOps(target, current+nums[i], n-1)) {
        ops[i-1]='+';
        return true;
    }
    return false;
}

int main() {
   ops=".....";
   for (int i=0; i<maxx; i++)
       std::cin >> nums[i];
   int target;
   std::cin >> target;

   if (fillOps(target, nums[0]))
       std::cout << ops;
   else
       std::cout << "No solution exists.";

   return 0;
}
</code>```

Body:
#include <iostream>
#include <vector>
using namespace std;

const int maxx = 6;
vector <int> nums {maxx};
string ops = "-----";

bool fillOps (int target, int n=maxx-1) {
    if (n == 0) {
        if (nums[n]==target) {
            cout << target << " GOOD " << endl;
            return true;
        } else {
            cout << target << " GOOD " << endl;
            return false;
        }
    }
    if (nums[n] != 0) {
        if (fillOps(target/nums[n], n-1)) {
            ops[n-1]='*';
            return true;
        }
    } else if (fillOps(target*nums[n], n-1)) {
        ops[n-1]='/';
        return true;
    } else if (fillOps(target+nums[n], n-1)) {
        ops[n-1]='-';
        return true;
    } else if (fillOps(target-nums[n], n-1)) {
        ops[n-1]='+';
        return true;
    } else
        return false;
}

int main() {
    ops=".....";
    for (int i=0; i<maxx; i++)
        cin >> nums[i];
    int target;
    cin >> target;

    if (fillOps(target))
        cout << ops;
    else
        cout << "No solution exists.";
}

The user is expected to enter 5 integers and a target number. The program is supposed to return the operations that you have to perform in order to get to the target number.

Example Input:

7 3 100 7 25 9

881

Example Output:

*+*++

Another example of input:

100 6 3 75 50 25

952

Output of that:

+**-/

Another example of input:

3 8 7 6 3 1

250

Example of output for above example:

+*+*+

Note that operations go from left to right for this program, i.e.,

(((((3+8)*7)+6)*3)+1) = 250

This is a solution to a challenge that I found on reddit. I want to solve this using recursion. I tried my but it doesn't seem to work properly. I've been banging my head around this problem for a a couple of weeks.

Thank you and have a nice day.

Body:
Make sure that every path has a return. Do not calculate in reverse order, this overs complicates the algorithm. See my following code and read the comments:

const int maxx = 5;
std::vector <int> nums(maxx); // <-- vector with 5 elements
std::string ops = "-----";

bool fillOps (int target, int current, int n=maxx-1) {

    if (n == 0) {
        // end of recursion path : do no output here becaus it is too early
        return current == target;
    }

    int i = maxx - n;
    if (nums[i] != 0 &&                           // <-- test divison by zero
        target % nums[n] == 0 &&                  // <-- test division has no rest
        fillOps(target, current/nums[i], n-1) ) { // <-- and fillOps in same condition
        ops[i-1]='/';
        return true;
    } else if (fillOps(target, current*nums[i], n-1)) {
        ops[i-1]='*';
        return true;
    } else if (fillOps(target, current-nums[i], n-1)) {
        ops[i-1]='-';
        return true;
    } else if (fillOps(target, current+nums[i], n-1)) {
        ops[i-1]='+';
        return true;
    }
    return false;
}

int main() {
   ops=".....";
   for (int i=0; i<maxx; i++)
       std::cin >> nums[i];
   int target;
   std::cin >> target;

   if (fillOps(target, nums[0]))
       std::cout << ops;
   else
       std::cout << "No solution exists.";

   return 0;
}


问:
Change foreground of a textblock in a ToggleButton
I'm new to WPF and I'm totaly stuck with a foreground who don't want to update :@

I wan't to make a radiobutton with a togglebutton behavior (that's ok), but i want to wrap the text inside this button.

If the content is defined in the toggleButton, my foreground become white. But if i use a Textblock inside the togglebutton (with a wrap), my foreground don't want to change.

My two buttons in XAML

```<code>        <RadioButton GroupName="line1" Grid.Row="1" Grid.Column="1" Style="{DynamicResource ToggleButtonStyle1}">
        <RadioButton.Content>
            <TextBlock TextWrapping="Wrap" >I can wrap but ...</TextBlock>
        </RadioButton.Content>
    </RadioButton>

    <RadioButton GroupName="line0" Grid.Row="1" Grid.Column="2" Style="{DynamicResource ToggleButtonStyle1}" Content="i can't Wrap and it's not good"/>
</code>```

And my ControlTemplate in app.xaml

```<code> <ControlTemplate TargetType="{x:Type ToggleButton}">
    <Border x:Name="border" BorderThickness="1" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
        <Border.BorderBrush>
            <SolidColorBrush Color="{DynamicResource BleuClair}"/>
        </Border.BorderBrush>
        <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="Button.IsDefaulted" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        </Trigger>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsChecked"  Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
</code>```

I'm not sure if i need to update the ControlTemplate or the ContentPresenter to add "Something" about the textblock or if i need to update the XAML to make a binding to this custom style.

Thank you for your time :)

答:
I find (finally :'( ) my solution.
I think it can be done in the ControlTemplate, but i don't know how ^^

I had this :

```<code><RadioButton GroupName="line1" Grid.Row="1" Grid.Column="1" Style"{DynamicResource ToggleButtonStyle1}">
        <TextBlock TextWrapping="Wrap" >I can wrap but ...</TextBlock>
</RadioButton>
</code>```

And to apply my foreground property (from the radioButton), i simply add a binding to the contentPresenter.

```<code>    <RadioButton GroupName="line1" Grid.Row="1" Grid.Column="1" Style="{DynamicResource ToggleButtonStyle1}">
        <TextBlock Foreground="{Binding Path=(TextElement.Foreground), RelativeSource={RelativeSource AncestorType=ContentPresenter}}"
                   TextWrapping="Wrap" >I can wrap but ...</TextBlock>
    </RadioButton>
</code>```

Body:
I'm new to WPF and I'm totaly stuck with a foreground who don't want to update :@

I wan't to make a radiobutton with a togglebutton behavior (that's ok), but i want to wrap the text inside this button.

If the content is defined in the toggleButton, my foreground become white. But if i use a Textblock inside the togglebutton (with a wrap), my foreground don't want to change.

My two buttons in XAML

        <RadioButton GroupName="line1" Grid.Row="1" Grid.Column="1" Style="{DynamicResource ToggleButtonStyle1}">
        <RadioButton.Content>
            <TextBlock TextWrapping="Wrap" >I can wrap but ...</TextBlock>
        </RadioButton.Content>
    </RadioButton>

    <RadioButton GroupName="line0" Grid.Row="1" Grid.Column="2" Style="{DynamicResource ToggleButtonStyle1}" Content="i can't Wrap and it's not good"/>

And my ControlTemplate in app.xaml

 <ControlTemplate TargetType="{x:Type ToggleButton}">
    <Border x:Name="border" BorderThickness="1" Background="{TemplateBinding Background}" SnapsToDevicePixels="true">
        <Border.BorderBrush>
            <SolidColorBrush Color="{DynamicResource BleuClair}"/>
        </Border.BorderBrush>
        <ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="Button.IsDefaulted" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Static.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Static.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
        </Trigger>
        <Trigger Property="IsMouseOver" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsPressed" Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Disabled.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Disabled.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
        <Trigger Property="IsChecked"  Value="true">
            <Setter Property="Background" TargetName="border" Value="{StaticResource Button.Pressed.Background}"/>
            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.Pressed.Border}"/>
            <Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="White"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

I'm not sure if i need to update the ControlTemplate or the ContentPresenter to add "Something" about the textblock or if i need to update the XAML to make a binding to this custom style.

Thank you for your time :)

Body:
I find (finally :'( ) my solution.
I think it can be done in the ControlTemplate, but i don't know how ^^

I had this :

<RadioButton GroupName="line1" Grid.Row="1" Grid.Column="1" Style"{DynamicResource ToggleButtonStyle1}">
        <TextBlock TextWrapping="Wrap" >I can wrap but ...</TextBlock>
</RadioButton>

And to apply my foreground property (from the radioButton), i simply add a binding to the contentPresenter.

    <RadioButton GroupName="line1" Grid.Row="1" Grid.Column="1" Style="{DynamicResource ToggleButtonStyle1}">
        <TextBlock Foreground="{Binding Path=(TextElement.Foreground), RelativeSource={RelativeSource AncestorType=ContentPresenter}}"
                   TextWrapping="Wrap" >I can wrap but ...</TextBlock>
    </RadioButton>


问:
BASH; using find and -exec to remove .pyc files
Using the command line in Ubuntu 16.04.2 LTS. I'm getting towards the end of Zed Shaw's LPTHW, and on the video to ex46.py he exercises the following bash command to find and remove all .pyc byte code files:

```<code>find . -name "*.pyc" -exec rm {}
</code>```

On the video this successfully removes all of Zed Shaw's .pyc files. However, upon typing in the exact same command I get the following error:

```<code>find: missing argument to `-exec'
</code>```

I understand that there are many ways to delete .pyc files, however, since I'm following along with Zed Shaw I'd like to know how to do it using find and -exec. What am I doing wrong?

答:
you need to terminate the -exec command with \;

```<code>find . -name "*.pyc" -exec rm {} \;
</code>```

have a look at find -exec in the man page.

as mentioned in the comments by Gordon Davisson it may be more efficient to terminate the command with + as rm is then invoked fewer times:

```<code>find . -name "*.pyc" -exec rm {} +
</code>```

Body:
Using the command line in Ubuntu 16.04.2 LTS. I'm getting towards the end of Zed Shaw's LPTHW, and on the video to ex46.py he exercises the following bash command to find and remove all .pyc byte code files:

find . -name "*.pyc" -exec rm {}

On the video this successfully removes all of Zed Shaw's .pyc files. However, upon typing in the exact same command I get the following error:

find: missing argument to `-exec'

I understand that there are many ways to delete .pyc files, however, since I'm following along with Zed Shaw I'd like to know how to do it using find and -exec. What am I doing wrong?

Body:
you need to terminate the -exec command with \;

find . -name "*.pyc" -exec rm {} \;

have a look at find -exec in the man page.

as mentioned in the comments by Gordon Davisson it may be more efficient to terminate the command with + as rm is then invoked fewer times:

find . -name "*.pyc" -exec rm {} +


问:
How To Increase Sklearn GMM predict() Performance Speed?
I am using Sklearn to estimate the Gaussian Mixture Model (GMM) on some data.

After the estimation, I have many query points. I would like to obtain their probabilities of belonging to each of the estimated Gaussian.

The code below works. However, the gmm_sk.predict_proba(query_points) part is very slow as I need to run it multiple times on 100000 sets of samples, where each sample contains 1000 points.

I guess that it happens because it is sequential. Is there a way to make it parallel? Or any other way to make it faster? Maybe on GPU using TensorFlow?

I saw TensorFlow has its own GMM algorithm but it was very hard to implement.

Here is the code that I have written:

```<code>import numpy as np
from sklearn.mixture import GaussianMixture
import time

n_gaussians = 1000
covariance_type = 'diag'
points = np.array(np.random.rand(10000, 3), dtype=np.float32)
query_points = np.array(np.random.rand(1000, 3), dtype=np.float32)
start = time.time()

#GMM with sklearn
gmm_sk = GaussianMixture(n_components = n_gaussians, covariance_type=covariance_type)
gmm_sk.fit(points)
mid_t = time.time()
elapsed = time.time() - start
print("learning took "+ str(elapsed))

temp = []
for i in range(2000):
    temp.append(gmm_sk.predict_proba(query_points))

end_t = time.time() - mid_t
print("predictions took " + str(end_t))
</code>```

I solved it ! using multiprocessing.
just replaced

```<code>temp = []
for i in range(2000):
    temp.append(gmm_sk.predict_proba(query_points))
</code>```

with

```<code>import multiprocessing as mp
    query_points = query_points.tolist()
    parallel = mp.Pool()
    fv = parallel.map(par_gmm, query_points)
    parallel.close()
    parallel.join()
</code>```

答:
You could speed up the process if you fit with the 'diagonal' or spherical covariance matrix instead of full.

Use:

covariance_type='diag'

or

covariance_type='spherical'

inside GaussianMixture

Also, try to decrease the Gaussian components.

However, keep in mind that this may affect the results but I cannot see other way to speed up the process.

Body:
I am using Sklearn to estimate the Gaussian Mixture Model (GMM) on some data.

After the estimation, I have many query points. I would like to obtain their probabilities of belonging to each of the estimated Gaussian.

The code below works. However, the gmm_sk.predict_proba(query_points) part is very slow as I need to run it multiple times on 100000 sets of samples, where each sample contains 1000 points.

I guess that it happens because it is sequential. Is there a way to make it parallel? Or any other way to make it faster? Maybe on GPU using TensorFlow?

I saw TensorFlow has its own GMM algorithm but it was very hard to implement.

Here is the code that I have written:

import numpy as np
from sklearn.mixture import GaussianMixture
import time

n_gaussians = 1000
covariance_type = 'diag'
points = np.array(np.random.rand(10000, 3), dtype=np.float32)
query_points = np.array(np.random.rand(1000, 3), dtype=np.float32)
start = time.time()

#GMM with sklearn
gmm_sk = GaussianMixture(n_components = n_gaussians, covariance_type=covariance_type)
gmm_sk.fit(points)
mid_t = time.time()
elapsed = time.time() - start
print("learning took "+ str(elapsed))

temp = []
for i in range(2000):
    temp.append(gmm_sk.predict_proba(query_points))

end_t = time.time() - mid_t
print("predictions took " + str(end_t))

I solved it ! using multiprocessing.
just replaced

temp = []
for i in range(2000):
    temp.append(gmm_sk.predict_proba(query_points))

with

import multiprocessing as mp
    query_points = query_points.tolist()
    parallel = mp.Pool()
    fv = parallel.map(par_gmm, query_points)
    parallel.close()
    parallel.join()


问:
plotting quarter wise using ggplot in R
I am trying to plot display the data set quarter-wise, but when I am using following command it is not in proper order i.e. the plot is in alphabetical order rather than the sequence given in the data.

```<code>ggplot(data =b1[b1$Rank==2,], aes(x=Quarter, y=Max, group=1)) +
  geom_line()
</code>```

Here is the data:

```<code> Max    Quarter     Rank

25379   Jul-Sep'13  2
25012   Oct-Dec'13  2
25026   Jan-Mar'14  2
24821   Apr-Jun'14  2
24946   Jul-Sep'14  2
24423   Oct-Dec'14  2
23738   Jan-Mar'15  2
23562   Apr-Jun'15  2
23122   Jul-Sep'15  2
22227   Oct-Dec'15  2
22347   Jan-Mar'16  2
21558   Apr-Jun'16  2
21272   Jul-Sep'16  2
23109   Oct-Dec'16  2
22349   Jan-Mar'17  2
</code>```

I have also tried to use the unique() function.

```<code>b1$Quarter <- factor(b1$Quarter, levels =unique (b1$Quarter))
</code>```

But the plot is still not in order.

答:
Couldn't you turn the dataframe into a ts object recognizing that this is quarterly data and then plot it using autoplot()?

```<code>y <- ts(df$Max, frequency=4, start = c(2013, 3)) ##starting 3rd Quarter
autoplot(y)
</code>```

Title: plotting quarter wise using ggplot in R

Body:
I am trying to plot display the data set quarter-wise, but when I am using following command it is not in proper order i.e. the plot is in alphabetical order rather than the sequence given in the data.

ggplot(data =b1[b1$Rank==2,], aes(x=Quarter, y=Max, group=1)) +
  geom_line()

Here is the data:

 Max    Quarter     Rank

25379   Jul-Sep'13  2
25012   Oct-Dec'13  2
25026   Jan-Mar'14  2
24821   Apr-Jun'14  2
24946   Jul-Sep'14  2
24423   Oct-Dec'14  2
23738   Jan-Mar'15  2
23562   Apr-Jun'15  2
23122   Jul-Sep'15  2
22227   Oct-Dec'15  2
22347   Jan-Mar'16  2
21558   Apr-Jun'16  2
21272   Jul-Sep'16  2
23109   Oct-Dec'16  2
22349   Jan-Mar'17  2

I have also tried to use the unique() function.

b1$Quarter <- factor(b1$Quarter, levels =unique (b1$Quarter))

But the plot is still not in order.

Body:
Couldn't you turn the dataframe into a ts object recognizing that this is quarterly data and then plot it using autoplot()?

y <- ts(df$Max, frequency=4, start = c(2013, 3)) ##starting 3rd Quarter
autoplot(y)


问:
Calculating n-dimensional Image Entropy Python
I am trying to calculate the entropy on higher dimensional "images". The obvious approach:

```<code>from scipy.stats import entropy

kernel_radius=2
entropy_stack = np.zeros(Stack.shape)
for ii in range(kernel_radius,entropy_stack.shape[0]-kernel_radius):
    for jj in range(kernel_radius,entropy_stack.shape[1]-kernel_radius):
        for kk in range(kernel_radius,entropy_stack.shape[2]-kernel_radius):
            entropy_stack[ii,jj,kk]=entropy(Stack[ii-kernel_radius:ii+kernel_radius,jj-kernel_radius:jj+kernel_radius,kk-kernel_radius:kk+kernel_radius].flatten())
</code>```

works but is painfully slow.

Are there any implementation tricks to calculating entropy in higher dimensional images? even better: are there any packages with an optimized version of this function?

I know scikit-image's entropy does a good job but only in 2D. Similarly I know matlab's entropyfilt which performs a couple hundred times faster than my current implementation.

答:
This is a solution that unfortunately turned out to be just as slow (albeit being much cleaner code and handling the boundaries properly). It uses the generic_filter in scipy.ndimage:

```<code>import numpy as np
from scipy.ndimage import generic_filter
from scipy.stats import entropy

def _entropy(values):
    probabilities = np.bincount(values.astype(np.int)) / float(len(values))
    return entropy(probabilities)

def local_entropy(img, kernel_radius=2):
    """
    Compute the local entropy for each pixel in an image or image stack using the neighbourhood specified by the kernel.

    Arguments:
    ----------
    img           -- 2D or 3D uint8 array with dimensions MxN or TxMxN, respectively.
                     Input image.
    kernel_radius -- int
                     Neighbourhood over which to compute the local entropy.

    Returns:
    --------
    h -- 2D or 3D uint8 array with dimensions MxN or TxMxN, respectively.
         Local entropy.

    """
    return generic_filter(img.astype(np.float), _entropy, size=2*kernel_radius)
</code>```

Body:
I am trying to calculate the entropy on higher dimensional "images". The obvious approach:

from scipy.stats import entropy

kernel_radius=2
entropy_stack = np.zeros(Stack.shape)
for ii in range(kernel_radius,entropy_stack.shape[0]-kernel_radius):
    for jj in range(kernel_radius,entropy_stack.shape[1]-kernel_radius):
        for kk in range(kernel_radius,entropy_stack.shape[2]-kernel_radius):
            entropy_stack[ii,jj,kk]=entropy(Stack[ii-kernel_radius:ii+kernel_radius,jj-kernel_radius:jj+kernel_radius,kk-kernel_radius:kk+kernel_radius].flatten())

works but is painfully slow.

Are there any implementation tricks to calculating entropy in higher dimensional images? even better: are there any packages with an optimized version of this function?

I know scikit-image's entropy does a good job but only in 2D. Similarly I know matlab's entropyfilt which performs a couple hundred times faster than my current implementation.

Body:
This is a solution that unfortunately turned out to be just as slow (albeit being much cleaner code and handling the boundaries properly). It uses the generic_filter in scipy.ndimage:

import numpy as np
from scipy.ndimage import generic_filter
from scipy.stats import entropy

def _entropy(values):
    probabilities = np.bincount(values.astype(np.int)) / float(len(values))
    return entropy(probabilities)

def local_entropy(img, kernel_radius=2):
    """
    Compute the local entropy for each pixel in an image or image stack using the neighbourhood specified by the kernel.

    Arguments:
    ----------
    img           -- 2D or 3D uint8 array with dimensions MxN or TxMxN, respectively.
                     Input image.
    kernel_radius -- int
                     Neighbourhood over which to compute the local entropy.

    Returns:
    --------
    h -- 2D or 3D uint8 array with dimensions MxN or TxMxN, respectively.
         Local entropy.

    """
    return generic_filter(img.astype(np.float), _entropy, size=2*kernel_radius)


问:
fio: blocksize too large for data set
I want to benchmark my SSD using Fio (Flexible I/O) I/O benchmarking tool inside Docker containers.

I am running my Docker containers like

docker run -it -v /dev/nvme0n1:/mount saurabhd04/docker_fio

where I am mounting my SSD as a Docker volume.

But, whenever I run fio inside Docker container, I get following error:

fio: blocksize too large for data set.

Am I missing anything? Any help regarding this would be of great help!

答:
Mapping directories and files does not mean "mounting" them.

You need to follow 2 steps:

Share the /dev/nvme0n1 to the container

```<code>docker run --cap-add SYS_ADMIN --device /dev/nvme0n1 -it saurabhd04/docker_fio
</code>```

With the container running mount the nvme0n1:

```<code>docker exec <container-id> mount /dev/nvme0n1 /mnt
</code>```

Title: fio: blocksize too large for data set

Body:
Mapping directories and files does not mean "mounting" them.

You need to follow 2 steps:

Share the /dev/nvme0n1 to the container

docker run --cap-add SYS_ADMIN --device /dev/nvme0n1 -it saurabhd04/docker_fio

With the container running mount the nvme0n1:

docker exec <container-id> mount /dev/nvme0n1 /mnt


问:
Invisible field on condition in odoo
I have one field which i want to hide when specific journal selected.

<field name="any_field" attrs="{'invisible':[('journal_id','=',10])]}"/>
```

<p>And For that above code is working fine.</p>

<p>I sure it is not a way to check condition.So, i tried this way.</p>

<pre class="lang-xml prettyprint-override"><code><field name="any_field" attrs="{'invisible':[('journal_id','=',ref('my_module.account_journal_10'))]}"/>
</code>```

It's working then i tried by using the static field on the journal eg. code.

<field name="any_field" attrs="{'invisible':[('journal_id.code','=','CARD')]}"/>
```

<p>But still not working and getting error from view.</p>

<p>I am thinking if i can return the attrs from .py like i do for domain. </p>

<p>eg.</p>

<pre class="lang-py prettyprint-override"><code>return {'domain':
            {
              'any_field':[('journal_id','=',self.env.ref('my_module.account_journal_10').id)]
            }
        }
</code>```

Can anybody help me in this?
Thank you.

答:
As far as i know these attrs domains/filters are client-side so you can't use something like journal_id.code or partner_id.customer, because the client doesn't know about such data.

A possible workaround is to define a related field on the model you're trying to do this. Let's assume the model is my.model and already has this Many2one field journal_id:

journal_code = fields.Char(string="Journal Code", related="journal_id.code")
```

<p>Now you need to extend the view of <code>my.model</code>:</p>

<pre class="lang-xml prettyprint-override"><code><field name="journal_code" invisible="1" />
<field name="any_field" attrs="{'invisible':[('journal_code','=','CARD')]}"/>
</code>```

Title: Invisible field on condition in odoo

Body:
I have one field which i want to hide when specific journal selected.

<field name="any_field" attrs="{'invisible':[('journal_id','=',10])]}"/>

And For that above code is working fine.

I sure it is not a way to check condition.So, i tried this way.

<field name="any_field" attrs="{'invisible':[('journal_id','=',ref('my_module.account_journal_10'))]}"/>

It's working then i tried by using the static field on the journal eg. code.

<field name="any_field" attrs="{'invisible':[('journal_id.code','=','CARD')]}"/>

But still not working and getting error from view.

I am thinking if i can return the attrs from .py like i do for domain.

eg.

return {'domain':
            {
              'any_field':[('journal_id','=',self.env.ref('my_module.account_journal_10').id)]
            }
        }

Can anybody help me in this?
Thank you.

Body:
As far as i know these attrs domains/filters are client-side so you can't use something like journal_id.code or partner_id.customer, because the client doesn't know about such data.

A possible workaround is to define a related field on the model you're trying to do this. Let's assume the model is my.model and already has this Many2one field journal_id:

journal_code = fields.Char(string="Journal Code", related="journal_id.code")

Now you need to extend the view of my.model:

<field name="journal_code" invisible="1" />
<field name="any_field" attrs="{'invisible':[('journal_code','=','CARD')]}"/>