问:
Incorporating ASP.NET and Flash Components in One Site
I need to integrate ASP.NET into an existing Flash site.  The site is heavily laden with Flash and needs to communicate with a SQL Server database.  I want to use ASP.NET SQLDataSource for this purpose.  Given that I need to integrate the two technologies for one web page on the site, do I need to make the site fully ASP.NET with embedded Flash objects?  Or, can I just add a single ASPX page to the site that contains the web.config and connection string to SQL Server?

Thanks much for your help and guidance.

答: What exactly are you trying to accomplish?  Does the Flash need to access the SQL server through .NET?  How does it need to interact?  If the Flash component just needs to access data, I'd recommend skipping the .aspx part and just having an HttpHandler that acts as a gateway to the database.  Is Flash JSON-friendly?  If so then it would be fairly easy to just pass relevant arguments to the handler (maybe just URL values) and have it serialize a response.</p>


来源: stackexchange

问:
Execute multiple blocks concurrently in a dispatch barrier
I want to send 2 types of requests to a web service. The first is a POST which changes the backend state. The second is a GET which retrieves data from the backend. I want to be able to have multiple POST requests sent concurrently since they won't cause desynchronization. But, I want a GET request to be sent serially in association with the POST requests (when the GET requests is sent, no POST requests can be sent while the GET response is not received. I implemented this with a dispatch barrier for the GET request.

My problem is that while one GET request is being executed, I want the option for more GET requests to be sent concurrently as well and the barrier to break when the last sent GET request's response is received.

I've been trying to make this work using dispatch barriers but haven't found a solution so far. Maybe the solution should be looked for elsewhere.

答:
After a lot of thought and a lot of help from @Rob which I'm very grateful for, the result is that it's best not to use GCD and use OperationQueue instead.

This is a gist with a playground of the implementation along with the tests.

This is its code:

```<code>import PlaygroundSupport

import Foundation

final class OperationsManager {

    private let serialQueue = DispatchQueue(label: "serialQueue")

    private let nonexclusiveOperationsQueue = OperationQueue()
    private let exclusiveOperationQueue = OperationQueue()

    func add(operation: Operation, exclusive: Bool) {
        serialQueue.async {
            if exclusive {
                self.exclusiveOperationQueue.cancelAllOperations()
                print("Ignore the finish of the previous exclusive operation")

                self.nonexclusiveOperationsQueue.operations.forEach {
                    nonexclusiveOperation in
                    operation.addDependency(nonexclusiveOperation)
                }
                self.exclusiveOperationQueue.addOperation(operation)
            } else {
                self.exclusiveOperationQueue.operations.forEach {
                    exclusiveOperation in
                    operation.addDependency(exclusiveOperation)
                }
                self.nonexclusiveOperationsQueue.addOperation(operation)
            }
        }
    }

}

final class BlockedAsynchronousOperation: Operation {

    private var semaphore: DispatchSemaphore?
    private let block: (@escaping () -> ()) -> ()

    init(block: @escaping (@escaping () -> ()) -> ()) {
        self.block = block
    }

    override func cancel() {
        super.cancel()
        semaphore?.signal()
    }

    override func main() {
        super.main()

        semaphore = DispatchSemaphore(value: 0)
        block {
            [weak self] in
            self?.semaphore?.signal()
        }
        semaphore!.wait()
    }

}

///////////////////////////////////////////////////////////////////
func longRunningOperation(
    seconds: Int, completionHandler: @escaping () -> ()) {
    DispatchQueue.global().asyncAfter(
        deadline: .now() + .seconds(seconds),
        execute: completionHandler)
}

func blockedAsynchronousOperation(
    withID id: String, seconds: Int) -> BlockedAsynchronousOperation {
    return BlockedAsynchronousOperation {
        unblockHandler in
        print("Operation with ID: \(id) started")
        longRunningOperation(seconds: seconds) {
            unblockHandler()
            print("Operation with ID: \(id) finished")
        }
    }
}

func addOperation(
    withID id: Int,
    exclusive: Bool,
    atSeconds startSeconds: Int,
    duration: Int,
    inOperationsManager operationsManager: OperationsManager) {
    let block = {
        operationsManager.add(operation:
            blockedAsynchronousOperation(
                withID: (exclusive ? "GET " : "POST ") +
                    String(id), seconds: duration), exclusive: exclusive)
    }
    if startSeconds > 0 {
        DispatchQueue.global().asyncAfter(
            deadline: .now() + .seconds(startSeconds), execute: block)
    } else {
        block()
    }
}

///////////////////////////////////////////////////////////////////
print("global start\n")

let operationsManager = OperationsManager()

addOperation(
    withID: 1,
    exclusive: false,
    atSeconds: 0,
    duration: 7,
    inOperationsManager: operationsManager)
addOperation(
    withID: 2,
    exclusive: false,
    atSeconds: 0,
    duration: 5,
    inOperationsManager: operationsManager)
addOperation(
    withID: 1,
    exclusive: true,
    atSeconds: 0,
    duration: 10,
    inOperationsManager: operationsManager)
addOperation(
    withID: 2,
    exclusive: true,
    atSeconds: 3,
    duration: 10,
    inOperationsManager: operationsManager)
addOperation(
    withID: 3,
    exclusive: true,
    atSeconds: 10,
    duration: 10,
    inOperationsManager: operationsManager)
addOperation(
    withID: 3,
    exclusive: false,
    atSeconds: 15,
    duration: 5,
    inOperationsManager: operationsManager)
addOperation(
    withID: 4,
    exclusive: false,
    atSeconds: 16,
    duration: 5,
    inOperationsManager: operationsManager)
addOperation(
    withID: 4,
    exclusive: true,
    atSeconds: 28,
    duration: 10,
    inOperationsManager: operationsManager)
addOperation(
    withID: 5,
    exclusive: true,
    atSeconds: 31,
    duration: 20,
    inOperationsManager: operationsManager)
addOperation(
    withID: 6,
    exclusive: true,
    atSeconds: 34,
    duration: 2,
    inOperationsManager: operationsManager)

print("\nglobal end\n")

PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After a lot of thought and a lot of help from @Rob which I'm very grateful for, the result is that it's best not to use GCD and use OperationQueue instead.

This is a gist with a playground of the implementation along with the tests.

This is its code:

import PlaygroundSupport

import Foundation

final class OperationsManager {

    private let serialQueue = DispatchQueue(label: "serialQueue")

    private let nonexclusiveOperationsQueue = OperationQueue()
    private let exclusiveOperationQueue = OperationQueue()

    func add(operation: Operation, exclusive: Bool) {
        serialQueue.async {
            if exclusive {
                self.exclusiveOperationQueue.cancelAllOperations()
                print("Ignore the finish of the previous exclusive operation")

                self.nonexclusiveOperationsQueue.operations.forEach {
                    nonexclusiveOperation in
                    operation.addDependency(nonexclusiveOperation)
                }
                self.exclusiveOperationQueue.addOperation(operation)
            } else {
                self.exclusiveOperationQueue.operations.forEach {
                    exclusiveOperation in
                    operation.addDependency(exclusiveOperation)
                }
                self.nonexclusiveOperationsQueue.addOperation(operation)
            }
        }
    }

}

final class BlockedAsynchronousOperation: Operation {

    private var semaphore: DispatchSemaphore?
    private let block: (@escaping () -> ()) -> ()

    init(block: @escaping (@escaping () -> ()) -> ()) {
        self.block = block
    }

    override func cancel() {
        super.cancel()
        semaphore?.signal()
    }

    override func main() {
        super.main()

        semaphore = DispatchSemaphore(value: 0)
        block {
            [weak self] in
            self?.semaphore?.signal()
        }
        semaphore!.wait()
    }

}

///////////////////////////////////////////////////////////////////
func longRunningOperation(
    seconds: Int, completionHandler: @escaping () -> ()) {
    DispatchQueue.global().asyncAfter(
        deadline: .now() + .seconds(seconds),
        execute: completionHandler)
}

func blockedAsynchronousOperation(
    withID id: String, seconds: Int) -> BlockedAsynchronousOperation {
    return BlockedAsynchronousOperation {
        unblockHandler in
        print("Operation with ID: \(id) started")
        longRunningOperation(seconds: seconds) {
            unblockHandler()
            print("Operation with ID: \(id) finished")
        }
    }
}

func addOperation(
    withID id: Int,
    exclusive: Bool,
    atSeconds startSeconds: Int,
    duration: Int,
    inOperationsManager operationsManager: OperationsManager) {
    let block = {
        operationsManager.add(operation:
            blockedAsynchronousOperation(
                withID: (exclusive ? "GET " : "POST ") +
                    String(id), seconds: duration), exclusive: exclusive)
    }
    if startSeconds > 0 {
        DispatchQueue.global().asyncAfter(
            deadline: .now() + .seconds(startSeconds), execute: block)
    } else {
        block()
    }
}

///////////////////////////////////////////////////////////////////
print("global start\n")

let operationsManager = OperationsManager()

addOperation(
    withID: 1,
    exclusive: false,
    atSeconds: 0,
    duration: 7,
    inOperationsManager: operationsManager)
addOperation(
    withID: 2,
    exclusive: false,
    atSeconds: 0,
    duration: 5,
    inOperationsManager: operationsManager)
addOperation(
    withID: 1,
    exclusive: true,
    atSeconds: 0,
    duration: 10,
    inOperationsManager: operationsManager)
addOperation(
    withID: 2,
    exclusive: true,
    atSeconds: 3,
    duration: 10,
    inOperationsManager: operationsManager)
addOperation(
    withID: 3,
    exclusive: true,
    atSeconds: 10,
    duration: 10,
    inOperationsManager: operationsManager)
addOperation(
    withID: 3,
    exclusive: false,
    atSeconds: 15,
    duration: 5,
    inOperationsManager: operationsManager)
addOperation(
    withID: 4,
    exclusive: false,
    atSeconds: 16,
    duration: 5,
    inOperationsManager: operationsManager)
addOperation(
    withID: 4,
    exclusive: true,
    atSeconds: 28,
    duration: 10,
    inOperationsManager: operationsManager)
addOperation(
    withID: 5,
    exclusive: true,
    atSeconds: 31,
    duration: 20,
    inOperationsManager: operationsManager)
addOperation(
    withID: 6,
    exclusive: true,
    atSeconds: 34,
    duration: 2,
    inOperationsManager: operationsManager)

print("\nglobal end\n")

PlaygroundPage.current.needsIndefiniteExecution = true


问:
How to prevent cell editing after pushing header section item?
When I push horizontal header section item in QTableWidget the upper cell in this column becomes ready to be edited.

How can I prevent it?

答:
The problem is related to the interference of

selecting a column when clicking on the column header and

immediately start editing when an item is selected (editTriggers > CurrentChanged)

So, basically, you should disable one or both behaviours.

To disable selecting a column when its header is clicked, you can have a look at the question Disable selecting row or column by clicking the header in QTableWidget containing many alternative solutions.

Or do not immediately start editing by disabling CurrentChanged.


问:
React Native Push Notication - react-native-fcm - ios cannot build

Hello,

I'm trying to use push notification in  react native and for that, I am using react-native-fcm.

It is working on Android and it allows the receiving of notifications from firebase.

However, on IOS, I get build errors as shown in the attached photo.

I did react-native link, made sure the lib was in build phases for linked binaries and also modified the AppDelegate as mentioned in the installation steps.

Has anyone encountered the below error? I did a project clean, delete the build folder but to no avail.

答:
So, after much struggling...

The issue was not with IOS or the react-native-fcm module.

It was with an outdated pod repository.

After updating the pod repo, "pod update Firebase/Core", all the errors disappeared.


问:
find nearest items from lat, lng in postgresql
My table contains lat and lng columns:

lng | double precision | not null

lat | double precision | not null

I want to retrieve only the results from a location (lat, lng).

How do I do ?

答:
This is how I solved it :

```<code>select * , ( point(lat, lng) <-> point($lat, $lng) )*111.325 AS distance
order by distance
</code>```

you get the results ordered by the distance increasing and the distance is in kilometers.

Body:
This is how I solved it :

select * , ( point(lat, lng) <-> point($lat, $lng) )*111.325 AS distance
order by distance

you get the results ordered by the distance increasing and the distance is in kilometers.


问:
Index python dict by object or two floats
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.

I need to record that, for example:

```<code>Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7
Point(X = 1.23, Y = 2.43) -> 9
Point(X = 8.342, Y = 6.754) -> 5
</code>```

I then need to be able to look up the resulting value by the X and Y values. I've tried using the Point objects as the dictionary's key, but this doesn't work as when I recreate the point object from the X and Y values it doesn't look it up properly anymore (presumably because the object ID has changed).

How should I go about linking these point values to the integers. Is there another way that I can use a dictionary?

答:
Python dictionary keys need to be immutable types.

You could use a tuple like (2.765, 3.982).  As long as a tuple contains only immutable types, it can be used as a dictionary key.

Here's my test in the console:

```<code>>>> my_dict[(12.3151, 1.2541)] = "test"
>>> my_dict[(12.3151, 1.2541)]
'test'
</code>```

You could come up with a simple string convention like "2.765, 3.982" to turn a point into an index, but that would be a waste of processing.  Also, a word of caution:  If for some reason you choose to do this, you must use repr instead of str (here's a Stack Overflow post on that topic).

ContentLicense: CC BY-SA 2.5

Body:
I have a number of objects which I need to link to an integer number. These objects are ArcGIS Point objects (exactly what they are isn't relevant), which store an X and a Y value for a point, as floating point numbers.

I need to record that, for example:

Point(X = 2.765, Y = 3.982) -> 2
Point(X = 33.9, Y = 98.45) -> 7
Point(X = 1.23, Y = 2.43) -> 9
Point(X = 8.342, Y = 6.754) -> 5

I then need to be able to look up the resulting value by the X and Y values. I've tried using the Point objects as the dictionary's key, but this doesn't work as when I recreate the point object from the X and Y values it doesn't look it up properly anymore (presumably because the object ID has changed).

How should I go about linking these point values to the integers. Is there another way that I can use a dictionary?

Body:
Python dictionary keys need to be immutable types.

You could use a tuple like (2.765, 3.982).  As long as a tuple contains only immutable types, it can be used as a dictionary key.

Here's my test in the console:

>>> my_dict[(12.3151, 1.2541)] = "test"
>>> my_dict[(12.3151, 1.2541)]
'test'

You could come up with a simple string convention like "2.765, 3.982" to turn a point into an index, but that would be a waste of processing.  Also, a word of caution:  If for some reason you choose to do this, you must use repr instead of str (here's a Stack Overflow post on that topic).


问:
Use of Add Type and Formula1 in Data Validation VBA: Error 1004
I know this question has been covered before and I've tried looking through all the answers, but I am still getting the below error

1004 error: Application-defined or object-defined error.

Below is the code:

```<code>With ActiveSheet.Range("A10").Validation
    .Delete
    .Add Type:=xlValidateList, Formula1:=Join(DPHeight, ",")
    .IgnoreBlank = True
    .InCellDropdown = True
    .ShowInput = True
    .ShowError = True
