问:
Proper way to add functionality to handle() in a python TCP Server?
I have code like this:

```<code>class SingleTCPHandler(SocketServer.BaseRequestHandler):
    """ One instance per connection. """
    def handle(self):
        data = Net.recv_from_socket(self.request)
        GUI.run(str("RECV'd message: %s" % data))

class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)
</code>```

But I don't want to have to use GUI, a global variable, to contain the function that I want to call when a message is received by my server. Instead I want to send the SingleTCPHandler class the GUI object so it can call the function locally instead of referencing a global variable.

Thoughts? Little new to python...

答:
This is basically the same as the accepted answer, but with less emphasis on the callback. It does not matter if GUI is a callback method or whatever. The problem is how to pass an object to the request handler. The solution is indeed a request handler factory, which receives the GUI (the object) and passes it to the handler when it creates it. Some would suggest to pass the object (GUI) through the server, but it is awkward because the server has nothing to do with it. It does not even look at it. A factory is also more flexible - you could even make the handler dependent upon the request !

The factory will have to pass the object (GUI) in the constructor of the handler, so this constructor needs to be extended (I assume Python 3 - with super()):

```<code>class SingleTCPHandler(SocketServer.BaseRequestHandler):
    """ One instance per connection. """

    def __init__(self, request, client_address, server, GUI):
        # The GUI must be passed before we call the parent constructor
        # because it actually handles the request and finishes it.
        self._GUI = GUI
        super().__init__(request, client_address, server)

    def handle(self):
        data = Net.recv_from_socket(self.request)
        self._GUI.run(str("RECV'd message: %s" % data))
</code>```

BTW, currently, there is no need to subclass SocketServer.BaseRequestHandler as discussed in https://bugs.python.org/issue29947 . I do it, because they suggest it in the documentation, but any handler can be used - no need to provide the setup, handle and finish API. There is no constraint on the handler, except that it must handle the request.  We only need to define the factory method which,  when called by the server, will instantiate the handler (and start it) while passing the GUI object and a connection (the request) to the client:

```<code>class RequestHandlerFactory:
    def __init__(self, GUI):
        self._GUI = GUI

    def start(self, request, client_address, server):
        # The factory could even pass a different handler at each request!
        # The application could change the handler while the server is running!
        return SingleTCPHandler(self, request, client_address, server, self._GUI)
</code>```

These are used in this way:

```<code>factory =  RequestHandlerFactory(GUI)

with ServerUseFactory((HOST, PORT), factory.start) as server:
    server.serve_forever()
</code>```

Body:
I have code like this:

class SingleTCPHandler(SocketServer.BaseRequestHandler):
    """ One instance per connection. """
    def handle(self):
        data = Net.recv_from_socket(self.request)
        GUI.run(str("RECV'd message: %s" % data))

class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)

But I don't want to have to use GUI, a global variable, to contain the function that I want to call when a message is received by my server. Instead I want to send the SingleTCPHandler class the GUI object so it can call the function locally instead of referencing a global variable.

Thoughts? Little new to python...

Body:
This is basically the same as the accepted answer, but with less emphasis on the callback. It does not matter if GUI is a callback method or whatever. The problem is how to pass an object to the request handler. The solution is indeed a request handler factory, which receives the GUI (the object) and passes it to the handler when it creates it. Some would suggest to pass the object (GUI) through the server, but it is awkward because the server has nothing to do with it. It does not even look at it. A factory is also more flexible - you could even make the handler dependent upon the request !

The factory will have to pass the object (GUI) in the constructor of the handler, so this constructor needs to be extended (I assume Python 3 - with super()):

class SingleTCPHandler(SocketServer.BaseRequestHandler):
    """ One instance per connection. """

    def __init__(self, request, client_address, server, GUI):
        # The GUI must be passed before we call the parent constructor
        # because it actually handles the request and finishes it.
        self._GUI = GUI
        super().__init__(request, client_address, server)

    def handle(self):
        data = Net.recv_from_socket(self.request)
        self._GUI.run(str("RECV'd message: %s" % data))

BTW, currently, there is no need to subclass SocketServer.BaseRequestHandler as discussed in https://bugs.python.org/issue29947 . I do it, because they suggest it in the documentation, but any handler can be used - no need to provide the setup, handle and finish API. There is no constraint on the handler, except that it must handle the request.  We only need to define the factory method which,  when called by the server, will instantiate the handler (and start it) while passing the GUI object and a connection (the request) to the client:

class RequestHandlerFactory:
    def __init__(self, GUI):
        self._GUI = GUI

    def start(self, request, client_address, server):
        # The factory could even pass a different handler at each request!
        # The application could change the handler while the server is running!
        return SingleTCPHandler(self, request, client_address, server, self._GUI)

These are used in this way:

factory =  RequestHandlerFactory(GUI)

with ServerUseFactory((HOST, PORT), factory.start) as server:
    server.serve_forever()


来源: stackexchange

问:
Generating random doable math problems swift
I'm looking to create a function that returns a math equation that can be preformed in ones head (Clearly thats a bit subjective but I'm not sure how else to phrase it).

I want to use the operations +,-,*,/,% and ().

Currently I have this function:

```<code>func createMathString() -> String{

let firstNum = Int(arc4random_uniform(300))
let secNum = Int(arc4random_uniform(300))
let exp = Int(arc4random_uniform(4))
print("\(firstNum) \(self.expressions[exp]) \(secNum)")
return "\(firstNum) \(self.expressions[exp]) \(secNum)"

}
</code>```

where self.expression is an array that contains +,-,*,/.

This function returns a string which is then interpreted using this function:

```<code>let question = createMathString()
                let mathExpression = NSExpression(format: question)
                let mathValue = mathExpression.expressionValue(with: nil, context: nil) as? Int
</code>```

My problems:

1) Division and Multiplication get difficult as numbers get higher

2) I'm not sure had to add the ( ). (Not every problem will consist of them, depends on the number of terms.

3) I want the questions to be easy enough to be completed in someones head but not to easy that I'm reducing the random numbers to 0-50.

I looked for a possible API but could not find one that suited my needs.

答:
I started programming with Turbo Pascal and as Niklaus Wirth said: Algorithms + Data Structure = Programs. You need to define data structures appropriate for your program.

First, some basic data structures. (Swift enum is much more powerful than that in other languages)

```<code>enum MathElement : CustomStringConvertible {
    case Integer(value: Int)
    case Percentage(value: Int)
    case Expression(expression: MathExpression)

    var description: String {
        switch self {
        case .Integer(let value): return "\(value)"
        case .Percentage(let percentage): return "\(percentage)%"
        case .Expression(let expr): return expr.description
        }
    }

    var nsExpressionFormatString : String {
        switch self {
        case .Integer(let value): return "\(value).0"
        case .Percentage(let percentage): return "\(Double(percentage) / 100)"
        case .Expression(let expr): return "(\(expr.description))"
        }
    }
}

enum MathOperator : String {
    case plus = "+"
    case minus = "-"
    case multiply = "*"
    case divide = "/"

    static func random() -> MathOperator {
        let allMathOperators: [MathOperator] = [.plus, .minus, .multiply, .divide]
        let index = Int(arc4random_uniform(UInt32(allMathOperators.count)))

        return allMathOperators[index]
    }
}
</code>```

Now the main class:

```<code>class MathExpression : CustomStringConvertible {
    var lhs: MathElement
    var rhs: MathElement
    var `operator`: MathOperator

    init(lhs: MathElement, rhs: MathElement, operator: MathOperator) {
        self.lhs = lhs
        self.rhs = rhs
        self.operator = `operator`
    }

    var description: String {
        var leftString = ""
        var rightString = ""

        if case .Expression(_) = lhs {
            leftString = "(\(lhs))"
        } else {
            leftString = lhs.description
        }
        if case .Expression(_) = rhs {
            rightString = "(\(rhs))"
        } else {
            rightString = rhs.description
        }

        return "\(leftString) \(self.operator.rawValue) \(rightString)"
    }

    var result : Any? {
        let format = "\(lhs.nsExpressionFormatString) \(`operator`.rawValue) \(rhs.nsExpressionFormatString)"
        let expr = NSExpression(format: format)
        return expr.expressionValue(with: nil, context: nil)
    }

    static func random() -> MathExpression {
        let lhs = MathElement.Integer(value: Int(arc4random_uniform(10)))
        let rhs = MathElement.Integer(value: Int(arc4random_uniform(10)))

        return MathExpression(lhs: lhs, rhs: rhs, operator: .random())
    }
}
</code>```

Usage:

