问:
Cordova application using Angular 2
Instead of ionic I would like to use cordova framework.

So far,

Step 1:

I have created an angular 2 application.

Step 2:

I have created an cordova application and integrated angular 2 application in it.

Its running successfully.

Step 3:

Next step is to load cordova.js file on load

Step 4:

Add cordova plugin(like camera , device ext) in my project.

Step 1 and 2  completed.

Please help me out to complete step 3 and step 4.

When I call plugin its throws an error as follows,

答:
Got an output with following steps,

1)Created an angular project

(Optional)I am using the angular IDE to create angular project

2)Added reference to cordova.js file reference in angular project html file.

```<code><script type="text/javascript" src="cordova.js"></script>
</code>```

3)Create an cordova project

4)Added platform and plugin to the cordova project.

for my case I added browser platform and cordova device plugin.

5)In angular project implemented OnIt and added the plugin callback function as follow.

Note: It is important to call cordova plugin after 'onDeviceReady'

```<code>    import { Component , OnInit} from '@angular/core';

    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit{

    ngOnInit() {
        document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
           alert(device.platform);
        }
    }

    }
</code>```

6)Typescript does not recogonise 'device.platform' and warns as cannot find device

To resolve this issue add the line 'declare var device;'

After adding the above my AppComponent.ts file looks like follows,

```<code>import { Component , OnInit} from '@angular/core';

declare var device;

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

ngOnInit() {
    document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
           alert(device.platform);
        }
}

}
</code>```

7)Build the angular project and copy the build files into cordova /www folder

I am using the script to copy file from angular project to cordova. Tutorial here

8)Prepare and run the cordova project.

for my case I ran the cordova project in browser and got an alert with value 'Browser'

Title: Cordova application using Angular 2

Body:
Got an output with following steps,

1)Created an angular project

(Optional)I am using the angular IDE to create angular project

2)Added reference to cordova.js file reference in angular project html file.

<script type="text/javascript" src="cordova.js"></script>

3)Create an cordova project

4)Added platform and plugin to the cordova project.

for my case I added browser platform and cordova device plugin.

5)In angular project implemented OnIt and added the plugin callback function as follow.

Note: It is important to call cordova plugin after 'onDeviceReady'

    import { Component , OnInit} from '@angular/core';

    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit{

    ngOnInit() {
        document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
           alert(device.platform);
        }
    }

    }

6)Typescript does not recogonise 'device.platform' and warns as cannot find device

To resolve this issue add the line 'declare var device;'

After adding the above my AppComponent.ts file looks like follows,

import { Component , OnInit} from '@angular/core';

declare var device;

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{

ngOnInit() {
    document.addEventListener("deviceready", onDeviceReady, false);
        function onDeviceReady() {
           alert(device.platform);
        }
}

}

7)Build the angular project and copy the build files into cordova /www folder

I am using the script to copy file from angular project to cordova. Tutorial here

8)Prepare and run the cordova project.

for my case I ran the cordova project in browser and got an alert with value 'Browser'


来源: stackexchange

问:
Receive items from a XAMARIN feed
With this command I search all the items of a url where he looks for 10 items, now I need with this command to select only the item from the fifth position,
Returning only one item, how can I do this using the command below, what changes should I make</p>

```<code>private async Task<List<FeedItem>> ParseFeed(string rss)
{
    return await Task.Run(() =>
    {
        var xdoc = XDocument.Parse(rss);
        var id = 0;
        return (from item in xdoc.Descendants("item")
                let enclosure = item.Element("enclosure")
                where enclosure != null
                select new FeedItem
                {
                    Title = (string)item.Element("title"),
                    Description = (string)item.Element("description"),
                    Link = (string)item.Element("link"),
                    PublishDate = DateTime.Parse((string)item.Element("pubDate")).ToUniversalTime().ToString("dd/MM/yyyy HH:mm:ss"),
                    Category = (string)item.Element("category"),
                    Mp3Url = (string)enclosure.Attribute("url"),
                    Image = (string)enclosure.Attribute("url"),
                    Color_category =Convert.ToString(int.Parse((string)item.Element("color")), 16).PadLeft(6, '0'),
                Id = id++
                }).ToList();
    });
}
</code>```

答:
Use Skip() and Take() </p>

```<code>    return (from item in xdoc.Descendants("item")
    ...
    }).Skip(4).Take(1).ToList();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Receive items from a XAMARIN feed

Body:
With this command I search all the items of a url where he looks for 10 items, now I need with this command to select only the item from the fifth position,
Returning only one item, how can I do this using the command below, what changes should I make

private async Task<List<FeedItem>> ParseFeed(string rss)
{
    return await Task.Run(() =>
    {
        var xdoc = XDocument.Parse(rss);
        var id = 0;
        return (from item in xdoc.Descendants("item")
                let enclosure = item.Element("enclosure")
                where enclosure != null
                select new FeedItem
                {
                    Title = (string)item.Element("title"),
                    Description = (string)item.Element("description"),
                    Link = (string)item.Element("link"),
                    PublishDate = DateTime.Parse((string)item.Element("pubDate")).ToUniversalTime().ToString("dd/MM/yyyy HH:mm:ss"),
                    Category = (string)item.Element("category"),
                    Mp3Url = (string)enclosure.Attribute("url"),
                    Image = (string)enclosure.Attribute("url"),
                    Color_category =Convert.ToString(int.Parse((string)item.Element("color")), 16).PadLeft(6, '0'),
                Id = id++
                }).ToList();
    });
}

Body:
Use Skip() and Take()

    return (from item in xdoc.Descendants("item")
    ...
    }).Skip(4).Take(1).ToList();


问:
Recursive hierarchical Oracle SQL query
I have a source table like below:

```<code>Emp_ID| Name| Manager_ID
001|abc|005
005|cde|010
010|xyz|050
050 | bcg| 100
100|sta|NULL
</code>```

My requirement is to populate the target table like below:

```<code>Emp_ID| Name| Manager_1| Manager_2| Manager_3| Manager_4
005|cde|xyz|bcg|sta|NULL
050|bcg|sta| NULL|NULL|NULL
100|sta|NULL|NULL|NULL
001|abc|cde|xyz|bcg|sta
</code>```

I am able to use recursive select through Connect by clause and populate the value for Manager_1 but not able to get through the logic to populate Manager_2, Manager_3 , Manager_4 values as different column values in a single row depending on how many level of hierarchy is present for a certain employee.
Please help.

答:
If your hierarchy only extends to 4 levels deep, the following query may be used:</p>

```<code>select t1.Emp_ID,
       t1.Name,
       t2.Name as Manager_1,
       t3.Name as Manager_2,
       t4.Name as Manager_3,
       t5.Name as Manager_4
from tmp t1
left join tmp t2 on t2.Emp_ID = t1.Manager_ID
left join tmp t3 on t3.Emp_ID = t2.Manager_ID
left join tmp t4 on t4.Emp_ID = t3.Manager_ID
left join tmp t5 on t5.Emp_ID = t4.Manager_ID;
</code>```

Title: Recursive hierarchical Oracle SQL query

Body:
I have a source table like below:

Emp_ID| Name| Manager_ID
001|abc|005
005|cde|010
010|xyz|050
050 | bcg| 100
100|sta|NULL

My requirement is to populate the target table like below:

Emp_ID| Name| Manager_1| Manager_2| Manager_3| Manager_4
005|cde|xyz|bcg|sta|NULL
050|bcg|sta| NULL|NULL|NULL
100|sta|NULL|NULL|NULL
001|abc|cde|xyz|bcg|sta

I am able to use recursive select through Connect by clause and populate the value for Manager_1 but not able to get through the logic to populate Manager_2, Manager_3 , Manager_4 values as different column values in a single row depending on how many level of hierarchy is present for a certain employee.
Please help.

Body:
If your hierarchy only extends to 4 levels deep, the following query may be used:

select t1.Emp_ID,
       t1.Name,
       t2.Name as Manager_1,
       t3.Name as Manager_2,
       t4.Name as Manager_3,
       t5.Name as Manager_4
from tmp t1
left join tmp t2 on t2.Emp_ID = t1.Manager_ID
left join tmp t3 on t3.Emp_ID = t2.Manager_ID
left join tmp t4 on t4.Emp_ID = t3.Manager_ID
left join tmp t5 on t5.Emp_ID = t4.Manager_ID;


问:
How to count the number of true elements in a NumPy bool array
I have a NumPy array 'boolarr' of boolean type. I want to count the number of elements whose values are True. Is there a NumPy or Python routine dedicated for this task? Or, do I need to iterate over the elements in my script?

答:
In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

```<code>import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array

res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])
</code>```

which can be extended to D dimensions.

The results are:

Prediction:

```<code>[[1 2]
 [2 0]
 [2 0]
 [1 2]
 [1 2]]
</code>```

Target:

```<code>[[0 1]
 [1 0]
 [2 0]
 [0 0]
 [2 1]]
</code>```

Count of correct prediction for D=1: 1

Count of correct prediction for D=2: 2

Body:
In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array

res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])

which can be extended to D dimensions.

The results are:

Prediction:

[[1 2]
 [2 0]
 [2 0]
 [1 2]
 [1 2]]

Target:

[[0 1]
 [1 0]
 [2 0]
 [0 0]
 [2 1]]

Count of correct prediction for D=1: 1

Count of correct prediction for D=2: 2


问:
i18next is undefined in react app
I have just started using i18next package on my react app but I'm having a problem. I did 'yarn add i18next@7.1.3 --save' to install the package. And then in my component I did this:

```<code>import i18next from 'i18next'
// other imports...

// defining class
constructor(props){
  super(props)

  console.log(i18next.t('Wähle einen Titel für deinen Ratgeber'))
}
</code>```

And in render method I'm doing this

```<code><Explainer header={i18next.t('Was macht ein gutes Thema aus?')}>
   <GoodTitleExplainer/>