End With
</code>```

DPHeight is a dynamic array that has been generated previously.
The code stops on the

.Add line

Any help is appreciated. Thank you

答:
Open a new Excel file.

Write this:

```<code>Option Explicit
Sub TetMe()

    Dim DPHeight    As Variant
    DPHeight = Array("34", "46", "67")

    With ActiveSheet.Range("A10").Validation
        .Add Type:=xlValidateList, Formula1:=Join(DPHeight, ",")
        .IgnoreBlank = True
        .InCellDropdown = True
        .ShowInput = True
        .ShowError = True
    End With
End Sub
</code>```

Then check the value of A10. The should be a data validation list present.

Body:
I know this question has been covered before and I've tried looking through all the answers, but I am still getting the below error

1004 error: Application-defined or object-defined error.

Below is the code:

With ActiveSheet.Range("A10").Validation
    .Delete
    .Add Type:=xlValidateList, Formula1:=Join(DPHeight, ",")
    .IgnoreBlank = True
    .InCellDropdown = True
    .ShowInput = True
    .ShowError = True
End With

DPHeight is a dynamic array that has been generated previously.
The code stops on the

.Add line

Any help is appreciated. Thank you

Body:
Open a new Excel file.

Write this:

Option Explicit
Sub TetMe()

    Dim DPHeight    As Variant
    DPHeight = Array("34", "46", "67")

    With ActiveSheet.Range("A10").Validation
        .Add Type:=xlValidateList, Formula1:=Join(DPHeight, ",")
        .IgnoreBlank = True
        .InCellDropdown = True
        .ShowInput = True
        .ShowError = True
    End With
End Sub

Then check the value of A10. The should be a data validation list present.


问:
How we can handle Multiple Type UITableViewCell
I have multiple type cell to show in UITableView.

I have five type of cell in UITableView. all cell show according the different service response data, if service data nil or empty then we will not need to show the cell. so how i can check the number of row and show the cell according the service response.

答:
First -

```<code>func numberOfSections(in tableView: UITableView) -> Int {
        return 2
   }