```<code>let a = MathExpression(lhs: .Integer(value: 1), rhs: .Integer(value: 2), operator: .divide)
let b = MathExpression(lhs: .Integer(value: 10), rhs: .Percentage(value: 20), operator: .minus)
let c = MathExpression.random()

let d = MathExpression(lhs: .Integer(value: 1), rhs: .Integer(value: 2), operator: .plus)
let e = MathExpression(lhs: .Integer(value: 3), rhs: .Integer(value: 4), operator: .plus)
let f = MathExpression(lhs: .Expression(expression: d), rhs: .Expression(expression: e), operator: .multiply)

let x = MathExpression.random()
let y = MathExpression.random()
let z = MathExpression(lhs: .Expression(expression: x), rhs: .Expression(expression: y), operator: .plus)

print("a: \(a) = \(a.result!)")
print("b: \(b) = \(b.result!)")
print("c: \(c) = \(c.result!)")

print("f: \(f) = \(f.result!)") // the classic (1 + 2) * (3 + 4)
print("z: \(z) = \(z.result!)") // this is completely random
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to create a function that returns a math equation that can be preformed in ones head (Clearly thats a bit subjective but I'm not sure how else to phrase it).

I want to use the operations +,-,*,/,% and ().

Currently I have this function:

func createMathString() -> String{

let firstNum = Int(arc4random_uniform(300))
let secNum = Int(arc4random_uniform(300))
let exp = Int(arc4random_uniform(4))
print("\(firstNum) \(self.expressions[exp]) \(secNum)")
return "\(firstNum) \(self.expressions[exp]) \(secNum)"

}

where self.expression is an array that contains +,-,*,/.

This function returns a string which is then interpreted using this function:

let question = createMathString()
                let mathExpression = NSExpression(format: question)
                let mathValue = mathExpression.expressionValue(with: nil, context: nil) as? Int

My problems:

1) Division and Multiplication get difficult as numbers get higher

2) I'm not sure had to add the ( ). (Not every problem will consist of them, depends on the number of terms.

3) I want the questions to be easy enough to be completed in someones head but not to easy that I'm reducing the random numbers to 0-50.

I looked for a possible API but could not find one that suited my needs.

Body:
I started programming with Turbo Pascal and as Niklaus Wirth said: Algorithms + Data Structure = Programs. You need to define data structures appropriate for your program.

First, some basic data structures. (Swift enum is much more powerful than that in other languages)

enum MathElement : CustomStringConvertible {
    case Integer(value: Int)
    case Percentage(value: Int)
    case Expression(expression: MathExpression)

    var description: String {
        switch self {
        case .Integer(let value): return "\(value)"
        case .Percentage(let percentage): return "\(percentage)%"
        case .Expression(let expr): return expr.description
        }
    }

    var nsExpressionFormatString : String {
        switch self {
        case .Integer(let value): return "\(value).0"
        case .Percentage(let percentage): return "\(Double(percentage) / 100)"
        case .Expression(let expr): return "(\(expr.description))"
        }
    }
}

enum MathOperator : String {
    case plus = "+"
    case minus = "-"
    case multiply = "*"
    case divide = "/"

    static func random() -> MathOperator {
        let allMathOperators: [MathOperator] = [.plus, .minus, .multiply, .divide]
        let index = Int(arc4random_uniform(UInt32(allMathOperators.count)))

        return allMathOperators[index]
    }
}

Now the main class:

class MathExpression : CustomStringConvertible {
    var lhs: MathElement
    var rhs: MathElement
    var `operator`: MathOperator

    init(lhs: MathElement, rhs: MathElement, operator: MathOperator) {
        self.lhs = lhs
        self.rhs = rhs
        self.operator = `operator`
    }

    var description: String {
        var leftString = ""
        var rightString = ""

        if case .Expression(_) = lhs {
            leftString = "(\(lhs))"
        } else {
            leftString = lhs.description
        }
        if case .Expression(_) = rhs {
            rightString = "(\(rhs))"
        } else {
            rightString = rhs.description
        }

        return "\(leftString) \(self.operator.rawValue) \(rightString)"
    }

    var result : Any? {
        let format = "\(lhs.nsExpressionFormatString) \(`operator`.rawValue) \(rhs.nsExpressionFormatString)"
        let expr = NSExpression(format: format)
        return expr.expressionValue(with: nil, context: nil)
    }

    static func random() -> MathExpression {
        let lhs = MathElement.Integer(value: Int(arc4random_uniform(10)))
        let rhs = MathElement.Integer(value: Int(arc4random_uniform(10)))

        return MathExpression(lhs: lhs, rhs: rhs, operator: .random())
    }
}

Usage:

let a = MathExpression(lhs: .Integer(value: 1), rhs: .Integer(value: 2), operator: .divide)
let b = MathExpression(lhs: .Integer(value: 10), rhs: .Percentage(value: 20), operator: .minus)
let c = MathExpression.random()

let d = MathExpression(lhs: .Integer(value: 1), rhs: .Integer(value: 2), operator: .plus)
let e = MathExpression(lhs: .Integer(value: 3), rhs: .Integer(value: 4), operator: .plus)
let f = MathExpression(lhs: .Expression(expression: d), rhs: .Expression(expression: e), operator: .multiply)

let x = MathExpression.random()
let y = MathExpression.random()
let z = MathExpression(lhs: .Expression(expression: x), rhs: .Expression(expression: y), operator: .plus)

print("a: \(a) = \(a.result!)")
print("b: \(b) = \(b.result!)")
print("c: \(c) = \(c.result!)")

print("f: \(f) = \(f.result!)") // the classic (1 + 2) * (3 + 4)
print("z: \(z) = \(z.result!)") // this is completely random


问:
search box result click and render html page
Hello I am building a website.

Problem is that in the search bar, when I type something I get this automatic list of available search queries as seen in the picture.
enter image description here
What I want is that when I see this list and click "AAPL: Apple Inc." then I want to render a html page named "aapl.html" I don't know how should I approach.
My html code for the search box is below

```<code>    <div class="searchbox">

        <!-- /.row -->

        <!-- Search Box -->
        <div class="container" style="max-width: 700px;">

                <h2 style="margin-bottom: -20px;"><kbd style="background-color: #0E6251; font-size: 20px;">text text some text</kbd>
                </h2>
                <h2><kbd style="background-color: #0E6251; font-size: 20px;">text text some text</kbd></h2>

                        <div class="panel panel-default" style="margin-bottom: 13px;">
                            <!-- Default panel contents -->

                            <div class="panel-heading">

                                <div class="input-group" style="margin-left: -3px; margin-right: -3px;">

                                    <input type="hidden" name="search_param" value="name" id="search_param">
                                    <input id="searchText"type="text" class="form-control" name="q" placeholder="Ticker here :)    e.g. AAPL or Apple Inc." id="search_key" value="">
                                    <span class="input-group-btn">

                                        <button class="btn btn-danger" type="submit">  Search  </button>
                                    </span>

                                </div>

                            </div>

                            <!-- List group -->
                            <ul id="autolist" class="list-group">
                                <div id="autocompleteTest">
                                </div>
                            </ul>

                        </div>
            <div class="row">
                <div class="col-md-2">
                    <div class="">
                        <ul id="autocompleteTest">

                        </ul>
                    </div>
                </div>
            </div>
        </div>

    </div>
    <!-- /.container -->