</Explainer>
</code>```

So, on console, I am getting undefined and an error The prop header is marked as required in Explainer, but its value is undefined.

I have got it working in another project but I don't know what's the problem here. Help please.

答:
Did you init the i18next instance? https://www.i18next.com/getting-started.html#basic-sample

Further for using with react i highly recommend using react-i18next: https://react.i18next.com makes loading translations and usage a lot easier

Title: i18next is undefined in react app

Body:
I have just started using i18next package on my react app but I'm having a problem. I did 'yarn add i18next@7.1.3 --save' to install the package. And then in my component I did this:

import i18next from 'i18next'
// other imports...

// defining class
constructor(props){
  super(props)

  console.log(i18next.t('Wähle einen Titel für deinen Ratgeber'))
}

And in render method I'm doing this

<Explainer header={i18next.t('Was macht ein gutes Thema aus?')}>
   <GoodTitleExplainer/>
</Explainer>

So, on console, I am getting undefined and an error The prop header is marked as required in Explainer, but its value is undefined.

I have got it working in another project but I don't know what's the problem here. Help please.


问:
zoom css style is not applied to positioned absolute div element and it's children in IE
Below is html code for testing.
In other browser, all 3-divs are scale down by 0.5.
However in IE(including IE9), absolutely positioned div(second-depth div) and it's child div(third-depth div) is not scale down properly.

How do I apply zoom style for all divs properly?

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="ko" xml:lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body style="zoom:0.5">
<div style="width:400px;height:400px;background:red">
<div style="position:absolute;width:200px;height:200px;background:black">
<div style="width:100px;height:100px;background:blue"></div>
</div>
</div>
</body>
</html>
</code>```

答:
Set the parent elements style to "position:relative".
Now all elements inside the zoomed parent element should be zoomed as well.</p>

Body:
Below is html code for testing.
In other browser, all 3-divs are scale down by 0.5.
However in IE(including IE9), absolutely positioned div(second-depth div) and it's child div(third-depth div) is not scale down properly.

How do I apply zoom style for all divs properly?

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">


问:
What is java interface equivalent in Ruby?
Can we expose interfaces in Ruby like we do in java and enforce the Ruby modules or classes to implement the methods defined by interface.

One way is to use inheritance and method_missing to achieve the same but is there any other more appropriate approach available ?

答:
Ruby has Interfaces just like any other language.

Note that you have to be careful not to conflate the concept of the Interface, which is an abstract specification of the responsibilities, guarantees and protocols of a unit with the concept of the interface which is a keyword in the Java, C# and VB.NET programming languages. In Ruby, we use the former all the time, but the latter simply doesn't exist.

It is very important to distinguish the two. What's important is the Interface, not the interface. The interface tells you pretty much nothing useful. Nothing demonstrates this better than the marker interfaces in Java, which are interfaces that have no members at all: just take a look at java.io.Serializable and java.lang.Cloneable; those two interfaces mean very different things, yet they have the exact same signature.

So, if two interfaces that mean different things, have the same signature, what exactly is the interface even guaranteeing you?

Another good example:

package java.util;

interface List<E> implements Collection<E>, Iterable<E> {
    void add(int index, E element)
        throws UnsupportedOperationException, ClassCastException,
            NullPointerException, IllegalArgumentException,
            IndexOutOfBoundsException;
}
```
<p>What is the <em>Interface</em> of <code>java.util.List<E>.add</code>?</p>
<ul>
<li>that the length of the collection does not decrease</li>
<li>that all the items that were in the collection before are still there</li>
<li>that <code>element</code> is in the collection</li>
</ul>
<p>And which of those actually shows up in the <code>interface</code>? None! There is nothing in the <code>interface</code> that says that the <code>Add</code> method must even <em>add</em> at all, it might just as well <em>remove</em> an element from the collection.</p>
<p>This is a perfectly valid implementation of that <code>interface</code>:</p>
<pre class="lang-java prettyprint-override"><code>class MyCollection<E> implements java.util.List<E> {
    void add(int index, E element)
        throws UnsupportedOperationException, ClassCastException,
            NullPointerException, IllegalArgumentException,
            IndexOutOfBoundsException {
        remove(element);
    }
}
</code>```

Another example: where in java.util.Set<E> does it actually say that it is, you know, a set? Nowhere! Or more precisely, in the documentation. In English.

In pretty much all cases of interfaces, both from Java and .NET, all the relevant information is actually in the docs, not in the types. So, if the types don't tell you anything interesting anyway, why keep them at all? Why not stick just to documentation? And that's exactly what Ruby does.

Note that there are other languages in which the Interface can actually be described in a meaningful way. However, those languages typically don't call the construct which describes the Interface "interface", they call it type. In a dependently-typed programming language, you can, for example, express the properties that a sort function returns a collection of the same length as the original, that every element which is in the original is also in the sorted collection and that no bigger element appears before a smaller element.

So, in short: Ruby does not have an equivalent to a Java interface. It does, however, have an equivalent to a Java Interface, and it's exactly the same as in Java: documentation.

Also, just like in Java, Acceptance Tests can be used to specify Interfaces as well.

In particular, in Ruby, the Interface of an object is determined by what it can do, not what class it is, or what module it mixes in. Any object that has a << method can be appended to. This is very useful in unit tests, where you can simply pass in an Array or a String instead of a more complicated Logger, even though Array and Logger do not share an explicit interface apart from the fact that they both have a method called <<.

Another example is StringIO, which implements the same Interface as IO and thus a large portion of the Interface of File, but without sharing any common ancestor besides Object.

ContentLicense: CC BY-SA 2.5

Body:
Ruby has Interfaces just like any other language.

Note that you have to be careful not to conflate the concept of the Interface, which is an abstract specification of the responsibilities, guarantees and protocols of a unit with the concept of the interface which is a keyword in the Java, C# and VB.NET programming languages. In Ruby, we use the former all the time, but the latter simply doesn't exist.

It is very important to distinguish the two. What's important is the Interface, not the interface. The interface tells you pretty much nothing useful. Nothing demonstrates this better than the marker interfaces in Java, which are interfaces that have no members at all: just take a look at java.io.Serializable and java.lang.Cloneable; those two interfaces mean very different things, yet they have the exact same signature.

So, if two interfaces that mean different things, have the same signature, what exactly is the interface even guaranteeing you?

Another good example:

package java.util;

interface List<E> implements Collection<E>, Iterable<E> {
    void add(int index, E element)
        throws UnsupportedOperationException, ClassCastException,
            NullPointerException, IllegalArgumentException,
            IndexOutOfBoundsException;
}

What is the Interface of java.util.List<E>.add?

that the length of the collection does not decrease

that all the items that were in the collection before are still there

that element is in the collection

And which of those actually shows up in the interface? None! There is nothing in the interface that says that the Add method must even add at all, it might just as well remove an element from the collection.

This is a perfectly valid implementation of that interface:

class MyCollection<E> implements java.util.List<E> {
    void add(int index, E element)
        throws UnsupportedOperationException, ClassCastException,
            NullPointerException, IllegalArgumentException,
            IndexOutOfBoundsException {
        remove(element);
    }
}

Another example: where in java.util.Set<E> does it actually say that it is, you know, a set? Nowhere! Or more precisely, in the documentation. In English.

In pretty much all cases of interfaces, both from Java and .NET, all the relevant information is actually in the docs, not in the types. So, if the types don't tell you anything interesting anyway, why keep them at all? Why not stick just to documentation? And that's exactly what Ruby does.

Note that there are other languages in which the Interface can actually be described in a meaningful way. However, those languages typically don't call the construct which describes the Interface "interface", they call it type. In a dependently-typed programming language, you can, for example, express the properties that a sort function returns a collection of the same length as the original, that every element which is in the original is also in the sorted collection and that no bigger element appears before a smaller element.

So, in short: Ruby does not have an equivalent to a Java interface. It does, however, have an equivalent to a Java Interface, and it's exactly the same as in Java: documentation.

Also, just like in Java, Acceptance Tests can be used to specify Interfaces as well.

In particular, in Ruby, the Interface of an object is determined by what it can do, not what class it is, or what module it mixes in. Any object that has a << method can be appended to. This is very useful in unit tests, where you can simply pass in an Array or a String instead of a more complicated Logger, even though Array and Logger do not share an explicit interface apart from the fact that they both have a method called <<.

Another example is StringIO, which implements the same Interface as IO and thus a large portion of the Interface of File, but without sharing any common ancestor besides Object.

ContentLicense: CC BY-SA 4.0


问:
Display coach marks view when user launches app for the first time Swift 3
I need to launch a coach marks/tutorial view over a tableview when the user launches the app for the first time. The coach marks will never display again, unless the user deletes and reinstalls the app.

I scoured the internet, but was unable to find a simple solution. Oh, I'm fairly new to Swift, so please be gentle. :)

EDIT:
Here is the what I used. Works great!

```<code>  override func viewDidAppear(_ animated: Bool) {
        if !UserDefaults.standard.bool(forKey: "isSecondTime") {
            let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
            if launchedBefore  {
                print("Not the first launch.")
            } else {
                let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CoachMarksViewController")
                self.present(VC, animated: true, completion: nil)
                print("This the first launch.")
                UserDefaults.standard.set(true, forKey: "isSecondTime")
            }

        }
}
</code>```