</code>```

second -

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if (section == 0){
            return 1
        }
        else{return 0
        }
}
</code>```

Third -

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 && indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier:"ImageCell") as! ImageCell

            if strfeaturedImageUrl != nil
            {
             cell.CasinoImage.sd_setImage(with:URL(string: strfeaturedImageUrl!))
            }
           return cell
        }
        else{
            let cell = tableView.dequeueReusableCell(withIdentifier:"InformationCell") as! InformationCell

     return cell
}
}
</code>```

Body:
First -

func numberOfSections(in tableView: UITableView) -> Int {
        return 2
   }

second -

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if (section == 0){
            return 1
        }
        else{return 0
        }
}

Third -

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 && indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier:"ImageCell") as! ImageCell

            if strfeaturedImageUrl != nil
            {
             cell.CasinoImage.sd_setImage(with:URL(string: strfeaturedImageUrl!))
            }
           return cell
        }
        else{
            let cell = tableView.dequeueReusableCell(withIdentifier:"InformationCell") as! InformationCell

     return cell
}
}

ContentLicense: CC BY-SA 4.0


问:
How to make a responsive menu with simple jquery and css
I am trying a simple responsive menu with Css and jQuery. I want the jQuery script to work only on a certain window width. When I resize the browser. Here is my code.

$(document).ready(function(){
   $(".resmenu").click(function(){
    $(".menu").slideToggle();
   });

   $(".submenu").click(function(){
    $(this).toggleClass("active_submenu");
    $(this).parent().find(".dropdown").slideToggle();
   });

  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
 width:980px;
 margin:100px auto 0 auto;
 font-family:arial;
}

ul, li {
 margin:0;
 padding:0;
}

.resmenu {
 display:none;
}

.menu li {
 display: inline-block;
 position: relative;
}
.menu li a {
 font-size: 14px;
 text-transform: uppercase;
 color: #3b2612;
 padding: 6px 17px;
 letter-spacing: 1px;
 display: block;
 text-decoration: none;
}
.menu li:hover a {
 background: #444;
 color: #fff !important;
}

.menu li ul {
 position: absolute;
 width: 250px;
 z-index: 5;
 left: 0px;
 top:28px;
 display:none;

}
.menu li:hover ul {
 display:block;
}
.menu li ul li {
 display: block;
}

.menu li ul li a {
 padding: 6px 17px;
 transition: all 0.2s;
 text-transform: capitalize;
}
.menu li ul li a:hover {
 background: #000;
}

/*--- responsive ----*/
@media screen and (max-width:768px) {

.resmenu {
 color: #fff !important;
 display: block;
 text-decoration: none !important;
 background: #6ca2bd;
 padding: 5px 10px;
}
.menu {
 display: none;
 background: #444444;
}
.menu li {
 position: relative;
 display: block;
}
.menu li a {
 color: #fff;
 font-size:14px;
 padding: 6px 17px;
}
.menu li a:hover {
 background-color: #000;
 color: #000;
 transition: all 0.3s;
}
.active_submenu {
 background-color: #ceb689 !important;
 color: #fff !important;
}

.menu li ul {
 display: none;
 width: 100%;
 position: relative;
 top: 0px;
 display:none;

}
.menu li:hover ul {
 display: none;
 top: 0px;
}

.menu li a.active {
 color: #fff;
 font-family: 'opensanssemibold';
}

.menu li ul li a {
 background:#333;
}

}</code>```

       Menu