</code>```

and javascript for this search box to work is below

```<code>$(document).ready(function () {
    $("#searchText").click(function () {
        $("#x").removeClass('hide');
    });
    $(".list-group-item").hover(function () {
        $(this,".list-group-item").css('background-color','rgba(172, 172, 172, 0.11)');

    },function () {
        $(this,".list-group-item").css('background-color','white');
    });

    $("#searchText").on( "trigger", function () {
        if ($( "#searchText" ).val()==''){
            $('#autocompleteTest').empty();
        }
        return false;
    } );
    $("#autocompleteTest").empty();
    var availableTags = [
        "AAPL : Apple Inc.",
        "Grisel Salmons",
        "Loree Pollak",
        "Kena Vanhorne",
        "Rodger Reuben",
        "Karen Mccutcheon",
        "Lourdes Newnam",
        "Cher Gershon",
        "Wava Hiers",
        "Georgine Gillette",
        "Marquetta Trotter"
    ];
    $('#searchText').autocomplete({
        search: function(event, ui) {
            $('#autocompleteTest').empty();
            $("#x").removeClass('hide')
        },
        close:function(){
            if ($('#searchText').val()==''){
                $('#autocompleteTest').empty();
            }
            $("#x").addClass('hide')
        },
        minLength: 1,
        source: availableTags
    }).data('ui-autocomplete')._renderItem = function(ul, item) {
        return $('<div/>')
            .data('ui-autocomplete-item', item)
            .append("<li class='list-group-item'> <div class='row'> <div class='col-md-12'> <div class='media-left media-middle'> <a href='#'> <img class='media-object img-circle' src='http://placehold.it/40x40'> </a> </div> <div id='center'>" + item.value + "<div id='center' class='material-switch pull-right'> <input id='"+item.value+"' name='someSwitchOption001i' type='checkbox'/> <label for='"+item.value+"' class='label-primary'></label> </div> </div> </div> </div> </li>")
            .appendTo($('#autocompleteTest'));
    };
    $("#x").on("click",function () {
        $("#searchText").val('');

    })
});
</code>```

I just want to render a html page (aapl.html) when I click the search result of AAPL: Apple Inc. How should I do this?

Please help me.

答:
Never mind, I have figured out how to do.
This is my previous javascript code. Fourth line when appending some html code,
I got the item.value and split it with ":" and take the first element of the split item.value which is AAPL. and make it lowercase --> aapl, and then put it in the  .

```<code>}).data('ui-autocomplete')._renderItem = function(ul, item) {
        return $('<div/>')
            .data('ui-autocomplete-item', item)
            .append("<li class='list-group-item'> <div class='row'> <div class='col-md-12'> <div class='media-left media-middle'> <a href='#'> <img class='media-object img-circle' src='http://placehold.it/40x40'> </a> </div> <div id='center'>" + item.value + "<div id='center' class='material-switch pull-right'> <input id='"+item.value+"' name='someSwitchOption001i' type='checkbox'/> <label for='"+item.value+"' class='label-primary'></label> </div> </div> </div> </div> </li>")
            .appendTo($('#autocompleteTest'));
    };
    $("#x").on("click",function () {
        $("#searchText").val('');

    })
});
</code>```

edited code:

```<code> }).data('ui-autocomplete')._renderItem = function(ul, item) {
        return $('<div/>')
            .data('ui-autocomplete-item', item)
            .append("<li class='list-group-item'> <div class='row'> <div class='col-md-12'> <div class='media-left media-middle'> <a href='#'> <img class='media-object img-circle' src='http://placehold.it/40x40'> </a> </div> <div id='center'>" + "<a href=/analytics/signals/"+ item.value.split(":")[0].toLowerCase() + ">" +item.value+ "</a>"+ " </div> </div> </div> </li>")
            .appendTo($('#autocompleteTest'));
    };
    $("#x").on("click",function () {
        $("#searchText").val('');

    })
});
</code>```

Body:
Hello I am building a website.

Problem is that in the search bar, when I type something I get this automatic list of available search queries as seen in the picture.
enter image description here
What I want is that when I see this list and click "AAPL: Apple Inc." then I want to render a html page named "aapl.html" I don't know how should I approach.
My html code for the search box is below

text text some text

text text some text

                                    <input type="hidden" name="search_param" value="name" id="search_param">
                                    <input id="searchText"type="text" class="form-control" name="q" placeholder="Ticker here :)    e.g. AAPL or Apple Inc." id="search_key" value="">

                                        <button class="btn btn-danger" type="submit">  Search  </button>

and javascript for this search box to work is below

$(document).ready(function () {
    $("#searchText").click(function () {
        $("#x").removeClass('hide');
    });
    $(".list-group-item").hover(function () {
        $(this,".list-group-item").css('background-color','rgba(172, 172, 172, 0.11)');

    },function () {
        $(this,".list-group-item").css('background-color','white');
    });

    $("#searchText").on( "trigger", function () {
        if ($( "#searchText" ).val()==''){
            $('#autocompleteTest').empty();
        }
        return false;
    } );
    $("#autocompleteTest").empty();
    var availableTags = [
        "AAPL : Apple Inc.",
        "Grisel Salmons",
        "Loree Pollak",
        "Kena Vanhorne",
        "Rodger Reuben",
        "Karen Mccutcheon",
        "Lourdes Newnam",
        "Cher Gershon",
        "Wava Hiers",
        "Georgine Gillette",
        "Marquetta Trotter"
    ];
    $('#searchText').autocomplete({
        search: function(event, ui) {
            $('#autocompleteTest').empty();
            $("#x").removeClass('hide')
        },
        close:function(){
            if ($('#searchText').val()==''){
                $('#autocompleteTest').empty();
            }
            $("#x").addClass('hide')
        },
        minLength: 1,
        source: availableTags
    }).data('ui-autocomplete')._renderItem = function(ul, item) {
        return $('
')
            .data('ui-autocomplete-item', item)
            .append("

" + item.value + "
 <input id='"+item.value+"' name='someSwitchOption001i' type='checkbox'/>

")
            .appendTo($('#autocompleteTest'));
    };
    $("#x").on("click",function () {
        $("#searchText").val('');

    })
});

I just want to render a html page (aapl.html) when I click the search result of AAPL: Apple Inc. How should I do this?

Please help me.

Body:
Never mind, I have figured out how to do.
This is my previous javascript code. Fourth line when appending some html code,
I got the item.value and split it with ":" and take the first element of the split item.value which is AAPL. and make it lowercase --> aapl, and then put it in the  .

}).data('ui-autocomplete')._renderItem = function(ul, item) {
        return $('<div/>')
            .data('ui-autocomplete-item', item)
            .append("<li class='list-group-item'> <div class='row'> <div class='col-md-12'> <div class='media-left media-middle'> <a href='#'> <img class='media-object img-circle' src='http://placehold.it/40x40'> </a> </div> <div id='center'>" + item.value + "<div id='center' class='material-switch pull-right'> <input id='"+item.value+"' name='someSwitchOption001i' type='checkbox'/> <label for='"+item.value+"' class='label-primary'></label> </div> </div> </div> </div> </li>")
            .appendTo($('#autocompleteTest'));
    };
    $("#x").on("click",function () {
        $("#searchText").val('');

    })
});

edited code:

 }).data('ui-autocomplete')._renderItem = function(ul, item) {
        return $('<div/>')
            .data('ui-autocomplete-item', item)
            .append("<li class='list-group-item'> <div class='row'> <div class='col-md-12'> <div class='media-left media-middle'> <a href='#'> <img class='media-object img-circle' src='http://placehold.it/40x40'> </a> </div> <div id='center'>" + "<a href=/analytics/signals/"+ item.value.split(":")[0].toLowerCase() + ">" +item.value+ "</a>"+ " </div> </div> </div> </li>")
            .appendTo($('#autocompleteTest'));
    };
    $("#x").on("click",function () {
        $("#searchText").val('');

    })
});


问:
How to use variable from a while (foreach) statement in a query?
I have this first query

```<code> <?php
       while($empsheetpanel=mysqli_fetch_array($resultempsheets)){

 ?>
</code>```

Under that I have placed this second query in order to get data from the first query

```<code> <?php
 $sql="SELECT * From my_table WHERE id="$empsheetpanel['employee_id']" ";
 $result=mysqli_query($db,$sql);
 ?>
<?php } ;?>
</code>```

I know this is improper and incorrect. What's the correct syntax to retrieve the $empsheetpanel['employee_id'] from the first query?

答:
use join like this</p>

```<code>"SELECT t1.*,t2.column name FROM table1 t1 JOIN table2 t2 ON t1.id=t2.employee_id "
</code>```

Body:
I have this first query

 <?php
       while($empsheetpanel=mysqli_fetch_array($resultempsheets)){

 ?>

Under that I have placed this second query in order to get data from the first query

 <?php
 $sql="SELECT * From my_table WHERE id="$empsheetpanel['employee_id']" ";
 $result=mysqli_query($db,$sql);
 ?>
<?php } ;?>

I know this is improper and incorrect. What's the correct syntax to retrieve the $empsheetpanel['employee_id'] from the first query?

Body:
use join like this

"SELECT t1.*,t2.column name FROM table1 t1 JOIN table2 t2 ON t1.id=t2.employee_id "


问:
Charset changes after uploading a file in a Java environment under Apache HTTP
I have a project running in a standalone WildFly that is working fine locally under Eclipse, but the same project running on WildFly in a remote server under Apache HTTP is getting special characters corrupted after submitting a file. For example:

Before submit a file:

After submit a file:

OS: Linux

Using: JSF 2.2, Java 8, WildFly 10 and Apache HTTP 2.4

All the XHTML files are encoded with UTF-8 and the head contains the meta tag:

```<code><meta http-equiv="restrict-type" content="text/html; charset=UTF-8" />
</code>```

I've already tried:

→ Form with the 'charset' param in the enctype attribute:

```<code><h:form id="fileForm" enctype="multipart/form-data;charset=UTF-8">
</code>```

→ Running WildFly with the argument:

```<code>-Dfile.encoding=UTF-8
</code>```

→ Enable the following option in httpd.conf:

```<code>AddDefaultCharset UTF-8
</code>```

I don't know what I'm missing... Did anyone know a solution to this problem? I would appreciate any help. Thank you in advance and sorry for the bad English.

答:
After turning off Apache HTTP and acessing the system by IP:port the problem was still there.

Then I found a solution here:
https://rogerkeays.com/servletrequest-setcharactercoding-ignored

I think a third-party lib was causing the damage, maybe it was the PrimeFaces Upload Filter. Now it works as expected after uploading a file.

Body:
I have a project running in a standalone WildFly that is working fine locally under Eclipse, but the same project running on WildFly in a remote server under Apache HTTP is getting special characters corrupted after submitting a file. For example:

Before submit a file:

After submit a file:

OS: Linux

Using: JSF 2.2, Java 8, WildFly 10 and Apache HTTP 2.4

All the XHTML files are encoded with UTF-8 and the head contains the meta tag:

<meta http-equiv="restrict-type" content="text/html; charset=UTF-8" />

I've already tried:

→ Form with the 'charset' param in the enctype attribute:

<h:form id="fileForm" enctype="multipart/form-data;charset=UTF-8">

→ Running WildFly with the argument:

-Dfile.encoding=UTF-8

→ Enable the following option in httpd.conf:

AddDefaultCharset UTF-8

I don't know what I'm missing... Did anyone know a solution to this problem? I would appreciate any help. Thank you in advance and sorry for the bad English.


问:
Firebase query where the key/value pair im looking for sits under an unknown ref
Here is the Firebase ref structure that i want to query:

```<code>- someData
    -KgWw4iasffsD-vht3QA   <=== Firebase generated key
        - fieldA: '12345'
        - fieldB: 'here it is'
</code>```

I want to query, key eg. fieldB, and test its value. eg. fieldB = 'there it was'

Here's what i tried but ive got syntax wrong:

```<code>var theRef = firebase.database().ref('someData').equalTo({fieldB: 'there it was'});
</code>```

How can i do this ? Thanks for your help.

答:
Yes, you can use orderByChild and equalTo to create a query ref:

var theRef = firebase.database()
  .ref('someData')
  .orderByChild('fieldB')
  .equalTo('there it was');
```

<p>Note that you will need to create an index using the Firebase Security Rules. Otherwise, all of the data under <code>someData</code> will be retrieved and the query will be performed on the client.</p>

<p>To perform the query once, you would do something like this:</p>

<pre class="lang-js prettyprint-override"><code>theRef.once('value',
  function (snapshot) {
    snapshot.forEach(function (child) {
      console.log(child.key, child.val());
    });
  },
  function (error) {
    console.log(error);
  }
);
</code>```

Or, using the returned Promise:

theRef.once('value')
  .then(function (snapshot) {
    snapshot.forEach(function (child) {
      console.log(child.key, child.val());
    });
  })
  .catch(function (error) {
    console.log(error);
  });
```

<p>Or, to query the data and continue listening for changes, you would do something like this:</p>

<pre class="lang-js prettyprint-override"><code>theRef.on('value',
  function (snapshot) {
    snapshot.forEach(function (child) {
      console.log(child.key, child.val());
    });
  },
  function (error) {
    console.log(error);
  }
);
</code>```

Body:
Here is the Firebase ref structure that i want to query:

- someData
    -KgWw4iasffsD-vht3QA   <=== Firebase generated key
        - fieldA: '12345'
        - fieldB: 'here it is'

I want to query, key eg. fieldB, and test its value. eg. fieldB = 'there it was'

Here's what i tried but ive got syntax wrong:

var theRef = firebase.database().ref('someData').equalTo({fieldB: 'there it was'});

How can i do this ? Thanks for your help.

Body:
Yes, you can use orderByChild and equalTo to create a query ref:

var theRef = firebase.database()
  .ref('someData')
  .orderByChild('fieldB')
  .equalTo('there it was');

Note that you will need to create an index using the Firebase Security Rules. Otherwise, all of the data under someData will be retrieved and the query will be performed on the client.

To perform the query once, you would do something like this:

theRef.once('value',
  function (snapshot) {
    snapshot.forEach(function (child) {
      console.log(child.key, child.val());
    });
  },
  function (error) {
    console.log(error);
  }
);

Or, using the returned Promise:

theRef.once('value')
  .then(function (snapshot) {
    snapshot.forEach(function (child) {
      console.log(child.key, child.val());
    });
  })
  .catch(function (error) {
    console.log(error);
  });

Or, to query the data and continue listening for changes, you would do something like this:

theRef.on('value',
  function (snapshot) {
    snapshot.forEach(function (child) {
      console.log(child.key, child.val());
    });
  },
  function (error) {
    console.log(error);
  }
);


问:
Orderby after select clause in C#
I have a VB .Net query which im attempting to convert to C#. I thought i did it correctly but my attempt in C# results in no data returned where as the VB code does return data (both coming from the same data source)

```<code>Dim MyQuery = From s In MyContext.StudentPlacements _
                    Where (s.StudentLocation.URL = StudentUrl) _
                          Select s _
                         Order By s.Id Descending, MyContext.GenerateRandomId