答:
Probably this is what you need? </p>

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated);
    let kFirstLaunch = "First_launch"

    if (UserDefaults.standard.object(forKey: kFirstLaunch) == nil) {
        UserDefaults.standard.set(1, forKey: kFirstLaunch);
        //Show your coach marks here

    }
}
</code>```

Body:
I need to launch a coach marks/tutorial view over a tableview when the user launches the app for the first time. The coach marks will never display again, unless the user deletes and reinstalls the app.

I scoured the internet, but was unable to find a simple solution. Oh, I'm fairly new to Swift, so please be gentle. :)

EDIT:
Here is the what I used. Works great!

  override func viewDidAppear(_ animated: Bool) {
        if !UserDefaults.standard.bool(forKey: "isSecondTime") {
            let launchedBefore = UserDefaults.standard.bool(forKey: "isSecondTime")
            if launchedBefore  {
                print("Not the first launch.")
            } else {
                let VC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CoachMarksViewController")
                self.present(VC, animated: true, completion: nil)
                print("This the first launch.")
                UserDefaults.standard.set(true, forKey: "isSecondTime")
            }

        }
}

Body:
Probably this is what you need?

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated);
    let kFirstLaunch = "First_launch"

    if (UserDefaults.standard.object(forKey: kFirstLaunch) == nil) {
        UserDefaults.standard.set(1, forKey: kFirstLaunch);
        //Show your coach marks here

    }
}


问:
Disadvantage of using macro to cover interface of move-like function
What are disadvantages of using macro as interface of all move semantics?

I have recently read about syntax of move-related function inside a class (http://stackoverflow.com/a/4782927/ ), and in my opinion, it is quite tedious and repetitive  :-

```<code>C(C&&) = default;                    // Move constructor
C& operator=(C&&) & = default;       // Move assignment operator
</code>```

It is dirtier if I want to customize both move-assignment and move-constructor with the same implementation. (same problem as Copy constructor and = operator overload in C++: is a common function possible?)

Therefore, I decide to create a macro (swap-like function) to make everything concise in a single place.

```<code>#define MACRO_MOVE(C)                        \
C& operator=(C&& that) &  {                 \
     moveHack(this,&that);  return *this;    \
}                                            \
C(C&& that){                                 \
     moveHack(this,&that);                   \
}                                            \
static void moveHack(C* dst,C* src)
</code>```

Here is the usage :-

```<code>class X{
    int data=42;
    MACRO_MOVE(X){
        dst->data=src->data;
        src->data=0;
    }
};
</code>```

However, I haven't seen anyone do like this before.

Are there any issues I should concern?

Are there any specific disadvantages of this approach?

答:
The rule of zero is that only classes that manage resources (like memory) need an explicit move/copy assign/construction method.

You can compose storage of almost every type into self-managing resources.  These resource types tend to be one of a few different variants (value pointer, unique pointer, shared pointer, etc).

Usually when move-assigning, you also want to clean up the existing state.  This isn't true when move-constructing.  The two implementations can share some code, but often you don't want them to.

Doing that kind of macro hackery for a few simple resource management types is a bad idea.  Having complex resource management types all over the place is a bad idea.  This macro hackery doens't deal with move and assignment being fundamentally different operations.  Macros, in general, should only be used when they are costly to avoid.

Your macro doesn't add much utility.  What it does do looks bug prone and dangerous.  If you ever have to debug it, you get undebuggable code.

So there are lots of reasons not to use that macro, and few to use it.

Construction, assignment and destruction are tied together.  Assignment can be viewed as is destruction + construction naively, but that is usually ineffient; and yours doesn't even do the destruction!

Body:
What are disadvantages of using macro as interface of all move semantics?

I have recently read about syntax of move-related function inside a class (http://stackoverflow.com/a/4782927/ ), and in my opinion, it is quite tedious and repetitive  :-

C(C&&) = default;                    // Move constructor
C& operator=(C&&) & = default;       // Move assignment operator

It is dirtier if I want to customize both move-assignment and move-constructor with the same implementation. (same problem as Copy constructor and = operator overload in C++: is a common function possible?)

Therefore, I decide to create a macro (swap-like function) to make everything concise in a single place.

#define MACRO_MOVE(C)                        \
C& operator=(C&& that) &  {                 \
     moveHack(this,&that);  return *this;    \
}                                            \
C(C&& that){                                 \
     moveHack(this,&that);                   \
}                                            \
static void moveHack(C* dst,C* src)

Here is the usage :-

class X{
    int data=42;
    MACRO_MOVE(X){
        dst->data=src->data;
        src->data=0;
    }
};

However, I haven't seen anyone do like this before.

Are there any issues I should concern?

Are there any specific disadvantages of this approach?


问:
Array returning undefined when it should return something else?
I am struggling with query.. I've been searching a lot, the only relevant posts I found had no answers.

row[0] returns undefined, I can't seem to find out why..

info:

As mentioned, logger.warn(rows[0]) returns undefined

rows.length returns 0

logger.warn(pool.escape(hash)) returns the correct hash(same as in DB)

logger.warn(rows[0].hash) returns undefined

This is the error in console/log file: TypeError: Cannot read property 'hash' of undefined

```<code>socket.on('hash', function(hash) {
        query('SELECT * FROM `members` WHERE `hash` = '+pool.escape(hash),
    function(err, rows) {
            logger.warn(rows[0]) // returns "undefined"
            if((err) || (!rows.length)) return socket.disconnect();
    }
</code>```

EDIT: QUERY FUNCITON

```<code>function query(sql, callback) {
if (typeof callback === 'undefined') {
    callback = function() {};
}
pool.getConnection(function(err, connection) {
    if(err) return callback(err);
    logger.info('DB Connection ID: '+connection.threadId);
    connection.query(sql, function(err, rows) {
        if(err) return callback(err);
        connection.release();
        return callback(null, rows);
    });
});
</code>```

}

EDIT: Debug log

https://gyazo.com/858796b81c674ba816f974039eea1c09

EDIT: On disconnect

```<code>socket.on('disconnect', function() {
        logger.warn('Socket disconnect');
        io.sockets.emit('message', {
            type: 'logins',
            count: Object.size(io.sockets.connected)
        });
        delete users[user.email];
    })
</code>```

答:
Looking at the log, it seems that the client is sending the hash event value like this: test%40mail.com.

However, as you state in your comment, in the database the value is stored as this: test@mail.com.

Which means that before running the query, you need to URI-unescape the hash value, and then SQL-escape it, before passing it to the database:

```<code>socket.on("hash", function(hash) {
  hash = pool.escape(decodeURIComponent(hash));
  query("SELECT * FROM `members` WHERE `hash` = " + hash, function(err, rows) {
    ...
  });
});
</code>```

Body:
I am struggling with query.. I've been searching a lot, the only relevant posts I found had no answers.

row[0] returns undefined, I can't seem to find out why..

info:

As mentioned, logger.warn(rows[0]) returns undefined

rows.length returns 0

logger.warn(pool.escape(hash)) returns the correct hash(same as in DB)

logger.warn(rows[0].hash) returns undefined

This is the error in console/log file: TypeError: Cannot read property 'hash' of undefined

socket.on('hash', function(hash) {
        query('SELECT * FROM `members` WHERE `hash` = '+pool.escape(hash),
    function(err, rows) {
            logger.warn(rows[0]) // returns "undefined"
            if((err) || (!rows.length)) return socket.disconnect();
    }

EDIT: QUERY FUNCITON

function query(sql, callback) {
if (typeof callback === 'undefined') {
    callback = function() {};
}
pool.getConnection(function(err, connection) {
    if(err) return callback(err);
    logger.info('DB Connection ID: '+connection.threadId);
    connection.query(sql, function(err, rows) {
        if(err) return callback(err);
        connection.release();
        return callback(null, rows);
    });
});

}

EDIT: Debug log

https://gyazo.com/858796b81c674ba816f974039eea1c09

EDIT: On disconnect

socket.on('disconnect', function() {
        logger.warn('Socket disconnect');
        io.sockets.emit('message', {
            type: 'logins',
            count: Object.size(io.sockets.connected)
        });
        delete users[user.email];
    })

Body:
Looking at the log, it seems that the client is sending the hash event value like this: test%40mail.com.

However, as you state in your comment, in the database the value is stored as this: test@mail.com.

Which means that before running the query, you need to URI-unescape the hash value, and then SQL-escape it, before passing it to the database:

socket.on("hash", function(hash) {
  hash = pool.escape(decodeURIComponent(hash));
  query("SELECT * FROM `members` WHERE `hash` = " + hash, function(err, rows) {
    ...
  });
});


问:
Python daemon threads and the "with" statement
If I have the following code in a daemon thread and the main thread does not do invoke a join on the daemon. Will the file close safely since it is used inside "with" once the main thread exits or no? Anyway to make it safe? Thanks :D  </p>

```<code>while True:
    with open('file.txt', 'r') as f:
        cfg = f.readlines()
time.sleep(60)
</code>```

答:
From the docs:

Note: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

This suggests, but does not outright state, that daemon threads are terminated without a chance for __exit__ methods and finally blocks to run. We can run an experiment to verify that this is the case:

```<code>import contextlib
import threading
import time

@contextlib.contextmanager
def cm():
    try:
        yield
    finally:
        print 'in __exit__'

def f():
    with cm():
        print 'in with block'
        event.set()
        time.sleep(10)

event = threading.Event()

t = threading.Thread(target=f)
t.daemon = True
t.start()

event.wait()
</code>```

where we start a daemon thread and leave it sleeping in a with block when the main thread exits. When we run the experiment, we get an output of

```<code>in with block
</code>```

but no in __exit__, so the __exit__ method never gets a chance to run.

If you want cleanup, don't use a daemon thread. Use a regular thread, and tell it to shut down at the end of the main thread through the regular inter-thread communication channels.

Body:
If I have the following code in a daemon thread and the main thread does not do invoke a join on the daemon. Will the file close safely since it is used inside "with" once the main thread exits or no? Anyway to make it safe? Thanks :D

while True:
    with open('file.txt', 'r') as f:
        cfg = f.readlines()
time.sleep(60)

Body:
From the docs:

Note: Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

This suggests, but does not outright state, that daemon threads are terminated without a chance for __exit__ methods and finally blocks to run. We can run an experiment to verify that this is the case:

import contextlib
import threading
import time

@contextlib.contextmanager
def cm():
    try:
        yield
    finally:
        print 'in __exit__'

def f():
    with cm():
        print 'in with block'
        event.set()
        time.sleep(10)

event = threading.Event()

t = threading.Thread(target=f)
t.daemon = True
t.start()

event.wait()

where we start a daemon thread and leave it sleeping in a with block when the main thread exits. When we run the experiment, we get an output of

in with block

but no in __exit__, so the __exit__ method never gets a chance to run.

If you want cleanup, don't use a daemon thread. Use a regular thread, and tell it to shut down at the end of the main thread through the regular inter-thread communication channels.


问:
Angular2 avoid adding duplicate JSON objects to array
I'm trying to avoid adding duplicate objects to an Angular2 array. For example let's say we have an array "Cars" and we put in a JSON object in that array that might be something like:

```<code>{
 "brand": "Acura"
 "engine": "2.4L"
 + others details
}
</code>```

We can keep adding cars with to the array. My issue is now how to avoid adding the same car into the array again. If I were to add the same JSON as described above, it shouldn't be added. Would I have to iterate through all the existing objects in the array and compare each field of the JSON? This sounds like an expensive operation to me, or is there some more elegant/faster method?

Thanks!

答:
If each car has something unique about it (like an ID), you could use an object instead of an array:

```<code>var map = { };

function add(car) {
    if (map[car.id]) {
        return;
    }

    map[car.id] = car;
}
</code>```

Your ID could be something else unique, like a combination of the brand and year or something similar.

```<code>map[car.brand + car.year] = car
</code>```

Body:
I'm trying to avoid adding duplicate objects to an Angular2 array. For example let's say we have an array "Cars" and we put in a JSON object in that array that might be something like:

{
 "brand": "Acura"
 "engine": "2.4L"
 + others details
}

We can keep adding cars with to the array. My issue is now how to avoid adding the same car into the array again. If I were to add the same JSON as described above, it shouldn't be added. Would I have to iterate through all the existing objects in the array and compare each field of the JSON? This sounds like an expensive operation to me, or is there some more elegant/faster method?

Thanks!

Body:
If each car has something unique about it (like an ID), you could use an object instead of an array:

var map = { };

function add(car) {
    if (map[car.id]) {
        return;
    }

    map[car.id] = car;
}

Your ID could be something else unique, like a combination of the brand and year or something similar.

map[car.brand + car.year] = car


问:
Retrieving index from multi-index based on column values in Pandas
Say I have a table as such:

```<code>  Attr   |  Foo    |  Bar
Name|Val | 1  | 2  | 3  | 4
-----------------------------
OFO |1   | F  | T  | F  | F
    |2   | T  | F  | F  | T
-----------------------------
ARB |5   | T  | T  | F  | F
    |6   | F  | F  | F  | T
</code>```

Where my rows are controlled by an index with level 0 = {OFO, ARB} and level 1 = {1,2,5,6} and columns are level 0 = {Foo,Bar} and level 1 = {1,2,3,4} I want to be able to pull the respective row and column index from each T entry, so one return would be:

```<code>((Foo,1),(OFO,1))
</code>```

I'm struggling to come up with a good solution.

答:
You can start with:

```<code>df.stack([0,1]).reset_index(name='value').query('value == True')
</code>```

Output:

```<code>   level_0  level_1 level_2  level_3 value
3      OFO        1     Foo        2  True
5      OFO        2     Bar        4  True
6      OFO        2     Foo        1  True
10     ARB        5     Foo        1  True
11     ARB        5     Foo        2  True
13     ARB        6     Bar        4  True
</code>```

Body:
Say I have a table as such:

  Attr   |  Foo    |  Bar
Name|Val | 1  | 2  | 3  | 4
-----------------------------
OFO |1   | F  | T  | F  | F
    |2   | T  | F  | F  | T
-----------------------------
ARB |5   | T  | T  | F  | F
    |6   | F  | F  | F  | T

Where my rows are controlled by an index with level 0 = {OFO, ARB} and level 1 = {1,2,5,6} and columns are level 0 = {Foo,Bar} and level 1 = {1,2,3,4} I want to be able to pull the respective row and column index from each T entry, so one return would be:

((Foo,1),(OFO,1))

I'm struggling to come up with a good solution.

Body:
You can start with:

df.stack([0,1]).reset_index(name='value').query('value == True')

Output:

   level_0  level_1 level_2  level_3 value
3      OFO        1     Foo        2  True
5      OFO        2     Bar        4  True
6      OFO        2     Foo        1  True
10     ARB        5     Foo        1  True
11     ARB        5     Foo        2  True
13     ARB        6     Bar        4  True


问:
total number of rows of a query
I have a very large query that is supposed to return only the top 10 results:

select top 10 ProductId from .....

The problem is that I also want the total number of results that match the criteria without that 'top 10', but in the same time it's considered unaceptable to return all rows (we are talking of roughly 100 thousand results.

Is there a way to get the total number of rows affected by the previous query, either in it or afterwords without running it again?

PS: please no temp tables of 100 000 rows :))

答:
Generally speaking no - reasoning is as follows:

If(!) the query planner can make use of TOP 10 to return only 10 rows then RDBMS will not even know the exact number of rows that satisfy the full criteria, it just gets the TOP 10.

Therefore, when you want to find out count of all rows satisfying the criteria you are not running it the second time, but the first time.

Having said that proper indexes might make both queries execute pretty fast.

Edit

MySQL has SQL_CALC_FOUND_ROWS which returns the number of rows that query would return if there was no LIMIT applied - googling for an equivalent in MS SQL points to analytical SQL and CTE variant, see this forum (even though not sure that either would qualify as running it only once, but feel free to check - and let us know).

Title: total number of rows of a query


问:
Pause HTML Video on exiting a tab
I have a section with tabs. Two tabs have a video.

Only problem is, which I can't figure out, when I click to play video it plays (that is good) but when I go to the next tab the initial video will still be playing - what I want is the video to pause when I exit each tab.

I've tried playing about with functions but just can't get it working.

Thanks!

$('ul.tabs li').click(function() {
    var tab_id = $(this).data('tab');

    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');

    $(this).addClass('current');
    $(this).parent().parent().parent().children("#"+tab_id).addClass('current');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
 background: #fff;
}

ul.tabs {
 margin: 0;
 padding: 0;
 list-style: none;
  background: #ccc;
}

.tab-link {
 background: none;
 color: #fff;
 display: inline-block;
 padding: 10px;
 cursor: pointer;
 font-size: 16px;
}

.tabs .tab-link.current {
 background: #ccc;
}

.tab-content {
 display: none;
 background: #ccc;
}

.tab-content.current {
 display: block;
}

video {
 width: 100%;
 height: 400px;
}</code>```

        One

        Two

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

```

答:
When you change tabs, pause and set the video currentTime to zero.

```<code>video.get(0).pause();
video.get(0).currentTime = 0;
</code>```

You don't need to iterate each video, just get the one that has current class.

See code below:

$('ul.tabs li').click(function() {
  var tab_id = $(this).data('tab');

  resetVideo();

  $('ul.tabs li').removeClass('current');
  $('.tab-content').removeClass('current');

  $(this).addClass('current');
  $(this).parent().parent().parent().children("#" + tab_id).addClass('current');
});

function resetVideo() {
  var $video = $('.tab-content.current video');
  $video.get(0).pause();
  $video.get(0).currentTime = 0;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section {
  background: #fff;
}

ul.tabs {
  margin: 0;
  padding: 0;
  list-style: none;
  background: #ccc;
}

.tab-link {
  background: none;
  color: #fff;
  display: inline-block;
  padding: 10px;
  cursor: pointer;
  font-size: 16px;
}

.tabs .tab-link.current {
  background: #ccc;
}

.tab-content {
  display: none;
  background: #ccc;
}

.tab-content.current {
  display: block;
}

video {
  width: 100%;
  height: 400px;
}</code>```

        One

        Two

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

```

Title: Pause HTML Video on exiting a tab

Body:
I have a section with tabs. Two tabs have a video.

Only problem is, which I can't figure out, when I click to play video it plays (that is good) but when I go to the next tab the initial video will still be playing - what I want is the video to pause when I exit each tab.

I've tried playing about with functions but just can't get it working.

Thanks!

$('ul.tabs li').click(function() {
    var tab_id = $(this).data('tab');

    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');

    $(this).addClass('current');
    $(this).parent().parent().parent().children("#"+tab_id).addClass('current');
});

section {
 background: #fff;
}

ul.tabs {
 margin: 0;
 padding: 0;
 list-style: none;
  background: #ccc;
}

.tab-link {
 background: none;
 color: #fff;
 display: inline-block;
 padding: 10px;
 cursor: pointer;
 font-size: 16px;
}

.tabs .tab-link.current {
 background: #ccc;
}

.tab-content {
 display: none;
 background: #ccc;
}

.tab-content.current {
 display: block;
}

video {
 width: 100%;
 height: 400px;
}

        One

        Two

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>

Body:
When you change tabs, pause and set the video currentTime to zero.

video.get(0).pause();
video.get(0).currentTime = 0;

You don't need to iterate each video, just get the one that has current class.

See code below:

$('ul.tabs li').click(function() {
  var tab_id = $(this).data('tab');

  resetVideo();

  $('ul.tabs li').removeClass('current');
  $('.tab-content').removeClass('current');

  $(this).addClass('current');
  $(this).parent().parent().parent().children("#" + tab_id).addClass('current');
});

function resetVideo() {
  var $video = $('.tab-content.current video');
  $video.get(0).pause();
  $video.get(0).currentTime = 0;
}

section {
  background: #fff;
}

ul.tabs {
  margin: 0;
  padding: 0;
  list-style: none;
  background: #ccc;
}

.tab-link {
  background: none;
  color: #fff;
  display: inline-block;
  padding: 10px;
  cursor: pointer;
  font-size: 16px;
}

.tabs .tab-link.current {
  background: #ccc;
}

.tab-content {
  display: none;
  background: #ccc;
}

.tab-content.current {
  display: block;
}

video {
  width: 100%;
  height: 400px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <nav>
    <ul class="tabs">
      <li class="tab-link current" data-tab="first">
        <a href="#tab-1">One</a>
      </li>
      <li class="tab-link" data-tab="sec">
        <a href="#tab-2">Two</a>
      </li>
    </ul>
  </nav>
  <div id="first" class="tab-content current">
    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>
  </div>
  <div id="sec" class="tab-content">
    <video controls>
      <source type="video/mp4"
      src="http://techslides.com/demos/sample-videos/small.mp4">
    </video>
  </div>
</section>


问:
Python - Mapping a Key to a Value that is a Map
Is it possible to map a string to a map in Python. For example, if I want a map that looks like:

mymap = { 'ABC': {'123' : 56}, 'DEF': {'456' : 92}  }

Is this possible? How would I add a value to the map, or check the map to see what the value is of the 'inner map' if I am doing an iteration when mymap is empty (at the start of a loop, for example). Thanks!

答:
```<code>>>> from collections import defaultdict

>>> mymap = defaultdict(dict)
>>> mymap['ABC'] = {'123' : 56}
>>> mymap
defaultdict(<type 'dict'>, {'ABC': {'123': 56}})
</code>```

can you try this snippet, hope this solves your purpose

Body:
>>> from collections import defaultdict

>>> mymap = defaultdict(dict)
>>> mymap['ABC'] = {'123' : 56}
>>> mymap
defaultdict(<type 'dict'>, {'ABC': {'123': 56}})

can you try this snippet, hope this solves your purpose


问:
App Maker and Cloud SQL - connection issue
I am working on an app which is using Cloud SQL database. I am already connected with Cloud SQL instance using instance name, user name, password. I am able to create tables (by adding model), drop tables (by check) from App Maker level.

However I can't insert record using form. I also can't present the data in tables.

I am getting following error,

Exception: Unable to connect to database. Check the connection string,
  user name, and password. Executing query for datasource ModelSQL:
  (Error) : Unable to connect to database. Check the connection string,
  user name, and password. Executing query for datasource ModelSQL
  failed.

答: Did you set the preview credentials? (App Settings > GOOGLE CLOUD SQL > SQL preview credentials > UPDATE).</p>


问:
Make content fill the whole viewport
https://gyazo.com/1440b13007c6e011ec46218ceecabb6a
As you can see by the screenshot, there is a white border around the main content of the page. Ive tried making everything 100% width etc. but nothing seems to work. The nav bar is just a ul and the bottom part is a container div with other child divs heald inside.</p>

答:
try adding css as below:</p>

```<code>body, html {
margin: 0;
padding: 0;
}
</code>```

Title: Make content fill the whole viewport

Body:
try adding css as below:

body, html {
margin: 0;
padding: 0;
}


问:
Oculus Tiny Room, Directx, Loading a 3D Model into scene
I am currently working on Oculus Rift PC SDK. Was trying to start off with something simpler like Tiny Room Demo(DX11). Saw this tutorial online to load a 3D model into the scene from external file (Rastertek
Tutorial 7: 3D Model Rendering)

The way the Tiny Room Demo creates model is to hardcode the coordinates and renders it

```<code>TriangleSet walls;
    walls.AddSolidColorBox(10.1f, 0.0f, 20.0f, 10.0f, 4.0f, -20.0f, 0xff808080);  // Left Wall
    walls.AddSolidColorBox(10.0f, -0.1f, 20.1f, -10.0f, 4.0f, 20.0f, 0xff808080); // Back Wall
    walls.AddSolidColorBox(-10.0f, -0.1f, 20.0f, -10.1f, 4.0f, -20.0f, 0xff808080);   // Right Wall
    Add(
        new Model(&walls, XMFLOAT3(0, 0, 0), XMFLOAT4(0, 0, 0, 1),
            new Material(
                new Texture(false, 256, 256, Texture::AUTO_WALL)
            )
        )
    );

void AddSolidColorBox(float x1, float y1, float z1, float x2, float y2, float z2, uint32_t c)
{
    AddQuad(Vertex(XMFLOAT3(x1, y2, z1), ModifyColor(c, XMFLOAT3(x1, y2, z1)), z1, x1),
            Vertex(XMFLOAT3(x2, y2, z1), ModifyColor(c, XMFLOAT3(x2, y2, z1)), z1, x2),
            Vertex(XMFLOAT3(x1, y2, z2), ModifyColor(c, XMFLOAT3(x1, y2, z2)), z2, x1),
            Vertex(XMFLOAT3(x2, y2, z2), ModifyColor(c, XMFLOAT3(x2, y2, z2)), z2, x2));
...}

AddQuad(Vertex v0, Vertex v1, Vertex v2, Vertex v3) { AddTriangle(v0, v1, v2);  AddTriangle(v3, v2, v1); }

void AddTriangle(Vertex v0, Vertex v1, Vertex v2)
{
    VALIDATE(numVertices <= (maxBuffer - 3), "Insufficient triangle set");
    for (int i = 0; i < 3; i++) Indices[numIndices++] = short(numVertices + i);
    Vertices[numVertices++] = v0;
    Vertices[numVertices++] = v1;
    Vertices[numVertices++] = v2;
}
</code>```

Tried to load the model into the scene using a function from the tutorial

```<code>TriangleSet models;
    models.LoadModel("F:\\cube.txt");
    Add(
        new OBJModel(&models, XMFLOAT3(0, 0, 0), XMFLOAT4(0, 0, 0, 1),
            new OBJMaterial(
                new Texture(false, 256, 256, Texture::AUTO_WHITE)
                //new Texture(DirectX, L"wallpaper.jpg")
            )
        )
    );  //3D Model

void LoadModel(char* filename)
{
    ifstream fin;
    char input;

    // Open the model file.
    fin.open(filename);

    // Read up to the value of vertex count.
    fin.get(input);
    while (input != ':')
    {
        fin.get(input);
    }

    // Read in the vertex count.
    m_vertexCount = 0;
    fin >> m_vertexCount;

    // Read up to the beginning of the data.
    fin.get(input);
    while (input != ':')
    {
        fin.get(input);
    }
    fin.get(input);
    fin.get(input);

    // Read in the vertex data.
    for (int i = 0; i<m_vertexCount; i++)
    {
        Indices[numIndices++] = short(numVertices + i);
        //numVertices++; deleted
        fin >> Vertices[numVertices].Pos.x >> Vertices[numVertices].Pos.y >> Vertices[numVertices].Pos.z;
        fin >> Vertices[numVertices].U >> Vertices[numVertices].V;
        fin >> Normals[numVertices].Norm.x >> Normals[numVertices].Norm.y >> Normals[numVertices].Norm.z;
        Vertices[numVertices].C = ModifyColor(0xffffffff, Vertices[numVertices].Pos);
        numVertices+=1; //new statement
    }

    // Close the model file.
    fin.close();
}
</code>```

I did not use the normal as from the tutorial it was meant for the texture of the object. Instead I defined the color to be solid yellow. Tried to keep the structure of loading the model as similar to Tiny Room Demo as possible.

I have used the same model, material and texture (vertex shader and pixel shader) as how Tiny Room Demo does. However what was rendered onto the scene did not appear as what it is supposed to be.

Did a step by step debugging to see if the coordinates were correctly loading into the Vertices[numVertices]. Seems like there is no issue. The file I tried to load was cube.txt

Vertex Count: 36

Data:

-1.0  1.0 -1.0 0.0 0.0  0.0  0.0 -1.0

1.0  1.0 -1.0 1.0 0.0  0.0  0.0 -1.0

-1.0 -1.0 -1.0 0.0 1.0  0.0  0.0 -1.0

-1.0 -1.0 -1.0 0.0 1.0  0.0  0.0 -1.0

1.0  1.0 -1.0 1.0 0.0  0.0  0.0 -1.0

1.0 -1.0 -1.0 1.0 1.0  0.0  0.0 -1.0

1.0  1.0 -1.0 0.0 0.0  1.0  0.0  0.0

1.0  1.0  1.0 1.0 0.0  1.0  0.0  0.0

1.0 -1.0 -1.0 0.0 1.0  1.0  0.0  0.0

1.0 -1.0 -1.0 0.0 1.0  1.0  0.0  0.0

1.0  1.0  1.0 1.0 0.0  1.0  0.0  0.0

1.0 -1.0  1.0 1.0 1.0  1.0  0.0  0.0

1.0  1.0  1.0 0.0 0.0  0.0  0.0  1.0

-1.0  1.0  1.0 1.0 0.0  0.0  0.0  1.0

1.0 -1.0  1.0 0.0 1.0  0.0  0.0  1.0

1.0 -1.0  1.0 0.0 1.0  0.0  0.0  1.0

-1.0  1.0  1.0 1.0 0.0  0.0  0.0  1.0

-1.0 -1.0  1.0 1.0 1.0  0.0  0.0  1.0

...

What was suppose to show up (except without the texture)
3D cube

What actually showed up was just fragments of triangle
TinyRoomDemo + 3D cube

Unsure what went wrong. Please do advice! Thank you very much :)

Vertex and Index buffer

```<code>struct OBJModel
{
XMFLOAT3     Pos;
XMFLOAT4     Rot;
OBJMaterial   * Fill;
DataBuffer * VertexBuffer;
DataBuffer * IndexBuffer;
int          NumIndices;

OBJModel() : Fill(nullptr), VertexBuffer(nullptr), IndexBuffer(nullptr) {};
void Init(TriangleSet * t)
{
    NumIndices = t->numIndices;
    VertexBuffer = new DataBuffer(DIRECTX.Device, D3D11_BIND_VERTEX_BUFFER, &t->Vertices[0], t->numVertices * sizeof(Vertex));
    IndexBuffer = new DataBuffer(DIRECTX.Device, D3D11_BIND_INDEX_BUFFER, &t->Indices[0], t->numIndices * sizeof(short));
}
</code>```

...

```<code>DIRECTX.Context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
</code>```

---------------------------------------------------------------------------------------------------------------------------------

06/06/2017 edited:
3D Model data:

Vertex Count: 798

Data:

28.3005 0.415886 -45.8282 0.7216 0.720211 0 0 -1

28.3005 -0.809079 -45.8282 0.732222 0.720211 0 0 -1

-27.7441 -0.809079 -45.8282 0.732222 0.847836 0 0 -1

28.3005 0.415886 68.1056 0.459891 0.720286 0 1 -0

28.3005 0.415886 -45.8282 0.719341 0.720286 0 1 -0

-27.7441 0.415886 -45.8282 0.719341 0.847911 0 1 -0

28.3005 -0.809079 68.1056 0.721603 0.720211 0 0 1

28.3005 0.415886 68.1056 0.732225 0.720211 0 0 1

-27.7441 0.415886 68.1056 0.732225 0.847836 0 0 1

28.3005 -0.809079 -45.8282 0.459891 0.720298 0 -1 -0

28.3005 -0.809079 68.1056 0.719341 0.720298 0 -1 -0

-27.7441 -0.809079 68.1056 0.719341 0.847923 0 -1 -0

28.3005 0.415886 68.1056 0.719341 0.70683 1 0 -0

...

答:
From the data u provided for the house, it seems like 1 triangle is facing in one way and second is facing the opposite way.

Use rasterizer without back culling to draw this object

Body:
I am currently working on Oculus Rift PC SDK. Was trying to start off with something simpler like Tiny Room Demo(DX11). Saw this tutorial online to load a 3D model into the scene from external file (Rastertek
Tutorial 7: 3D Model Rendering)

The way the Tiny Room Demo creates model is to hardcode the coordinates and renders it

TriangleSet walls;
    walls.AddSolidColorBox(10.1f, 0.0f, 20.0f, 10.0f, 4.0f, -20.0f, 0xff808080);  // Left Wall
    walls.AddSolidColorBox(10.0f, -0.1f, 20.1f, -10.0f, 4.0f, 20.0f, 0xff808080); // Back Wall
    walls.AddSolidColorBox(-10.0f, -0.1f, 20.0f, -10.1f, 4.0f, -20.0f, 0xff808080);   // Right Wall
    Add(
        new Model(&walls, XMFLOAT3(0, 0, 0), XMFLOAT4(0, 0, 0, 1),
            new Material(
                new Texture(false, 256, 256, Texture::AUTO_WALL)
            )
        )
    );

void AddSolidColorBox(float x1, float y1, float z1, float x2, float y2, float z2, uint32_t c)
{
    AddQuad(Vertex(XMFLOAT3(x1, y2, z1), ModifyColor(c, XMFLOAT3(x1, y2, z1)), z1, x1),
            Vertex(XMFLOAT3(x2, y2, z1), ModifyColor(c, XMFLOAT3(x2, y2, z1)), z1, x2),
            Vertex(XMFLOAT3(x1, y2, z2), ModifyColor(c, XMFLOAT3(x1, y2, z2)), z2, x1),
            Vertex(XMFLOAT3(x2, y2, z2), ModifyColor(c, XMFLOAT3(x2, y2, z2)), z2, x2));
...}

AddQuad(Vertex v0, Vertex v1, Vertex v2, Vertex v3) { AddTriangle(v0, v1, v2);  AddTriangle(v3, v2, v1); }

void AddTriangle(Vertex v0, Vertex v1, Vertex v2)
{
    VALIDATE(numVertices <= (maxBuffer - 3), "Insufficient triangle set");
    for (int i = 0; i < 3; i++) Indices[numIndices++] = short(numVertices + i);
    Vertices[numVertices++] = v0;
    Vertices[numVertices++] = v1;
    Vertices[numVertices++] = v2;
}

Tried to load the model into the scene using a function from the tutorial

TriangleSet models;
    models.LoadModel("F:\\cube.txt");
    Add(
        new OBJModel(&models, XMFLOAT3(0, 0, 0), XMFLOAT4(0, 0, 0, 1),
            new OBJMaterial(
                new Texture(false, 256, 256, Texture::AUTO_WHITE)
                //new Texture(DirectX, L"wallpaper.jpg")
            )
        )
    );  //3D Model

void LoadModel(char* filename)
{
    ifstream fin;
    char input;

    // Open the model file.
    fin.open(filename);

    // Read up to the value of vertex count.
    fin.get(input);
    while (input != ':')
    {
        fin.get(input);
    }

    // Read in the vertex count.
    m_vertexCount = 0;
    fin >> m_vertexCount;

    // Read up to the beginning of the data.
    fin.get(input);
    while (input != ':')
    {
        fin.get(input);
    }
    fin.get(input);
    fin.get(input);

    // Read in the vertex data.
    for (int i = 0; i<m_vertexCount; i++)
    {
        Indices[numIndices++] = short(numVertices + i);
        //numVertices++; deleted
        fin >> Vertices[numVertices].Pos.x >> Vertices[numVertices].Pos.y >> Vertices[numVertices].Pos.z;
        fin >> Vertices[numVertices].U >> Vertices[numVertices].V;
        fin >> Normals[numVertices].Norm.x >> Normals[numVertices].Norm.y >> Normals[numVertices].Norm.z;
        Vertices[numVertices].C = ModifyColor(0xffffffff, Vertices[numVertices].Pos);
        numVertices+=1; //new statement
    }

    // Close the model file.
    fin.close();
}

I did not use the normal as from the tutorial it was meant for the texture of the object. Instead I defined the color to be solid yellow. Tried to keep the structure of loading the model as similar to Tiny Room Demo as possible.

I have used the same model, material and texture (vertex shader and pixel shader) as how Tiny Room Demo does. However what was rendered onto the scene did not appear as what it is supposed to be.

Did a step by step debugging to see if the coordinates were correctly loading into the Vertices[numVertices]. Seems like there is no issue. The file I tried to load was cube.txt

Vertex Count: 36

Data:

-1.0  1.0 -1.0 0.0 0.0  0.0  0.0 -1.0

1.0  1.0 -1.0 1.0 0.0  0.0  0.0 -1.0

-1.0 -1.0 -1.0 0.0 1.0  0.0  0.0 -1.0

-1.0 -1.0 -1.0 0.0 1.0  0.0  0.0 -1.0

1.0  1.0 -1.0 1.0 0.0  0.0  0.0 -1.0

1.0 -1.0 -1.0 1.0 1.0  0.0  0.0 -1.0

1.0  1.0 -1.0 0.0 0.0  1.0  0.0  0.0

1.0  1.0  1.0 1.0 0.0  1.0  0.0  0.0

1.0 -1.0 -1.0 0.0 1.0  1.0  0.0  0.0

1.0 -1.0 -1.0 0.0 1.0  1.0  0.0  0.0

1.0  1.0  1.0 1.0 0.0  1.0  0.0  0.0

1.0 -1.0  1.0 1.0 1.0  1.0  0.0  0.0

1.0  1.0  1.0 0.0 0.0  0.0  0.0  1.0

-1.0  1.0  1.0 1.0 0.0  0.0  0.0  1.0

1.0 -1.0  1.0 0.0 1.0  0.0  0.0  1.0

1.0 -1.0  1.0 0.0 1.0  0.0  0.0  1.0

-1.0  1.0  1.0 1.0 0.0  0.0  0.0  1.0

-1.0 -1.0  1.0 1.0 1.0  0.0  0.0  1.0

...

What was suppose to show up (except without the texture)
3D cube

What actually showed up was just fragments of triangle
TinyRoomDemo + 3D cube

Unsure what went wrong. Please do advice! Thank you very much :)

Vertex and Index buffer

struct OBJModel
{
XMFLOAT3     Pos;
XMFLOAT4     Rot;
OBJMaterial   * Fill;
DataBuffer * VertexBuffer;
DataBuffer * IndexBuffer;
int          NumIndices;

OBJModel() : Fill(nullptr), VertexBuffer(nullptr), IndexBuffer(nullptr) {};
void Init(TriangleSet * t)
{
    NumIndices = t->numIndices;
    VertexBuffer = new DataBuffer(DIRECTX.Device, D3D11_BIND_VERTEX_BUFFER, &t->Vertices[0], t->numVertices * sizeof(Vertex));
    IndexBuffer = new DataBuffer(DIRECTX.Device, D3D11_BIND_INDEX_BUFFER, &t->Indices[0], t->numIndices * sizeof(short));
}

...

DIRECTX.Context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

---------------------------------------------------------------------------------------------------------------------------------

06/06/2017 edited:
3D Model data:

Vertex Count: 798

Data:

28.3005 0.415886 -45.8282 0.7216 0.720211 0 0 -1

28.3005 -0.809079 -45.8282 0.732222 0.720211 0 0 -1

-27.7441 -0.809079 -45.8282 0.732222 0.847836 0 0 -1

28.3005 0.415886 68.1056 0.459891 0.720286 0 1 -0

28.3005 0.415886 -45.8282 0.719341 0.720286 0 1 -0

-27.7441 0.415886 -45.8282 0.719341 0.847911 0 1 -0

28.3005 -0.809079 68.1056 0.721603 0.720211 0 0 1

28.3005 0.415886 68.1056 0.732225 0.720211 0 0 1

-27.7441 0.415886 68.1056 0.732225 0.847836 0 0 1

28.3005 -0.809079 -45.8282 0.459891 0.720298 0 -1 -0

28.3005 -0.809079 68.1056 0.719341 0.720298 0 -1 -0

-27.7441 -0.809079 68.1056 0.719341 0.847923 0 -1 -0

28.3005 0.415886 68.1056 0.719341 0.70683 1 0 -0

...


问:
how to get selected row value in the KendoUI
I have a kendoUI grid.

```<code>                @(Html.Kendo().Grid<EntityVM>()
                    .Name("EntitesGrid")
                                .HtmlAttributes(new { style = "height:750px;width:100%;scrollbar-face-color: #eff7fc;" })
                    .Columns(columns =>
                    {
                        columns.Bound(e => e.Id).Hidden().IncludeInMenu(false);
                        columns.Bound(e => e.EntityVersionId).Hidden().IncludeInMenu(false);
                        columns.Bound(e => e.Name).Width("70%").Title("Entity Name");
                        columns.Bound(e => e.EIN).Width("30%");
                    })
        .ToolBar(toolBar => toolBar.Template("<a class='k-button k-button-icontext k-grid-add' id='addEntity'><span class='k-icon k-add'></span>Entity</a>" +
             "<a class='k-button k-button-icontext' id='editEntity'><span class='k-icon k-edit'></span>Edit</a>"))
                    .DataSource(dataSource => dataSource
                    .Ajax().ServerOperation(false)
                    .Model(model => model.Id(e => e.Id))
                    .Read(read => read.Action("GetEntities", "Entity", new { projectId = Request.QueryString[DataKeyNameConstants.ProjectId] })))
                    .Sortable()
                    .Scrollable()
                    .Filterable()
                    .Resizable(resize => resize.Columns(true))
                    .Reorderable(reorder => reorder.Columns(true))
                    .ColumnMenu()
                    .Selectable(s => s.Mode(GridSelectionMode.Multiple))
                    .Events(events => events.Change("entSelChange"))
            )
</code>```

now, I need to get the value of EntityVersionId from the selected Row.  but not sure how to do it.

here's my javascript function

```<code>$("#editEntity").click(function () {

    var entityGrid = $("#EntitesGrid").data("kendoGrid");

    // what should I do from here
});
</code>```

UPDATE: add code to loop all rows.

```<code>function loadPreviousEntityVersion() {

    alert("sdfsdfsdf");
    var entityGrid = $("#EntitesGrid").data("kendoGrid");
    var data = entityGrid.dataSource.data();

    for(var i = 0; i<data.length; i++) {
        var currentDataItem = data[i];
        alert(dataItem.EntityVersionId);

    }
}
</code>```

答:
If you want to select particular element use below code</p>

```<code>var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];
</code>```

Body:
I have a kendoUI grid.

                @(Html.Kendo().Grid<EntityVM>()
                    .Name("EntitesGrid")
                                .HtmlAttributes(new { style = "height:750px;width:100%;scrollbar-face-color: #eff7fc;" })
                    .Columns(columns =>
                    {
                        columns.Bound(e => e.Id).Hidden().IncludeInMenu(false);
                        columns.Bound(e => e.EntityVersionId).Hidden().IncludeInMenu(false);
                        columns.Bound(e => e.Name).Width("70%").Title("Entity Name");
                        columns.Bound(e => e.EIN).Width("30%");
                    })
        .ToolBar(toolBar => toolBar.Template("Entity" +
             "Edit"))
                    .DataSource(dataSource => dataSource
                    .Ajax().ServerOperation(false)
                    .Model(model => model.Id(e => e.Id))
                    .Read(read => read.Action("GetEntities", "Entity", new { projectId = Request.QueryString[DataKeyNameConstants.ProjectId] })))
                    .Sortable()
                    .Scrollable()
                    .Filterable()
                    .Resizable(resize => resize.Columns(true))
                    .Reorderable(reorder => reorder.Columns(true))
                    .ColumnMenu()
                    .Selectable(s => s.Mode(GridSelectionMode.Multiple))
                    .Events(events => events.Change("entSelChange"))
            )

now, I need to get the value of EntityVersionId from the selected Row.  but not sure how to do it.

here's my javascript function

$("#editEntity").click(function () {

    var entityGrid = $("#EntitesGrid").data("kendoGrid");

    // what should I do from here
});

UPDATE: add code to loop all rows.

function loadPreviousEntityVersion() {

    alert("sdfsdfsdf");
    var entityGrid = $("#EntitesGrid").data("kendoGrid");
    var data = entityGrid.dataSource.data();

    for(var i = 0; i<data.length; i++) {
        var currentDataItem = data[i];
        alert(dataItem.EntityVersionId);

    }
}

Body:
If you want to select particular element use below code

var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];


问:
Angular 4 - HTTP Interceptor
I'm trying to create HTTP Interceptor in Angular 4 but I'm having some weird error. Following is my error:

```<code>Argument of type 'Observable<Response>' is not assignable to parameter of type 'Observable<Response>'.
</code>```

Following is my Code:

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';

@Injectable()
export class HttpInterceptor extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options)); // Here is the error
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.get(url, options)); // Here is the error
    }

    post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.post(url, body, this.getRequestOptionArgs(options))); // Here is the error
    }

    put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.put(url, body, this.getRequestOptionArgs(options))); // Here is the error
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.delete(url, options)); // Here is the error
    }

    getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers(); // Here is the error
        }
        options.headers.append('Content-Type', 'application/json');
        return options;
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            if (err.status == 401 && !_.endsWith(err.url, 'api/auth/login')) {
                this._router.navigate(['/login']);
                return Observable.empty();
            } else {
                return Observable.throw(err);
            }
        });

    }

}```
</div>
</div>
</p>

<p>Does anyone know what is going wrong here? I tried debugging for 3 hours but unable to find any clue.</p>

<p><strong>Edit:</strong></p>

<p>I also tried to remove everything and written a code like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options);
}</code>```

But still it's giving same error:

Argument of type 'string | Request' is not assignable to parameter of type 'string | Request'. Type 'Request' is not assignable to type 'string | Request'.

答:
The globally available DOM typings ("lib": ["dom"] in your tsconfig) include Response and Request interfaces that are unrelated to the types used by Angular.

You need to import Response and Request from @angular/http.

Title: Angular 4 - HTTP Interceptor

Body:
I'm trying to create HTTP Interceptor in Angular 4 but I'm having some weird error. Following is my error:

Argument of type 'Observable<Response>' is not assignable to parameter of type 'Observable<Response>'.

Following is my Code:

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import * as _ from 'lodash';

@Injectable()
export class HttpInterceptor extends Http {

    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private _router: Router) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.request(url, options)); // Here is the error
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.get(url, options)); // Here is the error
    }

    post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.post(url, body, this.getRequestOptionArgs(options))); // Here is the error
    }

    put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.put(url, body, this.getRequestOptionArgs(options))); // Here is the error
    }

    delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return this.intercept(super.delete(url, options)); // Here is the error
    }

    getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers(); // Here is the error
        }
        options.headers.append('Content-Type', 'application/json');
        return options;
    }

    intercept(observable: Observable<Response>): Observable<Response> {
        return observable.catch((err, source) => {
            if (err.status == 401 && !_.endsWith(err.url, 'api/auth/login')) {
                this._router.navigate(['/login']);
                return Observable.empty();
            } else {
                return Observable.throw(err);
            }
        });

    }

}

Does anyone know what is going wrong here? I tried debugging for 3 hours but unable to find any clue.

Edit:

I also tried to remove everything and written a code like this:

request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options);
}

But still it's giving same error:

Argument of type 'string | Request' is not assignable to parameter of type 'string | Request'. Type 'Request' is not assignable to type 'string | Request'.


答:
Please re-type CloudSQL credentials: in application setting - Cloud SQL for Preview or in deployment settings for Deployments.

Also ensure that your user is Editor or Owner on Google Cloud Platform's project with CloudSQL instance. And re-check setup instructions: https://developers.google.com/appmaker/models/cloudsql

Is the app running as user or as developer (https://developers.google.com/appmaker/security/identity)?

Title: App Maker and Cloud SQL - connection issue

Body:
I am working on an app which is using Cloud SQL database. I am already connected with Cloud SQL instance using instance name, user name, password. I am able to create tables (by adding model), drop tables (by check) from App Maker level.

However I can't insert record using form. I also can't present the data in tables.

I am getting following error,

Exception: Unable to connect to database. Check the connection string,
  user name, and password. Executing query for datasource ModelSQL:
  (Error) : Unable to connect to database. Check the connection string,
  user name, and password. Executing query for datasource ModelSQL
  failed.


答:
Yes it's possible. If you aren't sure is mymap has elements and don't want to do a try except you can use the dict.get(key, default) method:

```<code>value = mymap.get('ABC', {}).get('123', None)
if values is not None:
    # Found key 123 inside mymap['ABC']
else:
    # mymap['123'] or mymap['123']['ABC'] doesn't exist
</code>```

Title: Python - Mapping a Key to a Value that is a Map

Body:
Is it possible to map a string to a map in Python. For example, if I want a map that looks like:

mymap = { 'ABC': {'123' : 56}, 'DEF': {'456' : 92}  }

Is this possible? How would I add a value to the map, or check the map to see what the value is of the 'inner map' if I am doing an iteration when mymap is empty (at the start of a loop, for example). Thanks!

Body:
Yes it's possible. If you aren't sure is mymap has elements and don't want to do a try except you can use the dict.get(key, default) method:

value = mymap.get('ABC', {}).get('123', None)
if values is not None:
    # Found key 123 inside mymap['ABC']
else:
    # mymap['123'] or mymap['123']['ABC'] doesn't exist


问:
API Status Page Response Codes
(This is sort of an abstract philosophical question. But I believe it has objective concrete answers.)

I'm writing an API, my API has a "status" page (like, https://status.github.com/).

If whatever logic I have in place to determine the status says everything is good my plan would be to return 200 OK, and a JSON response with more information about each service tested by my status page.

But what if my logic says the API is down? Say the database isn't responding or something.

I think I want to return 500 INTERNAL SERVER ERROR (or 503 SERVICE NOT AVAILABLE) along with a JSON response with more details.

However, is that breaking the HTTP Status Code spec? Would that confuse end users? My status page itself is working just fine in that case. So maybe it should return 200? But that would mean anyone using it would have to dig into the body looking for a specific parameter to determine the API's status vs. just checking the HTTP Status Code. (Also if my status page itself was broken, I'm fine with the end user taking that to mean the API is down since that's a pretty bad sign...)

Thoughts? Is there official protocol on how a status page should work?

https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

答:
For me the page should return 200 unless has problems itself. Is true that is easier to check the status code of a response than parsing but using HTTP status codes to encode application informations breaks what people (and spiders) expect. If a spider passes for your page and sees a 500 or 503 will think your site has a page with problems, not that that page is ok and is signaling that the site is down.

Also, as you notice, it wont' be possible to distinguish between the service is down and the status page is down cases, with the last the only one that should send 500. Also, what if you show more than one service like the twitter status page ? Use 200.

Related: https://stackoverflow.com/a/943021/1536382 https://stackoverflow.com/a/34324179/1536382

Title: API Status Page Response Codes


问:
Remove object if key in object is zero
I am trying to build a payload that takes in 2 values, Name and Quantity. Each quantity is associated with the name. What I am trying to do is if the quantity equals zero, then that object with the name and quantity is not added to my payload.

  var myQuantity = $('input[name="quantity[]"]').map(function() {return $(this).val();}).get();
var myName = $('[name="name[]"]').map(function(){return $(this).text();}).get();

var len = myQuantity.length;
var data = []

for (var x = 0; x < len; x++){
  var element = {
    "name"     : myName[x],
    "quantity" : myQuantity[x]
  }
  data.push(element);
}
console.log(data);```
<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>
<span name="name[]" class="name">1</span><input type="text" name="quantity[]" class="quantity" value="1"><br>
<span name="name[]" class="name">2</span><input type="text" name="quantity[]" class="quantity" value="0"><br>
<span name="name[]" class="name">3</span><input type="text" name="quantity[]" class="quantity" value="5"><br></code>```

答:
you can add that only if it is not empty.</p>

```<code>for (var x = 0; x < len; x++){
    var element = {
        "name"     : myName[x],
        "quantity" : myQuantity[x]
    }
    if(myQuantity[x] != 0){
        data.push(element);
    }
  }
  console.log(data);
</code>```

Title: Remove object if key in object is zero

Body:
I am trying to build a payload that takes in 2 values, Name and Quantity. Each quantity is associated with the name. What I am trying to do is if the quantity equals zero, then that object with the name and quantity is not added to my payload.

  var myQuantity = $('input[name="quantity[]"]').map(function() {return $(this).val();}).get();
var myName = $('[name="name[]"]').map(function(){return $(this).text();}).get();

var len = myQuantity.length;
var data = []

for (var x = 0; x < len; x++){
  var element = {
    "name"     : myName[x],
    "quantity" : myQuantity[x]
  }
  data.push(element);
}
console.log(data);

1<input type="text" name="quantity[]" class="quantity" value="1">

2<input type="text" name="quantity[]" class="quantity" value="0">

3<input type="text" name="quantity[]" class="quantity" value="5">

Body:
you can add that only if it is not empty.

for (var x = 0; x < len; x++){
    var element = {
        "name"     : myName[x],
        "quantity" : myQuantity[x]
    }
    if(myQuantity[x] != 0){
        data.push(element);
    }
  }
  console.log(data);


问:
VBA bit converter
I would like to know how to use the bitconverter method in Excel VBA.
I would like to convert 4 bytes each one placed in a difference cells in a 32 bit integer using BitConverter.ToInt32.

Can someone help me with an example to use in VBA? I think I am struggling with the syntax.

Thanks

答:
With CopyMemory:

```<code>Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)

Public Function BytesToLong(b() As Byte) As Long
  CopyMemory BytesToLong, b(LBound(b)), 4
End Function
</code>```

Without CopyMemory 1:

```<code>Private Type thebytes
  b(1 To 4) As Byte
End Type

Private Type thelong
  l As Long
End Type

Public Function BytesToLong(b() As Byte) As Long
  Dim tb As thebytes, tl As thelong
  Dim lb As Long

  lb = LBound(b)
  tb.b(1) = b(lb)
  tb.b(2) = b(lb + 1)
  tb.b(3) = b(lb + 2)
  tb.b(4) = b(lb + 3)

  LSet tl = tb

  BytesToLong = tl.l
End Function
</code>```

Without CopyMemory 2:

```<code>Public Function BytesToLong(b() As Byte) As Long
  Dim lb As Long
  lb = LBound(b)

  If (b(lb + 3) And &H80) = &H80 Then
    BytesToLong = (b(lb) + b(lb + 1) * &H100& + b(lb + 2) * &H10000 + (b(lb + 3) And Not &H80) * &H1000000) Or &H80000000
  Else
    BytesToLong = b(lb) + b(lb + 1) * &H100& + b(lb + 2) * &H10000 + b(lb + 3) * &H1000000
  End If

End Function
</code>```

Title: VBA bit converter

Body:
With CopyMemory:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (ByRef Destination As Any, ByRef Source As Any, ByVal Length As Long)

Public Function BytesToLong(b() As Byte) As Long
  CopyMemory BytesToLong, b(LBound(b)), 4
End Function

Without CopyMemory 1:

Private Type thebytes
  b(1 To 4) As Byte
End Type

Private Type thelong
  l As Long
End Type

Public Function BytesToLong(b() As Byte) As Long
  Dim tb As thebytes, tl As thelong
  Dim lb As Long

  lb = LBound(b)
  tb.b(1) = b(lb)
  tb.b(2) = b(lb + 1)
  tb.b(3) = b(lb + 2)
  tb.b(4) = b(lb + 3)

  LSet tl = tb

  BytesToLong = tl.l
End Function

Without CopyMemory 2:

Public Function BytesToLong(b() As Byte) As Long
  Dim lb As Long
  lb = LBound(b)

  If (b(lb + 3) And &H80) = &H80 Then
    BytesToLong = (b(lb) + b(lb + 1) * &H100& + b(lb + 2) * &H10000 + (b(lb + 3) And Not &H80) * &H1000000) Or &H80000000
  Else
    BytesToLong = b(lb) + b(lb + 1) * &H100& + b(lb + 2) * &H10000 + b(lb + 3) * &H1000000
  End If

End Function


问:
Using Javascript to hide and show options
In the drop down menu below I am trying to make it show other sections or display multiple when selected..

```<code><label>Calls</label>
<select id = "callList">
    <option value = "1">one</option>
    <option value = "2">two</option>
    <option value = "3">three</option>
    <option value = "4">four</option>
</select>
<select id = "Split">
    <option value = "Quality1">Sam's</option>
    <option value = "Quality2">Walmart</option>
</select>
</code>```

so if someone picks option 2 it will display option 1 and 2 but hide the rest.
I am trying to use the js posted below to get it to display correctly but it wont.

```<code>function check() {
    var dropdown = document.getElementById("callList");
    var current_value = dropdown.options[dropdown.selectedIndex].value;

    if (current_value == "1") {
        document.getElementById("Split").style.display = "block";
    }
    else {
        document.getElementById("Split").style.display = "none";
    }
}
</code>```

答:
You need to initiate the event for the Dropdown.
In case of select HTML element you can use the onchange event handler to respond to the change in selection for the DropDown.

function check() {
var dropdown = document.getElementById("callList");
var current_value = dropdown.options[dropdown.selectedIndex].value;
if (current_value == "1") {
    document.getElementById("Split").style.display = "block";

}
else {
    document.getElementById("Split").style.display = "none";

}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>Calls</label>
<select id = "callList" onchange="check()">
    <option value = "1">one</option>
    <option value = "2">two</option>
    <option value = "3">three</option>
    <option value = "4">four</option>
</select>
<select id = "Split">
    <option value = "Quality1">Sam's</option>
    <option value = "Quality2">Walmart</option>
</select></code>```

Body:
In the drop down menu below I am trying to make it show other sections or display multiple when selected..

Calls
<select id = "callList">
    <option value = "1">one</option>
    <option value = "2">two</option>
    <option value = "3">three</option>
    <option value = "4">four</option>
</select>
<select id = "Split">
    <option value = "Quality1">Sam's</option>
    <option value = "Quality2">Walmart</option>
</select>

so if someone picks option 2 it will display option 1 and 2 but hide the rest.
I am trying to use the js posted below to get it to display correctly but it wont.

function check() {
    var dropdown = document.getElementById("callList");
    var current_value = dropdown.options[dropdown.selectedIndex].value;

    if (current_value == "1") {
        document.getElementById("Split").style.display = "block";
    }
    else {
        document.getElementById("Split").style.display = "none";
    }
}

Body:
You need to initiate the event for the Dropdown.
In case of select HTML element you can use the onchange event handler to respond to the change in selection for the DropDown.

function check() {
var dropdown = document.getElementById("callList");
var current_value = dropdown.options[dropdown.selectedIndex].value;
if (current_value == "1") {
    document.getElementById("Split").style.display = "block";

}
else {
    document.getElementById("Split").style.display = "none";

}
}

<label>Calls</label>
<select id = "callList" onchange="check()">
    <option value = "1">one</option>
    <option value = "2">two</option>
    <option value = "3">three</option>
    <option value = "4">four</option>
</select>
<select id = "Split">
    <option value = "Quality1">Sam's</option>
    <option value = "Quality2">Walmart</option>
</select>