Menu

Dropdown One

Dropdown

Dropdown

Dropdown

Dropdown

Dropdown Two

Dropdown

Dropdown

Dropdown

Dropdown

Menu

Menu

```

It is working on 768px screen size, but when I click on the drop-down link instead of hover on more than 768 screen size, the drop down link is slide toggle. I need this script work on certain width only.

答: In css change "container" width to 100%, and set max-width to 980px.</p>

Body:
I am trying a simple responsive menu with Css and jQuery. I want the jQuery script to work only on a certain window width. When I resize the browser. Here is my code.

$(document).ready(function(){
   $(".resmenu").click(function(){
    $(".menu").slideToggle();
   });

   $(".submenu").click(function(){
    $(this).toggleClass("active_submenu");
    $(this).parent().find(".dropdown").slideToggle();
   });

  });

.container {
 width:980px;
 margin:100px auto 0 auto;
 font-family:arial;
}

ul, li {
 margin:0;
 padding:0;
}

.resmenu {
 display:none;
}

.menu li {
 display: inline-block;
 position: relative;
}
.menu li a {
 font-size: 14px;
 text-transform: uppercase;
 color: #3b2612;
 padding: 6px 17px;
 letter-spacing: 1px;
 display: block;
 text-decoration: none;
}
.menu li:hover a {
 background: #444;
 color: #fff !important;
}

.menu li ul {
 position: absolute;
 width: 250px;
 z-index: 5;
 left: 0px;
 top:28px;
 display:none;

}
.menu li:hover ul {
 display:block;
}
.menu li ul li {
 display: block;
}

.menu li ul li a {
 padding: 6px 17px;
 transition: all 0.2s;
 text-transform: capitalize;
}
.menu li ul li a:hover {
 background: #000;
}

/*--- responsive ----*/
@media screen and (max-width:768px) {

.resmenu {
 color: #fff !important;
 display: block;
 text-decoration: none !important;
 background: #6ca2bd;
 padding: 5px 10px;
}
.menu {
 display: none;
 background: #444444;
}
.menu li {
 position: relative;
 display: block;
}
.menu li a {
 color: #fff;
 font-size:14px;
 padding: 6px 17px;
}
.menu li a:hover {
 background-color: #000;
 color: #000;
 transition: all 0.3s;
}
.active_submenu {
 background-color: #ceb689 !important;
 color: #fff !important;
}

.menu li ul {
 display: none;
 width: 100%;
 position: relative;
 top: 0px;
 display:none;

}
.menu li:hover ul {
 display: none;
 top: 0px;
}

.menu li a.active {
 color: #fff;
 font-family: 'opensanssemibold';
}

.menu li ul li a {
 background:#333;
}

}

       Menu

Menu

Dropdown One

Dropdown

Dropdown

Dropdown

Dropdown

Dropdown Two

Dropdown

Dropdown

Dropdown

Dropdown

Menu

Menu

It is working on 768px screen size, but when I click on the drop-down link instead of hover on more than 768 screen size, the drop down link is slide toggle. I need this script work on certain width only.


问:
How to get a sum of all values from a node in Firebase?
this is my Database structure:

I want to get the sum from all child values, from example for I want to get de value "5" that is the sum from all de values of the Node "UNICARIBE"

答:
To count all those value, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference unicaribeRef = rootRef.child("Unicaribe");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int total = 0;
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int value = ds.getValue(Integer.class);
            total =+ value;
        }
        Log.d("TAG", String.valueOf(total));
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
unicaribeRef.addListenerForSingleValueEvent(eventListener);
</code>```

Your output will be 5.

Body:
To count all those value, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference unicaribeRef = rootRef.child("Unicaribe");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        int total = 0;
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            int value = ds.getValue(Integer.class);
            total =+ value;
        }
        Log.d("TAG", String.valueOf(total));
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
unicaribeRef.addListenerForSingleValueEvent(eventListener);