</code>```

C#

```<code>IQueryable<StudentPlacement> MyQuery = from s in MyContext.StudentPlacements
                            where (s.StudentLocation.URL == StudentUrl)
                            orderby s.Id descending, MyContext.GenerateRandomId()
                            select s;
</code>```

So i searched to see if i could add an orderby after the select in C# but all my attempts didnt seem to work. I dont think you can have an order by after the select in C#? I tried to change my C# code to use a dynamic variable but that didnt do the trick. Used an online converter which gave something different but it didnt compile.

Any idea how i could achieve the same code in C#?

答:
The VB.Net does case insensitive comparisons for texts so the VB statement

```<code>s.StudentLocation.URL = StudentUrl
</code>```

Returns different results from the same statement in C#

```<code>s.StudentLocation.URL == StudentUrl
</code>```

Use

```<code>s.StudentLocation.URL.ToUpper() == StudentUrl.ToUpper()
</code>```

OR

```<code> s.StudentLocation.URL.Equals(StudentUrl,StringComparison.OrdinalIgnoreCase)
</code>```

Title: Orderby after select clause in C#

Body:
I have a VB .Net query which im attempting to convert to C#. I thought i did it correctly but my attempt in C# results in no data returned where as the VB code does return data (both coming from the same data source)

Dim MyQuery = From s In MyContext.StudentPlacements _
                    Where (s.StudentLocation.URL = StudentUrl) _
                          Select s _
                         Order By s.Id Descending, MyContext.GenerateRandomId

C#

IQueryable<StudentPlacement> MyQuery = from s in MyContext.StudentPlacements
                            where (s.StudentLocation.URL == StudentUrl)
                            orderby s.Id descending, MyContext.GenerateRandomId()
                            select s;

So i searched to see if i could add an orderby after the select in C# but all my attempts didnt seem to work. I dont think you can have an order by after the select in C#? I tried to change my C# code to use a dynamic variable but that didnt do the trick. Used an online converter which gave something different but it didnt compile.

Any idea how i could achieve the same code in C#?

Body:
The VB.Net does case insensitive comparisons for texts so the VB statement

s.StudentLocation.URL = StudentUrl

Returns different results from the same statement in C#

s.StudentLocation.URL == StudentUrl

Use

s.StudentLocation.URL.ToUpper() == StudentUrl.ToUpper()

OR

 s.StudentLocation.URL.Equals(StudentUrl,StringComparison.OrdinalIgnoreCase)


问:
Find how many arrays with valid keys in multidimensional array in php
I need to know how many arrays have valid keys, how many arrays with valid keys in multidimensional array. Let me explain:

Input:

```<code>Array
(
    [65] => Array
        (
            [1] => Array
                (
                    [0] => Array
                        (
                            [mediumid] => 65
                            [mediumname] => VINYL
                            [trackid] => 525
                            [trackposition] => 1
                            [tracklocation] => SIDE A
                            [tracknumber] => 1
                            [trackname] => I love u
                        )

                    [1] => Array
                        (
                            [mediumid] => 65
                            [mediumname] => VINYL
                            [trackid] => 526
                            [trackposition] => 1
                            [tracklocation] => SIDE A
                            [tracknumber] => 2
                            [trackname] => Sun is yellow
                        )

                )

            [2] => Array
                (
                    [0] => Array
                        (
                            [mediumid] => 65
                            [mediumname] => VINYL
                            [trackid] => 527
                            [trackposition] => 2
                            [tracklocation] => SIDE B
                            [tracknumber] => 1
                            [trackname] => Car red
                        )

                    [1] => Array
                        (
                            [mediumid] => 65
                            [mediumname] => VINYL
                            [trackid] => 528
                            [trackposition] => 2
                            [tracklocation] => SIDE B
                            [tracknumber] => 2
                            [trackname] => Lady in red
                        )

                )

        )

     [769] => Array
        (
            [] => Array
                (
                    [0] => Array
                        (
                            [mediumid] => 769
                            [mediumname] => DVD
                            [trackid] =>
                            [trackposition] =>
                            [tracklocation] =>
                            [tracknumber] =>
                            [trackname] =>
                        )
                )
        )
    )
</code>```

The mediums[65] next array contains 2 valid keys (1 and 2). The mediums[769] next array contains no valid keys

Therefore only mediums[65] contains valid keys, so total of arrays with valid keys = 1.
I need to find that total. How ?

I've try using array_keys and array_filter, with no success (or either i'm doing it wrong)

答:
PHP code demo</p>

```<code><?php
$array=Array
(
    65 => Array
        (
            1 => Array
                (
                    0 => Array
                        (
                            "mediumid" => 65,
                            "mediumname" => "VINYL",
                            "trackid" => 525,
                            "trackposition" => 1,
                            "tracklocation" => "SIDE A",
                            "tracknumber" => 1,
                            "trackname" => "I love u"
                        ),

                    1 => Array
                        (
                            "mediumid" => 65,
                            "mediumname" => "VINYL",
                            "trackid" => 526,
                            "trackposition" => 1,
                            "tracklocation" => "SIDE A",
                            "tracknumber" => 2,
                            "trackname" =>"Sun is yellow"
                        )

                ),

            2 => Array
                (
                    0 => Array
                        (
                            "mediumid" => 65,
                            "mediumname" => "VINYL",
                            "trackid" => 527,
                            "trackposition" => 2,
                            "tracklocation" => "SIDE B",
                            "tracknumber" => 1,
                            "trackname" => "Car red"
                        ),

                    1 => Array
                        (
                            "mediumid" => 65,
                            "mediumname" => "VINYL",
                            "trackid" => 528,
                            "trackposition" => 2,
                            "tracklocation" => "SIDE B",
                            "tracknumber" => 2,
                            "trackname" => "Lady in red"
                        )

                )

        ),

     769 => Array
        (
           ""  => Array
                (
                    0 => Array
                        (
                            "mediumid" => 769,
                            "mediumname" => "DVD",
                            "trackid" => "",
                            "trackposition" => "",
                            "tracklocation" => "",
                            "tracknumber" =>"",
                            "trackname" => ""
                        )
                )
        )
    );
$counter=0;
$trackedNull=false;
foreach($array as $key => $value)
{
    $keys=array_keys($array[$key]);
    foreach($keys as $arraykey)
    {
        if($arraykey=="")
        {
            $trackedNull=true;
            break;
        }
    }
    if($trackedNull==true)
    {
        $trackedNull=false;
    }
    else
    {
        $counter++;
    }
}
echo $counter;
</code>```

Body:
I need to know how many arrays have valid keys, how many arrays with valid keys in multidimensional array. Let me explain:

Input:

Array
(
    [65] => Array
        (
            [1] => Array
                (
                    [0] => Array
                        (
                            [mediumid] => 65
                            [mediumname] => VINYL
                            [trackid] => 525
                            [trackposition] => 1
                            [tracklocation] => SIDE A
                            [tracknumber] => 1
                            [trackname] => I love u
                        )

                    [1] => Array
                        (
                            [mediumid] => 65
                            [mediumname] => VINYL
                            [trackid] => 526
                            [trackposition] => 1
                            [tracklocation] => SIDE A
                            [tracknumber] => 2
                            [trackname] => Sun is yellow
                        )

                )

            [2] => Array
                (
                    [0] => Array
                        (
                            [mediumid] => 65
                            [mediumname] => VINYL
                            [trackid] => 527
                            [trackposition] => 2
                            [tracklocation] => SIDE B
                            [tracknumber] => 1
                            [trackname] => Car red
                        )

                    [1] => Array
                        (
                            [mediumid] => 65
                            [mediumname] => VINYL
                            [trackid] => 528
                            [trackposition] => 2
                            [tracklocation] => SIDE B
                            [tracknumber] => 2
                            [trackname] => Lady in red
                        )

                )

        )

     [769] => Array
        (
            [] => Array
                (
                    [0] => Array
                        (
                            [mediumid] => 769
                            [mediumname] => DVD
                            [trackid] =>
                            [trackposition] =>
                            [tracklocation] =>
                            [tracknumber] =>
                            [trackname] =>
                        )
                )
        )
    )

The mediums[65] next array contains 2 valid keys (1 and 2). The mediums[769] next array contains no valid keys

Therefore only mediums[65] contains valid keys, so total of arrays with valid keys = 1.
I need to find that total. How ?

I've try using array_keys and array_filter, with no success (or either i'm doing it wrong)

Body:
PHP code demo

<?php
$array=Array
(
    65 => Array
        (
            1 => Array
                (
                    0 => Array
                        (
                            "mediumid" => 65,
                            "mediumname" => "VINYL",
                            "trackid" => 525,
                            "trackposition" => 1,
                            "tracklocation" => "SIDE A",
                            "tracknumber" => 1,
                            "trackname" => "I love u"
                        ),

                    1 => Array
                        (
                            "mediumid" => 65,
                            "mediumname" => "VINYL",
                            "trackid" => 526,
                            "trackposition" => 1,
                            "tracklocation" => "SIDE A",
                            "tracknumber" => 2,
                            "trackname" =>"Sun is yellow"
                        )

                ),

            2 => Array
                (
                    0 => Array
                        (
                            "mediumid" => 65,
                            "mediumname" => "VINYL",
                            "trackid" => 527,
                            "trackposition" => 2,
                            "tracklocation" => "SIDE B",
                            "tracknumber" => 1,
                            "trackname" => "Car red"
                        ),

                    1 => Array
                        (
                            "mediumid" => 65,
                            "mediumname" => "VINYL",
                            "trackid" => 528,
                            "trackposition" => 2,
                            "tracklocation" => "SIDE B",
                            "tracknumber" => 2,
                            "trackname" => "Lady in red"
                        )

                )

        ),

     769 => Array
        (
           ""  => Array
                (
                    0 => Array
                        (
                            "mediumid" => 769,
                            "mediumname" => "DVD",
                            "trackid" => "",
                            "trackposition" => "",
                            "tracklocation" => "",
                            "tracknumber" =>"",
                            "trackname" => ""
                        )
                )
        )
    );
$counter=0;
$trackedNull=false;
foreach($array as $key => $value)
{
    $keys=array_keys($array[$key]);
    foreach($keys as $arraykey)
    {
        if($arraykey=="")
        {
            $trackedNull=true;
            break;
        }
    }
    if($trackedNull==true)
    {
        $trackedNull=false;
    }
    else
    {
        $counter++;
    }
}
echo $counter;


问:
WordPress, removing comments block programmatically
I want to remove Word Press comment block from specified 'n' posts. These posts are generated dynamically and don't want comment block</p>

答:
The comment block of items is in listing files the articles of the mainpage or of each of the categories you have created.
Check out the archive /index.php in your Wordpress and see the HTML comment block.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Why my bigrams are still considering stopwords?
The result still consider stopwords...
Few lines of my txt:

Sensacional, uma das melhores remakes de animação sai do cinema emocionado, absurdamente lindo, insensibilidade de quem reclama do musical, lindo demais.
(...)o filme depende muito da nostalgia da animação para funcionar. E apesar de ser eficaz, somente esse sentimento não sustenta o longa sozinho para dizer que esta obra tenha qualidade e refinamento cinematográficos.(...)A Bela e a Fera acerta em tornar a sua história ainda extremamente relevante nos dias atuais, e se de um lado inova o seu contexto social, por outro lado a falta de originalidade compromete que a obra seja mais impactante.

Reding txt

```<code>data <- read_tsv("bela.txt", locale = locale(encoding = "latin1"))
</code>```

Making a corpus

```<code>datacorpus <- VCorpus(VectorSource(data))

datacorpus <- tm_map(datacorpus, PlainTextDocument)

datacorpus <- tm_map(datacorpus, removePunctuation)

datacorpus <- tm_map(datacorpus, removeWords, stopwords('pt'))

BigramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 2, max = 2))

tdm <- TermDocumentMatrix(datacorpus,control=list(removePunctuation = TRUE,
                                       stopwords = stopwords('pt'),
                                       removeNumbers = TRUE,
                                       tokenize = BigramTokenizer))

m <- as.matrix(tdm)
v <- sort(rowSums(m),decreasing=TRUE)
d <- data.frame(word = names(v),freq=v)
head(d, 10)

set.seed(1234)
wordcloud(words = d$word, freq = d$freq, min.freq = 1,
      max.words=200, random.order=FALSE, rot.per=0.35,
      colors=brewer.pal(8, "Dark2"))
</code>```

![enter image description here][1]
[1]: https://i.stack.imgur.com/Uu67O.jpg

答:
Assuming you mean you want to drop bigrams that contain a stop word, using the tidytext package, you could do

library(dplyr)
library(tidytext)

set.seed(47)

data_frame(text = 'Sensacional, uma das melhores remakes de animação sai do cinema emocionado, absurdamente lindo, insensibilidade de quem reclama do musical, lindo demais. (...)o filme depende muito da nostalgia da animação para funcionar. E apesar de ser eficaz, somente esse sentimento não sustenta o longa sozinho para dizer que esta obra tenha qualidade e refinamento cinematográficos.(...)A Bela e a Fera acerta em tornar a sua história ainda extremamente relevante nos dias atuais, e se de um lado inova o seu contexto social, por outro lado a falta de originalidade compromete que a obra seja mais impactante.') %>%
    unnest_tokens(bigram, text, 'ngrams', n = 2) %>%    # tokenize bigrams
    mutate(i = row_number()) %>%    # add index for later grouping
    unnest_tokens(word, bigram, drop = FALSE) %>%    # tokenize bigrams into words
    anti_join(data_frame(word = tm::stopwords('pt'))) %>%    # drop rows with stop words
    group_by(i) %>%    # group by bigram index
    filter(n() == 2) %>%    # drop bigram instances where only one word left
    summarise(bigram = unique(bigram)) %>%    # collapse groups to single bigram each
    count(bigram) %>%
    { wordcloud::wordcloud(.$bigram, .$n, min.freq = 1, scale = c(1, .2), rot.per = .35,
                           colors = RColorBrewer::brewer.pal(8, 'Dark2')) }
```

Colors don't work here because there's a single occurrence of each, but should work fine at scale.

Body:
The result still consider stopwords...
Few lines of my txt:

Sensacional, uma das melhores remakes de animação sai do cinema emocionado, absurdamente lindo, insensibilidade de quem reclama do musical, lindo demais.
(...)o filme depende muito da nostalgia da animação para funcionar. E apesar de ser eficaz, somente esse sentimento não sustenta o longa sozinho para dizer que esta obra tenha qualidade e refinamento cinematográficos.(...)A Bela e a Fera acerta em tornar a sua história ainda extremamente relevante nos dias atuais, e se de um lado inova o seu contexto social, por outro lado a falta de originalidade compromete que a obra seja mais impactante.

Reding txt

data <- read_tsv("bela.txt", locale = locale(encoding = "latin1"))

Making a corpus

datacorpus <- VCorpus(VectorSource(data))

datacorpus <- tm_map(datacorpus, PlainTextDocument)

datacorpus <- tm_map(datacorpus, removePunctuation)

datacorpus <- tm_map(datacorpus, removeWords, stopwords('pt'))

BigramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = 2, max = 2))

tdm <- TermDocumentMatrix(datacorpus,control=list(removePunctuation = TRUE,
                                       stopwords = stopwords('pt'),
                                       removeNumbers = TRUE,
                                       tokenize = BigramTokenizer))

m <- as.matrix(tdm)
v <- sort(rowSums(m),decreasing=TRUE)
d <- data.frame(word = names(v),freq=v)
head(d, 10)

set.seed(1234)
wordcloud(words = d$word, freq = d$freq, min.freq = 1,
      max.words=200, random.order=FALSE, rot.per=0.35,
      colors=brewer.pal(8, "Dark2"))

![enter image description here][1]
[1]: https://i.stack.imgur.com/Uu67O.jpg

Body:
Assuming you mean you want to drop bigrams that contain a stop word, using the tidytext package, you could do

library(dplyr)
library(tidytext)

set.seed(47)

data_frame(text = 'Sensacional, uma das melhores remakes de animação sai do cinema emocionado, absurdamente lindo, insensibilidade de quem reclama do musical, lindo demais. (...)o filme depende muito da nostalgia da animação para funcionar. E apesar de ser eficaz, somente esse sentimento não sustenta o longa sozinho para dizer que esta obra tenha qualidade e refinamento cinematográficos.(...)A Bela e a Fera acerta em tornar a sua história ainda extremamente relevante nos dias atuais, e se de um lado inova o seu contexto social, por outro lado a falta de originalidade compromete que a obra seja mais impactante.') %>%
    unnest_tokens(bigram, text, 'ngrams', n = 2) %>%    # tokenize bigrams
    mutate(i = row_number()) %>%    # add index for later grouping
    unnest_tokens(word, bigram, drop = FALSE) %>%    # tokenize bigrams into words
    anti_join(data_frame(word = tm::stopwords('pt'))) %>%    # drop rows with stop words
    group_by(i) %>%    # group by bigram index
    filter(n() == 2) %>%    # drop bigram instances where only one word left
    summarise(bigram = unique(bigram)) %>%    # collapse groups to single bigram each
    count(bigram) %>%
    { wordcloud::wordcloud(.$bigram, .$n, min.freq = 1, scale = c(1, .2), rot.per = .35,
                           colors = RColorBrewer::brewer.pal(8, 'Dark2')) }

Colors don't work here because there's a single occurrence of each, but should work fine at scale.


问:
Inset-shadow on HTML5 canvas image
I've seen this question before but  the answers given are for canvas images that have been drawn on via path however, i'm drawing an image.

Is it possible to create an inset-shadow?

```<code>context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 10;
context.shadowColor = 'rgba(30,30,30, 0.4)';

var imgOne = new Image();
imgOne.onload = function() {
    context.drawImage(imgOne, 0, 0);
};
imgOne.src = "./public/circle.png";
</code>```

So I draw the circle picture on. I've now at the moment got a slight shadow on the outside of the circle, how can I get this inset instead of offset?

答:
Inspired by K3N's answer, I've created Inset.js for this exact situation!

Inset.js

Only requires setting ctx.shadowInset = true;

For example: http://codepen.io/patlillis/pen/ryoWey

```<code>var ctx = canvas.getContext('2d');
var img = new Image;
img.onload = function() {
  ctx.shadowInset = true;
  ctx.shadowBlur = 25;
  ctx.shadowColor = "#000";
  ctx.drawImage(this, 0, 0);
}
img.src = "http://i.imgur.com/Qrfga2b.png";
</code>```

Title: Inset-shadow on HTML5 canvas image

Body:
I've seen this question before but  the answers given are for canvas images that have been drawn on via path however, i'm drawing an image.

Is it possible to create an inset-shadow?

context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 10;
context.shadowColor = 'rgba(30,30,30, 0.4)';

var imgOne = new Image();
imgOne.onload = function() {
    context.drawImage(imgOne, 0, 0);
};
imgOne.src = "./public/circle.png";