Your output will be 5.


问:
Stop Typescript from emitting @class comments
In my project, the Typescript compiler compiles my classes like so:

```<code>class Example
{
    ...
}
</code>```

into:

```<code>var Example = /** @class */ (function () {
  function Example() {
  }
  return Example;
}());
</code>```

How can I configure Typescript (currently using VS2015) so that it doesn't emit that @class comment?

答: There is no way to remove just the /** @class */ comment. I checked the source code and it does not seem to be controlled by any special compiler flag. The only way to remove this comment is to remove all comments, using the --removeComments compiler option.

Body:
In my project, the Typescript compiler compiles my classes like so:

class Example
{
    ...
}

into:

var Example = /** @class */ (function () {
  function Example() {
  }
  return Example;
}());

How can I configure Typescript (currently using VS2015) so that it doesn't emit that @class comment?


问:
Sql script to find invalid email addresses
A data import was done from an access database and there was no validation on the email address field.  Does anyone have an sql script that can return a list of invalid email addresses (missing @, etc).</p>

答:
I find this approach more intuitive:

```<code>CREATE FUNCTION [dbo].[ContainsVailidEmail] (@Input varchar(250))
RETURNS bit
AS
BEGIN
  RETURN CASE
    WHEN @Input LIKE '%_@__%.__%' THEN 1
    ELSE 0
  END
END
</code>```

I call it using the following:

```<code>SELECT [dbo].[ContainsVailidEmail] (Email) FROM [dbo].[User]
</code>```

OR

If you are only going to use this once then why not it as a Computed Column, with the following specification:

```<code>(case when [Email] like '%_@__%.__%' then (1) else (0) end)
</code>```

Then you can just use it without needing to call a function.

Body:
I find this approach more intuitive:

CREATE FUNCTION [dbo].[ContainsVailidEmail] (@Input varchar(250))
RETURNS bit
AS
BEGIN
  RETURN CASE
    WHEN @Input LIKE '%_@__%.__%' THEN 1
    ELSE 0
  END
END

I call it using the following:

SELECT [dbo].[ContainsVailidEmail] (Email) FROM [dbo].[User]

OR

If you are only going to use this once then why not it as a Computed Column, with the following specification:

(case when [Email] like '%_@__%.__%' then (1) else (0) end)

Then you can just use it without needing to call a function.


问:
Recursive many-to-many CTE
I am not a DB expert was trying to write cte for below scenario for sql server 2012 but could not resolve my problem. Appreciate if some one help me to figure this out.

I am having a many to many table called Jockcard2Item for for the tables Jobcard and items.

Jobcard may have multiple items and items can have many Jobcards,

in my case I want to find out all the Jobcards for given item id like bellow.

jobcard1 having item 1, item 2.

jobcard2 having item 2, item 3

jobards3 having item 3

jobcard4 having item 4

I want to get all jobcards associated to given item, if there other
  items which is refering the same jobcard (like jobcard2 referring
  item2) want to include that job cards too.

result should return  jobcard1,jobcard3,jobcard3,

I was trying with below query which is running infinite.

```<code>DECLARE @itemId int
SELECT @itemId = 12

;WITH temp as(
    SELECT jobCard_ID, item_id FROM Jobcard2Item
    WHERE item_id = @EstimateID

    UNION ALL

    SELECT bi.jobCard_ID ,bi.item_id  FROM Jobcard2Item
    JOIN temp x ON bi.jobCard_ID= x.jobCard_ID where x.item_id  not IN (bi.item_id )
)

select * from temp option (maxrecursion 0)
</code>```

sample date as bellow