So I draw the circle picture on. I've now at the moment got a slight shadow on the outside of the circle, how can I get this inset instead of offset?

Body:
Inspired by K3N's answer, I've created Inset.js for this exact situation!

Inset.js

Only requires setting ctx.shadowInset = true;

For example: http://codepen.io/patlillis/pen/ryoWey

var ctx = canvas.getContext('2d');
var img = new Image;
img.onload = function() {
  ctx.shadowInset = true;
  ctx.shadowBlur = 25;
  ctx.shadowColor = "#000";
  ctx.drawImage(this, 0, 0);
}
img.src = "http://i.imgur.com/Qrfga2b.png";


问:
Change font for TextView in ArrayAdapter in Android
I can't figure out away to change the textView font in an Array Adapter. I usually change the font using the code below

```<code>TextView textview = (TextView) findViewById(R.id.textViewsawtyat1);
Typeface face2 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Israr.ttf");
textview.setTypeface(face2);
</code>```

but i am getting an error when i try to use that method because it tries to run this code before creating the Array Adapter. Here is the code for the whole class.

```<code>public class PlayerMainScreen extends Activity implements View.OnTouchListener, AdapterView.OnItemClickListener{
    private ListView listView;
    private String TAG = "Album Main Screen";
    private FirebaseDatabase firebaseDatabaseInstance;
    private DatabaseReference booksInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_main_screen);
        init();
        getData();
    }

    private void init(){

        listView = (ListView) findViewById(R.id.listView);

        listView.setOnItemClickListener(this);

    }
    private void getData(){

        Constants.showLoadingDialog(this);
        firebaseDatabaseInstance = FirebaseDatabase.getInstance();

        // get reference to 'users' node
        booksInstance = firebaseDatabaseInstance.getReference("sawtyat");

        booksInstance.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                setData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
    }

    List<List<String>> playerList;
    List<String> temp1, temp2;
    private void setData(DataSnapshot dataSnapshot){
        playerList = new ArrayList<>();
        temp1 = new ArrayList<>();
        temp2 = new ArrayList<>();

        for (DataSnapshot alert: dataSnapshot.getChildren()) {
            Log.d("cover_image_name", (String) alert.child("book_name").getValue());
            Log.d("cover_image_path", (String) alert.child("sound_path").getValue());

            temp1.add((String) alert.child("book_name").getValue());
            temp2.add((String) alert.child("sound_path").getValue());
        }
        playerList.add(temp1);
        playerList.add(temp2);
        if(playerList.size() > 0){
            setListView();
        }else{
            Toast.makeText(this, "No data Found.", Toast.LENGTH_SHORT).show();
        }
    }

    private void setListView(){
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.fragment_player_main_screen, R.id.textViewsawtyat1, playerList.get(0));

        listView.setAdapter(arrayAdapter);

TextView textview = (TextView) findViewById(R.id.textViewsawtyat1);
        Typeface face3 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Isra.ttf");
        textview.setTypeface(face3);

        Constants.hideDialog();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        PlayAudio(position);
    }

    private void PlayAudio(int position){

        try {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data = Uri.parse(playerList.get(1).get(position));
            intent.setDataAndType(data, "audio/*");
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this, "No player Found.", Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

the text view font i wanna change is in the method setListView

This is the error i am getting

```<code>                 --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.metwally.almostshar.almostshar, PID: 3116
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.widget.TextView.getContext()' on a null object reference
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.setListView(PlayerMainScreen.java:190)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.setData(PlayerMainScreen.java:179)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.access$000(PlayerMainScreen.java:40)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen$5.onDataChange(PlayerMainScreen.java:151)
                      at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
                      at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
                      at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
If you are using a single font to apply throughout your adapter, prefer using custom views for that. Here's the example of how you can do it.

The custom view class

```<code>public class CustomTextView extends TextView {

    public CustomTextView (Context context) {
        super(context);
        init();
    }

    public CustomTextView (Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomTextView (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setTypeface(Typeface.createFromAsset(getContext().getAssets(), YOUR_FONT));
    }

}
</code>```

And then use it in your layout.xml like below

```<code><your.package.name.CustomTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="25sp"
    android:background="@color/colorPrimary"
    android:textColor="@android:color/white"/>
</code>```

Body:
I can't figure out away to change the textView font in an Array Adapter. I usually change the font using the code below

TextView textview = (TextView) findViewById(R.id.textViewsawtyat1);
Typeface face2 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Israr.ttf");
textview.setTypeface(face2);

but i am getting an error when i try to use that method because it tries to run this code before creating the Array Adapter. Here is the code for the whole class.

public class PlayerMainScreen extends Activity implements View.OnTouchListener, AdapterView.OnItemClickListener{
    private ListView listView;
    private String TAG = "Album Main Screen";
    private FirebaseDatabase firebaseDatabaseInstance;
    private DatabaseReference booksInstance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_main_screen);
        init();
        getData();
    }

    private void init(){

        listView = (ListView) findViewById(R.id.listView);

        listView.setOnItemClickListener(this);

    }
    private void getData(){

        Constants.showLoadingDialog(this);
        firebaseDatabaseInstance = FirebaseDatabase.getInstance();

        // get reference to 'users' node
        booksInstance = firebaseDatabaseInstance.getReference("sawtyat");

        booksInstance.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                setData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
    }

    List<List<String>> playerList;
    List<String> temp1, temp2;
    private void setData(DataSnapshot dataSnapshot){
        playerList = new ArrayList<>();
        temp1 = new ArrayList<>();
        temp2 = new ArrayList<>();

        for (DataSnapshot alert: dataSnapshot.getChildren()) {
            Log.d("cover_image_name", (String) alert.child("book_name").getValue());
            Log.d("cover_image_path", (String) alert.child("sound_path").getValue());

            temp1.add((String) alert.child("book_name").getValue());
            temp2.add((String) alert.child("sound_path").getValue());
        }
        playerList.add(temp1);
        playerList.add(temp2);
        if(playerList.size() > 0){
            setListView();
        }else{
            Toast.makeText(this, "No data Found.", Toast.LENGTH_SHORT).show();
        }
    }

    private void setListView(){
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.fragment_player_main_screen, R.id.textViewsawtyat1, playerList.get(0));

        listView.setAdapter(arrayAdapter);

TextView textview = (TextView) findViewById(R.id.textViewsawtyat1);
        Typeface face3 = Typeface.createFromAsset(textview.getContext().getAssets(), "fonts/Isra.ttf");
        textview.setTypeface(face3);

        Constants.hideDialog();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        PlayAudio(position);
    }

    private void PlayAudio(int position){

        try {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri data = Uri.parse(playerList.get(1).get(position));
            intent.setDataAndType(data, "audio/*");
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this, "No player Found.", Toast.LENGTH_SHORT).show();
        }
    }
}

the text view font i wanna change is in the method setListView

This is the error i am getting

                 --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.metwally.almostshar.almostshar, PID: 3116
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.widget.TextView.getContext()' on a null object reference
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.setListView(PlayerMainScreen.java:190)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.setData(PlayerMainScreen.java:179)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen.access$000(PlayerMainScreen.java:40)
                      at com.metwally.almostshar.almostshar.activities.PlayerMainScreen$5.onDataChange(PlayerMainScreen.java:151)
                      at com.google.android.gms.internal.zzbpx.zza(Unknown Source)
                      at com.google.android.gms.internal.zzbqx.zzZS(Unknown Source)
                      at com.google.android.gms.internal.zzbra$1.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
If you are using a single font to apply throughout your adapter, prefer using custom views for that. Here's the example of how you can do it.

The custom view class

public class CustomTextView extends TextView {

    public CustomTextView (Context context) {
        super(context);
        init();
    }

    public CustomTextView (Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomTextView (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setTypeface(Typeface.createFromAsset(getContext().getAssets(), YOUR_FONT));
    }

}

And then use it in your layout.xml like below

<your.package.name.CustomTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="25sp"
    android:background="@color/colorPrimary"
    android:textColor="@android:color/white"/>


问:
Can't set timezone using abbreviation
I can't set timezone on Rails using its abbreviation, for example:

```<code>>> Time.zone = 'BRT'
ArgumentError: Invalid Timezone: BRT
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:61:in `rescue in find_zone!'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:53:in `find_zone!'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:37:in `zone='
        from (irb):14
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands/console.rb:47:in `start'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands/console.rb:8:in `start'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands.rb:41:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'
</code>```

This is necessary as some systems (android and some browsers) report timezone using the abbreviation.
The list of abbreviations can be found at http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations

答:
You don't have to use around_filter.
Put this in before_action

Time.zone = "Etc/GMT#{gmt_offset}"

(Time.zone is thread local. It's safe to change.)

Title: Can't set timezone using abbreviation

Body:
I can't set timezone on Rails using its abbreviation, for example:

>> Time.zone = 'BRT'
ArgumentError: Invalid Timezone: BRT
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:61:in `rescue in find_zone!'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:53:in `find_zone!'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/activesupport-3.2.21/lib/active_support/core_ext/time/zones.rb:37:in `zone='
        from (irb):14
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands/console.rb:47:in `start'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands/console.rb:8:in `start'
        from /home/braulio/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/railties-3.2.21/lib/rails/commands.rb:41:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `'

This is necessary as some systems (android and some browsers) report timezone using the abbreviation.
The list of abbreviations can be found at http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations


答:
You can set the custom font to textview by creating a class which extends Textview and write the code to apply new font in that and use that textivew in your listview.

I have kept three fonts in my assets folder and use them as shown in following code.

```<code>public class CustomTextView extends TextView {
    public final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android";

    public CustomTextView(Context context) {
        super(context);
        setTextViewFont(context, 0);

    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        try {
            int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);
            setTextViewFont(context, textStyle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        try {
            int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);
            setTextViewFont(context, textStyle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Set textstyle
     *
     * @param context   pass context
     * @param fontStyle pass the desired font style <br/>
     *                  0: normal <br/>
     *                  1: bold <br/>
     *                  2: italic <br/>
     */
    public void setTextViewFont(Context context, int fontStyle) {
        if (!isInEditMode()) {
            switch (fontStyle) {
                case Typeface.NORMAL:
                    setTypeface(FontFaceCache.getTypeface("fonts/Roboto-Regular.ttf", context));
                    break;
                case Typeface.BOLD:
                    setTypeface(FontFaceCache.getTypeface("fonts/Roboto-Bold.ttf", context));
                    break;
                case Typeface.ITALIC:
                    setTypeface(FontFaceCache.getTypeface("fonts/Roboto-Italic.ttf", context));
                    break;
            }
        }
    }
</code>```

Then in my layout I use this textview as follows:

```<code><com.abc.CustomTextView
  blah blah...
</code>```

instead of normal android textview

In my answer I have used class FontFaceCache, because accessing font file every time from asset folder is performance consuming which will rssult in UI jagginess/jerks/UI got hang in case of listview or the view where there are lots of Textview.

To resolve that I use a hashmap as follows and get the font everytime from that

```<code>public class FontFaceCache {
    private static HashMap<String, Typeface> fontCache = new HashMap<>(3);

    public static Typeface getTypeface(String fontname, Context context) {
        Typeface typeface = fontCache.get(fontname);
        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), fontname);
            } catch (Exception e) {
                typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
            }
            fontCache.put(fontname, typeface);
        }
        return typeface;
    }
}
</code>```

Title: Change font for TextView in ArrayAdapter in Android

Body:
You can set the custom font to textview by creating a class which extends Textview and write the code to apply new font in that and use that textivew in your listview.

I have kept three fonts in my assets folder and use them as shown in following code.

public class CustomTextView extends TextView {
    public final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android";

    public CustomTextView(Context context) {
        super(context);
        setTextViewFont(context, 0);

    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        try {
            int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);
            setTextViewFont(context, textStyle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public CustomTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        try {
            int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);
            setTextViewFont(context, textStyle);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Set textstyle
     *
     * @param context   pass context
     * @param fontStyle pass the desired font style <br/>
     *                  0: normal <br/>
     *                  1: bold <br/>
     *                  2: italic <br/>
     */
    public void setTextViewFont(Context context, int fontStyle) {
        if (!isInEditMode()) {
            switch (fontStyle) {
                case Typeface.NORMAL:
                    setTypeface(FontFaceCache.getTypeface("fonts/Roboto-Regular.ttf", context));
                    break;
                case Typeface.BOLD:
                    setTypeface(FontFaceCache.getTypeface("fonts/Roboto-Bold.ttf", context));
                    break;
                case Typeface.ITALIC:
                    setTypeface(FontFaceCache.getTypeface("fonts/Roboto-Italic.ttf", context));
                    break;
            }
        }
    }

Then in my layout I use this textview as follows:

<com.abc.CustomTextView
  blah blah...

instead of normal android textview

In my answer I have used class FontFaceCache, because accessing font file every time from asset folder is performance consuming which will rssult in UI jagginess/jerks/UI got hang in case of listview or the view where there are lots of Textview.

To resolve that I use a hashmap as follows and get the font everytime from that

public class FontFaceCache {
    private static HashMap<String, Typeface> fontCache = new HashMap<>(3);

    public static Typeface getTypeface(String fontname, Context context) {
        Typeface typeface = fontCache.get(fontname);
        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), fontname);
            } catch (Exception e) {
                typeface = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Regular.ttf");
            }
            fontCache.put(fontname, typeface);
        }
        return typeface;
    }
}


问:
Ionic App not installing in android device
I am a newbie in Ionic. I just made a simple app in Ionic that ran well on browser. So, I converted it into an .apk file using Android studios that generated an android-release-unsigned.apk file. I transfered it to my device and on trying to install it I encountered that it was not being installed. I am not able to figure out the cause. Need some assistance.</p>

答:
You can follow the steps which are mentioned in the official doc below.

Deploying to a Device

But for me, it didn't work.So I just manually did that as shown below.

ionic cordova run android --device

Plugged device to the PC using USB

Copy the android-debug.apk file to the device (apk path:.. \platforms\android\build\outputs\apk)

After that, You have to enable below setting on your Android device

settings --> general tab --> security --> unknown sources (enabled this)

After that just double-clicked the android-debug.apk from the location which you have copied.Then your app will be installed on your device.That is it.You can use your app on real device now.


问:
SQL Join 2 tables
I have two tables one named Person, which contains columns ID and Name and the second one, named Relation, which contains two columns, each of which contains an ID of a Person. It's about a relation between customer and serviceman. I'd like to Join these two tables so that I'll have names of people in every relation. Is it possible to write this query with some kind of joining?

EDIT::

I must do something wrong, but it's not working. I had tried a lot of forms of so looking queries, but I had been only getting one column or some errors. It's actually the school task, I have it already done (with different JOIN query). Firstly I had been trying to do this, but I'd failed: It seems to be very common situation, so I don't know why it's too complicated for me..

Here are my tables:

```<code>CREATE TABLE Oprava..(Repair) (
  KodPodvozku INTEGER PRIMARY KEY REFERENCES Automobil(KodPodvozku),
  IDzakaznika..(IDcustomer) INTEGER REFERENCES Osoba(ID),
  IDzamestnance..(IDemployee) INTEGER REFERENCES Osoba(ID)
);

CREATE TABLE Osoba..(Person) (
  ID INTEGER CONSTRAINT primaryKeyOsoba PRIMARY KEY ,
  Jmeno..(Name) VARCHAR(256) NOT NULL,
  OP INTEGER UNIQUE NOT NULL
);
</code>```

It's in Czech, but the words in brackets after ".." are english equivalents.
PS: I am using Oracle SQL.

答:
```<code>SELECT p1.name AS customer, p2.name AS serciveman
FROM person p1, person p2, relation
WHERE p1.id=relation.customerid AND p2.id=relation.servicemanid
</code>```

Title: SQL Join 2 tables

Body:
I have two tables one named Person, which contains columns ID and Name and the second one, named Relation, which contains two columns, each of which contains an ID of a Person. It's about a relation between customer and serviceman. I'd like to Join these two tables so that I'll have names of people in every relation. Is it possible to write this query with some kind of joining?

EDIT::

I must do something wrong, but it's not working. I had tried a lot of forms of so looking queries, but I had been only getting one column or some errors. It's actually the school task, I have it already done (with different JOIN query). Firstly I had been trying to do this, but I'd failed: It seems to be very common situation, so I don't know why it's too complicated for me..

Here are my tables:

CREATE TABLE Oprava..(Repair) (
  KodPodvozku INTEGER PRIMARY KEY REFERENCES Automobil(KodPodvozku),
  IDzakaznika..(IDcustomer) INTEGER REFERENCES Osoba(ID),
  IDzamestnance..(IDemployee) INTEGER REFERENCES Osoba(ID)
);

CREATE TABLE Osoba..(Person) (
  ID INTEGER CONSTRAINT primaryKeyOsoba PRIMARY KEY ,
  Jmeno..(Name) VARCHAR(256) NOT NULL,
  OP INTEGER UNIQUE NOT NULL
);

It's in Czech, but the words in brackets after ".." are english equivalents.
PS: I am using Oracle SQL.


问:
Reversing elements in Arrays
```<code>public static void main(String[] args) {

    int[] HwArray = new int[10];
    for (int i = 0; i < HwArray.length; i++) {
        HwArray[i] = i;
        }

    int count = 0;
    for (int i = 0; i < HwArray.length; i++){
    HwArray[i] = (int) (100 + Math.random() * 100);

    System.out.print("HwArray[i]=" + HwArray[i]);
            }

        }

    {
        int[] reverse(int[] HwArray); {
            int[] reversed = new int[HwArray.length];
            for (int i=0; i<HwArray.length; i++) {
                reversed[i] = HwArray[HwArray.length - 1 - i];
            }
            return reverse;
        }
    }

}
</code>```

Sorry, I'm still learning. I'm trying to reverse the order of all the elements, but I keep receiving an error. Am I doing something wrong?

答:
To be honest, you're actually not that far off. The reverse function actually seems to work okay but you have all kinds of weird syntax errors and you're not even calling the reverse method. Try doing this:

Move the reverse method inside the class where main is defined. If you want to call it directly from main you'll have to make it an static method.

Get rid of the extra curly braces on lines 17 and 25.

Remove the semicolon on line 18 when declaring reverse. It shouldn't be there.

The reverse method is trying to return a variable called reverse. That's the name of the method, you can't do that. I think you meant to return reversed.

Actually call the reverse method after you have initialized the array with random numbers. Then print the array out again to verify that it worked.

Notice that you're not actually printing out the values of the array on line 11. That should be System.out.println("HwArray[" + i + "]=" + HwArray[i]);

Title: Reversing elements in Arrays

Body:
public static void main(String[] args) {

    int[] HwArray = new int[10];
    for (int i = 0; i < HwArray.length; i++) {
        HwArray[i] = i;
        }

    int count = 0;
    for (int i = 0; i < HwArray.length; i++){
    HwArray[i] = (int) (100 + Math.random() * 100);

    System.out.print("HwArray[i]=" + HwArray[i]);
            }

        }

    {
        int[] reverse(int[] HwArray); {
            int[] reversed = new int[HwArray.length];
            for (int i=0; i<HwArray.length; i++) {
                reversed[i] = HwArray[HwArray.length - 1 - i];
            }
            return reverse;
        }
    }

}

Sorry, I'm still learning. I'm trying to reverse the order of all the elements, but I keep receiving an error. Am I doing something wrong?


问:
StatusStrip / StatusBar text not visible
This is the first time I am using StatusStrip in Visual Studio 2017 using Visual C# Windows Forms. But a strange thing happened. The Status Bar is visible at the Bottom of the form but somehow it is not showing the text. In StatusStrip Propetries I set the Text property to Ready. Also in code I changed the StatusStrip Text Property twice ... But it doesnot show any text there.  :-(

Please guide me. Your response will be appreciated greatly. I shall be glad and thankful to you :-)

Edit: Thanks ! I have found the solution to this problem (guided by someone in comments). My mistake was that i didn't add StatusLabel to the top of StatusStrip. After making that change, now it works fine :-)

答: As stated in my comment. All you need to do is add a StatusLabel which is one of the options you can add in your StatusStrip bar for any form of text to appear on it.


问:
CSS: display a long string line-line with checkbox
I have a string with 255 characters (no space) and want to display it inline with a checkbox, not under. I have tried inline; inline-block; ... but it doesn't work. Anyone help?</p>

```<code><div class="item">
    <input type="checkbox" id="a">
    <label for="a">a</label>