id    jobcard_ID, item_ID
1     512         12
2     512         13
3     513         13
4     513         14
5     514         14
6     515         15
7     516         16
```

when I pass the 12 as item_ID it should return the result - 512,513,514,

答:
This query should help:

```<code>select distinct A.jobcard_id from Jockcard2Item A join Jockcard2Item B
on A.jobcard_id = B.jobcard_id or A.item_id = B.item_id
where A.item_id <> B.item_id or A.jobcard_id <> B.jobcard_id
</code>```

It doesn't require CTE (I tried, but I think it's impossible).

Title: Recursive many-to-many CTE

Body:
I am not a DB expert was trying to write cte for below scenario for sql server 2012 but could not resolve my problem. Appreciate if some one help me to figure this out.

I am having a many to many table called Jockcard2Item for for the tables Jobcard and items.

Jobcard may have multiple items and items can have many Jobcards,

in my case I want to find out all the Jobcards for given item id like bellow.

jobcard1 having item 1, item 2.

jobcard2 having item 2, item 3

jobards3 having item 3

jobcard4 having item 4

I want to get all jobcards associated to given item, if there other
  items which is refering the same jobcard (like jobcard2 referring
  item2) want to include that job cards too.

result should return  jobcard1,jobcard3,jobcard3,

I was trying with below query which is running infinite.

DECLARE @itemId int
SELECT @itemId = 12

;WITH temp as(
    SELECT jobCard_ID, item_id FROM Jobcard2Item
    WHERE item_id = @EstimateID

    UNION ALL

    SELECT bi.jobCard_ID ,bi.item_id  FROM Jobcard2Item
    JOIN temp x ON bi.jobCard_ID= x.jobCard_ID where x.item_id  not IN (bi.item_id )
)

select * from temp option (maxrecursion 0)

sample date as bellow

id    jobcard_ID, item_ID
1     512         12
2     512         13
3     513         13
4     513         14
5     514         14
6     515         15
7     516         16

when I pass the 12 as item_ID it should return the result - 512,513,514,

Body:
This query should help:

select distinct A.jobcard_id from Jockcard2Item A join Jockcard2Item B
on A.jobcard_id = B.jobcard_id or A.item_id = B.item_id
where A.item_id <> B.item_id or A.jobcard_id <> B.jobcard_id

It doesn't require CTE (I tried, but I think it's impossible).


问:
What's better to use for Django?
Django-rest or Django Pistons?

What's better plugin for API stuff?

答:
I personally like Piston.  It seems like it's got an active mailing list and it is pretty customizable.  I like that is pretty flexible as to what type of output formats that you can request from it.  Also, creating your own authentication module is pretty easy.
I haven't really used django-rest though. </p>

Title: What's better to use for Django?


问:
Jenkins - Release management integration
we run builds on Jenkins and would like to deploy artifacts using a Microsoft release management (TFS 2017.2). So far seems easy, but the problem is that we use folders within the Jenkins so the Release Management cannot see all jobs and see only Jenkins folders. Did anyone handled such an issue?</p>

答:
After involving Microsoft support, I got this answer:

The capability to link jobs organized in folders is not included in
  TFS 2017. It is amongst the latest of the features on VSTS and would
  be available in the next update to TFS 2018.


问:
Android : Custom DialogFragment so slow to display
I have a DialogFragment which serves as a popup. This DialogFragment has a ListView in it and that uses a BaseAdapter that has custom TableRow. My problem is, it takes about 2 seconds to display the popup fully. Is there any solution, or recommendation that you can give me to display this popup faster.

More details : The TableRow has 2 ImageViews and 3 custom TextViews. The BaseAdapter processes the View because it has to do some stuff like hiding other View, setting texts, etc.

Any help will be appreciated. Thanks! :D

答:
I also had many issues with DialogFragment and in our company we decided to abandon it.
The main problem is it needs some time to infiltrate and do Fragment stuff. But before it appears user can interact with screen.
E.g. press button multiple times before the popup appears and may lead to unexpected behaviors, you have to consider in your code.

Instead use normal Dialog and set Content View - a custom layout and other parameters

```<code>    Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.progress_dialog);
    dialog.setCancelable(false);

    Window window = dialog.getWindow();
    if (window != null) {
        window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    }

    dialog.show();
</code>```

It helps avoid problems connected with Fragments, Fragment Transactions, State and many others.

Body:
I also had many issues with DialogFragment and in our company we decided to abandon it.
The main problem is it needs some time to infiltrate and do Fragment stuff. But before it appears user can interact with screen.
E.g. press button multiple times before the popup appears and may lead to unexpected behaviors, you have to consider in your code.

Instead use normal Dialog and set Content View - a custom layout and other parameters

    Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.progress_dialog);
    dialog.setCancelable(false);

    Window window = dialog.getWindow();
    if (window != null) {
        window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    }

    dialog.show();

It helps avoid problems connected with Fragments, Fragment Transactions, State and many others.


问:
JQuery not working for radio button
Group,

I have below code that isn't doing what I intend it to do. Not sure what am I missing. Can you please help? I would like an alert to flash as soon as radio button is clicked by the user. However, nothing is happening when the radio button is clicked.

```<code><HTML>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

$('#amtopts input').on('change', function() {
   alert($('input[name=amount_r]:checked', '#amtopts').val());
});

var donateamt = document.getElementsByName('amount_r');
var donateamt_value;

function GetDonationAmt() {
    for(var i = 0; i < donateamt.length; i++){
        if(donateamt[i].checked){
            donateamt_value = donateamt[i].value;
            alert("Donation Amount is "+donameamt_value);
            break;
        }
    }
 }
 );
 </script>
 <body>
 <h1>Donate Now</h1>
 <p></p>
  Amount: Amount: <form id="amtopts"><input type="radio" id="amount_r" name="amount_r" value="50"> 50<input type="radio" id="amount_r" name="amount_r" value="75"> 75<input type="radio" id="amount_r" name="amount_r" value="100" > 100<input type="radio" id="amount_r" name="amount_r" value="150"> 150</form>

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

答:
You can not have code inside a script tag if you are using the src attribute.:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
code
</script>
</code>```

you have to do it like:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script>
code
</script>
</code>```