</div>
<div class="item">
   <input type="checkbox" id="b">
<!-- 255 characters string here -->
    <label for="b">eyDlDLuT8A8AMTeyHSBXj4BeiWefQc1KWilxVWe7m7Vja1m9eEDc8iJ778jvaR2pCN2PcPcIWexrHehXSPJGqWaiSWfqSZL3AuZfOB0U3hlOCQMFWmqHWsERpWrF5YynmiJnn5mZoUP9TDPjW379O38BuBH9Q5zYlIRWgxAskcFT4DJAejiiIeu78jt1jsUU90RqV499IigZSqluOaJY3sptm0qADxE5M1JmnfEB9a8v7yihlrDq3Yy1MVMofBF</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">c</label>
</div>
</code>```

答:
I believe you're looking for the white-space nowrap CSS property.

```<code>.item {
    white-space: nowrap;
}
</code>```

Or with inline CSS:

```<code><div class="item">
    <input type="checkbox" id="a">
    <label for="a">a</label>
</div>
<div class="item" style="white-space: nowrap">
   <input type="checkbox" id="b">
<!-- 255 characters string here -->
    <label for="b">eyDlDLuT8A8AMTeyHSBXj4BeiWefQc1KWilxVWe7m7Vja1m9eEDc8iJ778jvaR2pCN2PcPcIWexrHehXSPJGqWaiSWfqSZL3AuZfOB0U3hlOCQMFWmqHWsERpWrF5YynmiJnn5mZoUP9TDPjW379O38BuBH9Q5zYlIRWgxAskcFT4DJAejiiIeu78jt1jsUU90RqV499IigZSqluOaJY3sptm0qADxE5M1JmnfEB9a8v7yihlrDq3Yy1MVMofBF</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">c</label>
</div>
</code>```

Body:
I have a string with 255 characters (no space) and want to display it inline with a checkbox, not under. I have tried inline; inline-block; ... but it doesn't work. Anyone help?

    <input type="checkbox" id="a">
    a

   <input type="checkbox" id="b">

    eyDlDLuT8A8AMTeyHSBXj4BeiWefQc1KWilxVWe7m7Vja1m9eEDc8iJ778jvaR2pCN2PcPcIWexrHehXSPJGqWaiSWfqSZL3AuZfOB0U3hlOCQMFWmqHWsERpWrF5YynmiJnn5mZoUP9TDPjW379O38BuBH9Q5zYlIRWgxAskcFT4DJAejiiIeu78jt1jsUU90RqV499IigZSqluOaJY3sptm0qADxE5M1JmnfEB9a8v7yihlrDq3Yy1MVMofBF

    <input type="checkbox" id="c">
    c

Body:
I believe you're looking for the white-space nowrap CSS property.

.item {
    white-space: nowrap;
}

Or with inline CSS:

<div class="item">
    <input type="checkbox" id="a">
    <label for="a">a</label>
</div>
<div class="item" style="white-space: nowrap">
   <input type="checkbox" id="b">
<!-- 255 characters string here -->
    <label for="b">eyDlDLuT8A8AMTeyHSBXj4BeiWefQc1KWilxVWe7m7Vja1m9eEDc8iJ778jvaR2pCN2PcPcIWexrHehXSPJGqWaiSWfqSZL3AuZfOB0U3hlOCQMFWmqHWsERpWrF5YynmiJnn5mZoUP9TDPjW379O38BuBH9Q5zYlIRWgxAskcFT4DJAejiiIeu78jt1jsUU90RqV499IigZSqluOaJY3sptm0qADxE5M1JmnfEB9a8v7yihlrDq3Yy1MVMofBF</label>
</div>
<div class="item">
    <input type="checkbox" id="c">
    <label for="c">c</label>
</div>


问:
Switch statement inside a while loop
I have a function which is supposed to act like a cash register. It is suppose to deduct money as long as the change is bigger than 0. However, I don't think the loop or switch statement is working properly as the values are not being deducted and returned to my variable or array. When I view my array the value should be deducted.

The code:

```<code>function checkCashRegister(price, cash, cid) {
  var change = cash - price;
  var message = "";
  var isBoolean = true;
  var cashInReg = cid;

  while(isBoolean) {
    switch (change) {
        case change -100 > 0:
          change-= 100;
          cashInReg[8][1]-= 100;
          break;
        case change -20 > 0:
          break;
        case change -10 > 0:
          break;
        case change -5 > 0:
          break;
        case change -1 > 0:
          break;
        case change -0.25 > 0:
          break;
        case change -0.10 > 0:
          break;
        case change -0.05 > 0:
          break;
        case change -0.01 > 0:
          break;
        case change === 0:
          isBoolean = false;
          break;
        case change < 0:
          message = "Insufficient Funds";
          isBoolean = false;
          break;
      default:
          message = "hi";
    }
  }

  return cashInReg;
}

checkCashRegister(100,500.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
</code>```

答:
From MDN website

The switch statement evaluates an expression, matching the
expression's value to a case clause, and executes statements
associated with that case.

In your code, normally changeshould be compare to the value in case construct which happen to be in (your code a boolean). case change -100 > 0:

 I recommend that you use if else if else if ... else construct.

 Good luck.

Title: Switch statement inside a while loop

Body:
I have a function which is supposed to act like a cash register. It is suppose to deduct money as long as the change is bigger than 0. However, I don't think the loop or switch statement is working properly as the values are not being deducted and returned to my variable or array. When I view my array the value should be deducted.

The code:

function checkCashRegister(price, cash, cid) {
  var change = cash - price;
  var message = "";
  var isBoolean = true;
  var cashInReg = cid;

  while(isBoolean) {
    switch (change) {
        case change -100 > 0:
          change-= 100;
          cashInReg[8][1]-= 100;
          break;
        case change -20 > 0:
          break;
        case change -10 > 0:
          break;
        case change -5 > 0:
          break;
        case change -1 > 0:
          break;
        case change -0.25 > 0:
          break;
        case change -0.10 > 0:
          break;
        case change -0.05 > 0:
          break;
        case change -0.01 > 0:
          break;
        case change === 0:
          isBoolean = false;
          break;
        case change < 0:
          message = "Insufficient Funds";
          isBoolean = false;
          break;
      default:
          message = "hi";
    }
  }

  return cashInReg;
}

checkCashRegister(100,500.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);


问:
What logging apis does Liberty provide?
Obviously Java.util.logging is an option but are any other options available (possibly by enabling a feature)? I did see the eventLogging-1.0 feature but I can't find the related jar or docs.

Specifically, I want to provide a unique identifire with some of my logs, similar to how Liberty does it. Example, see CWWK* below

```<code>[3/30/17 13:29:27:198 PDT] 00000001 com.ibm.ws.kernel.launch.internal.FrameworkManager           A CWWKE0001I: The server defaultServer has been launched.
[3/30/17 13:29:28:638 PDT] 00000001 com.ibm.ws.kernel.launch.internal.FrameworkManager           I CWWKE0002I: The kernel started after 1.695 seconds
</code>```

I could just wrap my calls to Logger.log() and append the ids myself but I figured there has to be a better way. I shouldn't have to include a new lib (ex log4j) since the internal Liberty logs are already doing this.

答:
The CWWK* prefix is part of the message in the NLS message files. There is no magic that prepends these ids to the log messages. They only appear for NLS enabled messages, if you look in trace.

The eventLogging feature essentially causes important events to be logged to the messages.log, it isn't providing an application logging API which is why you can't find any documentation on it.

Liberty doesn't provide a logging API, if java.util.logging doesn't work for you then you can use log4j or slf4j by putting those logging libraries in your application.

Title: What logging apis does Liberty provide?

Body:
Obviously Java.util.logging is an option but are any other options available (possibly by enabling a feature)? I did see the eventLogging-1.0 feature but I can't find the related jar or docs.

Specifically, I want to provide a unique identifire with some of my logs, similar to how Liberty does it. Example, see CWWK* below

[3/30/17 13:29:27:198 PDT] 00000001 com.ibm.ws.kernel.launch.internal.FrameworkManager           A CWWKE0001I: The server defaultServer has been launched.
[3/30/17 13:29:28:638 PDT] 00000001 com.ibm.ws.kernel.launch.internal.FrameworkManager           I CWWKE0002I: The kernel started after 1.695 seconds

I could just wrap my calls to Logger.log() and append the ids myself but I figured there has to be a better way. I shouldn't have to include a new lib (ex log4j) since the internal Liberty logs are already doing this.


答:
Person(ID, Name)
Relation(ID)

You don't mention the other columns that relation contains but this is what you need:

```<code>Select name
from Person as p
join Relation as r
on p.ID = r.ID
</code>```

This is an INNER JOIN as are most of the other answers here.  Please don't use this until you understand that if either record doesn't have a relationship in the other table it will be missing from the dataset (i.e. you can lose data)

Its very important to understand the different types of join so I would use this as an opportunity.

Title: SQL Join 2 tables

Body:
Person(ID, Name)
Relation(ID)

You don't mention the other columns that relation contains but this is what you need:

Select name
from Person as p
join Relation as r
on p.ID = r.ID

This is an INNER JOIN as are most of the other answers here.  Please don't use this until you understand that if either record doesn't have a relationship in the other table it will be missing from the dataset (i.e. you can lose data)

Its very important to understand the different types of join so I would use this as an opportunity.