$('#amtopts input').on('change', function() {
  alert($('input[name=amount_r]:checked', '#amtopts').val());
});

var donateamt = document.getElementsByName('amount_r');
var donateamt_value;

function GetDonationAmt() {
  for (var i = 0; i < donateamt.length; i++) {
    if (donateamt[i].checked) {
      donateamt_value = donateamt[i].value;
      alert("Donation Amount is " + donameamt_value);
      break;
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <h1>Donate Now</h1>
  <p></p>
  Amount: Amount:
  <form id="amtopts"><input type="radio" id="amount_r" name="amount_r" value="50"> 50<input type="radio" id="amount_r" name="amount_r" value="75"> 75<input type="radio" id="amount_r" name="amount_r" value="100"> 100<input type="radio" id="amount_r" name="amount_r" value="150">    150</form></code>```

As RoryMcCrossan says, it would be a good idea to wrap your code in document ready:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    code
})
</script>
</code>```

Title: JQuery not working for radio button

Body:
Group,

I have below code that isn't doing what I intend it to do. Not sure what am I missing. Can you please help? I would like an alert to flash as soon as radio button is clicked by the user. However, nothing is happening when the radio button is clicked.

Donate Now

  Amount: Amount: <form id="amtopts"><input type="radio" id="amount_r" name="amount_r" value="50"> 50<input type="radio" id="amount_r" name="amount_r" value="75"> 75<input type="radio" id="amount_r" name="amount_r" value="100" > 100<input type="radio" id="amount_r" name="amount_r" value="150"> 150</form>

Body:
You can not have code inside a script tag if you are using the src attribute.:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
code
</script>

you have to do it like:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script>
code
</script>

$('#amtopts input').on('change', function() {
  alert($('input[name=amount_r]:checked', '#amtopts').val());
});

var donateamt = document.getElementsByName('amount_r');
var donateamt_value;

function GetDonationAmt() {
  for (var i = 0; i < donateamt.length; i++) {
    if (donateamt[i].checked) {
      donateamt_value = donateamt[i].value;
      alert("Donation Amount is " + donameamt_value);
      break;
    }
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <h1>Donate Now</h1>
  <p></p>
  Amount: Amount:
  <form id="amtopts"><input type="radio" id="amount_r" name="amount_r" value="50"> 50<input type="radio" id="amount_r" name="amount_r" value="75"> 75<input type="radio" id="amount_r" name="amount_r" value="100"> 100<input type="radio" id="amount_r" name="amount_r" value="150">    150</form>

As RoryMcCrossan says, it would be a good idea to wrap your code in document ready:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    code
})
</script>


问:
Pivot Tables and eloquent Laravel 5.5
this is maybe the hardest problem I'm facing since I use laravel and I hope some of you might help me to solve it.

So, I have the following schema in my database:

Games

id_game

Players

id_player

Role_Players

id_role
description

Games_players

role_id
game_id
player_id

Now, I have a many to many relationships with games and players and the following model

```<code> class Games {

    public function players {

     return $this->belongsToMany(Players::class, Games_players,  id_game, id_player)

   }
}
</code>```

This will return all the players associated with games, but how can I return the role of the players in this game? I know that I have an object $games->players->pivot where I can add the column role_id, but how can I get for example the description using eloquent? I'm struggling to get this work.

I will appreciate any help.

Thanks.

D

答:
I have an idea.

You can add relation to your Players model somethink like this

```<code>class Players {

    public function roles {

     return $this->belongsToMany(Roles::class, Games_players,  id_player, id_role )

   }
}
</code>```

Then you can use Eager Loading

$games = Games::with('players.roles')->get()

Title: Pivot Tables and eloquent Laravel 5.5

Body:
this is maybe the hardest problem I'm facing since I use laravel and I hope some of you might help me to solve it.

So, I have the following schema in my database:

Games

id_game

Players

id_player

Role_Players

id_role
description

Games_players

role_id
game_id
player_id

Now, I have a many to many relationships with games and players and the following model

 class Games {

    public function players {

     return $this->belongsToMany(Players::class, Games_players,  id_game, id_player)

   }
}

This will return all the players associated with games, but how can I return the role of the players in this game? I know that I have an object $games->players->pivot where I can add the column role_id, but how can I get for example the description using eloquent? I'm struggling to get this work.

I will appreciate any help.

Thanks.

D

Body:
I have an idea.

You can add relation to your Players model somethink like this

class Players {

    public function roles {

     return $this->belongsToMany(Roles::class, Games_players,  id_player, id_role )

   }
}

Then you can use Eager Loading

$games = Games::with('players.roles')->get()


问:
How to prevent 2d object from rotating in unity?
I'm making my first ever game (2D) in unity. And i just a flat character move on surface , and put some walls on the edge of screen to stop him from falling over map, but when he hit the wall he rotates. How do i prevent rotating?</p>

答: If your character has a 2D Rigidbody, you can freeze both position and rotation in any given direction. You can find these options under Constrains in your Rigidbody component.