问:
Wait for CSS property to change before asserting the change
I'm using python webdriver and I'm trying to make the system wait until the border colour of a password field has changed after a submit button has been clicked. The colour fades from one to the other and I can get the desired result using this: -

```<code>password_border_colour_after_click = ""
count = 0
while password_border_colour_after_click != "rgba(169, 68, 66, 1)":
    password_border_colour_after_click = self.driver.find_element_by_name("password").value_of_css_property('border-bottom-color')
    time.sleep(0.1)
    count += 1
    if password_border_colour_after_click == "rgba(169, 68, 66, 1)":
        break
    elif count > 50:
        break
assert password_border_colour_after_click == "rgba(169, 68, 66, 1)"
</code>```

It feels a bit clunky and is probably awful code so I was thinking there must be a way to package it all up in a wait command, but I can't get the syntax right.

Is it possible?

答:
TL;DR;

Selenium API has a "wait for ..." functionality :

http://selenium-python.readthedocs.io/waits.html

Implement a expected_condition and then combine it with wait

```<code>element = WebDriverWait(driver, 10)
             .until(custom_expected_condition((By.ID, 'search-input'), argA, argB))
</code>```

Wait

Good to know is that "wait" runs synchronously (blocks the thread) and can be combined with one of the following, out of the box:

title_is

title_contains

presence_of_element_located

visibility_of_element_located

visibility_of

presence_of_all_elements_located

text_to_be_present_in_element

text_to_be_present_in_element_value

frame_to_be_available_and_switch_to_it

invisibility_of_element_located

element_to_be_clickable

staleness_of

element_to_be_selected

element_located_to_be_selected

element_selection_state_to_be

element_located_selection_state_to_be

alert_is_present

As you can see there is no element_has_style_value condition, however one can always extend the "wait" with its own implementation.

Out of the docs a custom expected condition looks like so:

```<code>class element_has_css_class(object):
  """An expectation for checking that an element has a particular css class.

  locator - used to find the element
  returns the WebElement once it has the particular css class
  """
  def __init__(self, locator, css_class):
    self.locator = locator
    self.css_class = css_class

  def __call__(self, driver):
    element = driver.find_element(*self.locator)   # Finding the referenced element
    if self.css_class in element.get_attribute("class"):
        return element
    else:
        return False
</code>```

And its usage is:

```<code># Wait until an element with id='myNewInput' has class 'myCSSClass'
wait = WebDriverWait(driver, 10)
element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass"))
</code>```

Possible solution

Putting everything together for an asset page like so : https://output.jsbin.com/xutipu

One can implement this:

```<code>class element_has_css_value(object):
  """An expectation for checking that an element has a particular css property and value.

  locator - used to find the element
  returns the WebElement once it has the particular css property and value
  """
  def __init__(self, locator, css_property, css_value):
    self.locator = locator
    self.css_property = css_property
    self.css_value = css_value

  def matchPropertyAndValue(self, css_property, css_value):

      return css_property == self.css_property and css_value  == self.css_value;

  def extractPropertyAndValue(self, cssStatement):
    keyValue = cssStatement.split(':')
    if len(keyValue) == 2:
        key = keyValue[0].strip();
        value = keyValue[1].strip();
        return (key, value)
    return (None, None)

  def findProperty(self, entries):
    foundProperty = False
    for entry in entries:
      (css_property, css_value) = self.extractPropertyAndValue(entry)
      if css_value is None:
          continue
      foundProperty = self.matchPropertyAndValue(css_property, css_value);
      if foundProperty :
          break;
    return foundProperty

  def __call__(self, driver):
    element = driver.find_element(*self.locator)   # Finding the referenced element
    styles = element.get_attribute("style")
    entries = styles.split(';')
    foundProperty = self.findProperty(entries);

    if foundProperty :
        return element
    else:
        return False
</code>```

and use it like this :

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://output.jsbin.com/xutipu")
button = None;
try:
    button = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "search-button"))
    )
except e:
    print(e);
    driver.quit()

button.send_keys(Keys.RETURN)

try :
    wait = WebDriverWait(driver, 10)
    element = wait.until(element_has_css_value((By.ID, 'search-input'), "border-color", "rgb(169, 68, 66)"))
    assert element;
    print('Success');
finally:
    driver.quit()
</code>```

Body:
I'm using python webdriver and I'm trying to make the system wait until the border colour of a password field has changed after a submit button has been clicked. The colour fades from one to the other and I can get the desired result using this: -

password_border_colour_after_click = ""
count = 0
while password_border_colour_after_click != "rgba(169, 68, 66, 1)":
    password_border_colour_after_click = self.driver.find_element_by_name("password").value_of_css_property('border-bottom-color')
    time.sleep(0.1)
    count += 1
    if password_border_colour_after_click == "rgba(169, 68, 66, 1)":
        break
    elif count > 50:
        break
assert password_border_colour_after_click == "rgba(169, 68, 66, 1)"

It feels a bit clunky and is probably awful code so I was thinking there must be a way to package it all up in a wait command, but I can't get the syntax right.

Is it possible?

Body:
TL;DR;

Selenium API has a "wait for ..." functionality :

http://selenium-python.readthedocs.io/waits.html

Implement a expected_condition and then combine it with wait

element = WebDriverWait(driver, 10)
             .until(custom_expected_condition((By.ID, 'search-input'), argA, argB))

Wait

Good to know is that "wait" runs synchronously (blocks the thread) and can be combined with one of the following, out of the box:

title_is

title_contains

presence_of_element_located

visibility_of_element_located

visibility_of

presence_of_all_elements_located

text_to_be_present_in_element

text_to_be_present_in_element_value

frame_to_be_available_and_switch_to_it

invisibility_of_element_located

element_to_be_clickable

staleness_of

element_to_be_selected

element_located_to_be_selected

element_selection_state_to_be

element_located_selection_state_to_be

alert_is_present

As you can see there is no element_has_style_value condition, however one can always extend the "wait" with its own implementation.

Out of the docs a custom expected condition looks like so:

class element_has_css_class(object):
  """An expectation for checking that an element has a particular css class.

  locator - used to find the element
  returns the WebElement once it has the particular css class
  """
  def __init__(self, locator, css_class):
    self.locator = locator
    self.css_class = css_class

  def __call__(self, driver):
    element = driver.find_element(*self.locator)   # Finding the referenced element
    if self.css_class in element.get_attribute("class"):
        return element
    else:
        return False

And its usage is:

# Wait until an element with id='myNewInput' has class 'myCSSClass'
wait = WebDriverWait(driver, 10)
element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass"))

Possible solution

Putting everything together for an asset page like so : https://output.jsbin.com/xutipu

One can implement this:

class element_has_css_value(object):
  """An expectation for checking that an element has a particular css property and value.

  locator - used to find the element
  returns the WebElement once it has the particular css property and value
  """
  def __init__(self, locator, css_property, css_value):
    self.locator = locator
    self.css_property = css_property
    self.css_value = css_value

  def matchPropertyAndValue(self, css_property, css_value):

      return css_property == self.css_property and css_value  == self.css_value;

  def extractPropertyAndValue(self, cssStatement):
    keyValue = cssStatement.split(':')
    if len(keyValue) == 2:
        key = keyValue[0].strip();
        value = keyValue[1].strip();
        return (key, value)
    return (None, None)

  def findProperty(self, entries):
    foundProperty = False
    for entry in entries:
      (css_property, css_value) = self.extractPropertyAndValue(entry)
      if css_value is None:
          continue
      foundProperty = self.matchPropertyAndValue(css_property, css_value);
      if foundProperty :
          break;
    return foundProperty

  def __call__(self, driver):
    element = driver.find_element(*self.locator)   # Finding the referenced element
    styles = element.get_attribute("style")
    entries = styles.split(';')
    foundProperty = self.findProperty(entries);

    if foundProperty :
        return element
    else:
        return False

and use it like this :

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://output.jsbin.com/xutipu")
button = None;
try:
    button = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "search-button"))
    )
except e:
    print(e);
    driver.quit()

button.send_keys(Keys.RETURN)

try :
    wait = WebDriverWait(driver, 10)
    element = wait.until(element_has_css_value((By.ID, 'search-input'), "border-color", "rgb(169, 68, 66)"))
    assert element;
    print('Success');
finally:
    driver.quit()


来源: stackexchange

问:
How to get DataAnnotation Display Name?
I have EF model class. for that I created MetadataType for that partial class.

Now I need to read or get all of these displayname of the properties of the object from c#. So I can use the in Excel Header row.

```<code>[MetadataType(typeof(vwGridMetadata))]
public partial class vwGrid
{

}

public class vwGridMetadata
{
    [Display(Name = "Note ID")]
    public int intNoteID { get; set; }
    [Display(Name = "Global Number")]
    public string strGlobalLoanNumber { get; set; }
    [Display(Name = "Data Source ID")]
    public Nullable<int> intDataSourceID { get; set; }
    [Display(Name = "Sample ID")]
    ....
}
</code>```

vwGrid grd = new vwGrid;

Here I want get all properties displayname in iteration. So I can add them to excel Header row and cells. How to do that?

答:
ASP.Net Core 2 :   </p>

```<code> var listOfFieldNames = typeof(vwGridMetadata)
                    .GetProperties()
                    .Select(f => f.GetCustomAttribute<DisplayAttribute>())
                    .Where(x => x != null)
                    .Select(x=>x.Name)
                    .ToList();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get DataAnnotation Display Name?

Body:
I have EF model class. for that I created MetadataType for that partial class.

Now I need to read or get all of these displayname of the properties of the object from c#. So I can use the in Excel Header row.

[MetadataType(typeof(vwGridMetadata))]
public partial class vwGrid
{

}

public class vwGridMetadata
{
    [Display(Name = "Note ID")]
    public int intNoteID { get; set; }
    [Display(Name = "Global Number")]
    public string strGlobalLoanNumber { get; set; }
    [Display(Name = "Data Source ID")]
    public Nullable<int> intDataSourceID { get; set; }
    [Display(Name = "Sample ID")]
    ....
}

vwGrid grd = new vwGrid;

Here I want get all properties displayname in iteration. So I can add them to excel Header row and cells. How to do that?

Body:
ASP.Net Core 2 :

 var listOfFieldNames = typeof(vwGridMetadata)
                    .GetProperties()
                    .Select(f => f.GetCustomAttribute<DisplayAttribute>())
                    .Where(x => x != null)
                    .Select(x=>x.Name)
                    .ToList();


问:
How can I add a link for a rate button with swift?
First I don't know how to get the link before I submit my app, and if the link is for each country app store or is it universal?

Also I don't know if the way to do it is just by putting the link there like:

```<code>@IBAction func rate(sender: AnyObject) {
    UIApplication.sharedApplication().openURL(NSURL(string : "webLinkHere")!)
}
</code>```

Or should I use another way to do this?

Thanks

答:
Swift 4

```<code>let url = URL(string: "itms-apps:itunes.apple.com/us/app/apple-store/id\(YOURAPPID)?mt=8&action=write-review")!
UIApplication.shared.openURL(url)
</code>```

Body:
First I don't know how to get the link before I submit my app, and if the link is for each country app store or is it universal?

Also I don't know if the way to do it is just by putting the link there like:

@IBAction func rate(sender: AnyObject) {
    UIApplication.sharedApplication().openURL(NSURL(string : "webLinkHere")!)
}

Or should I use another way to do this?

Thanks

Body:
Swift 4

let url = URL(string: "itms-apps:itunes.apple.com/us/app/apple-store/id\(YOURAPPID)?mt=8&action=write-review")!
UIApplication.shared.openURL(url)


问:
JavaScript not executed in WKWebView
Since I'm going a bit crazy with this one, I've decided to give it another try and post about it here.

So...

I have a simple Swift/Cocoa application with a WKWebView in it.

I load a local HTML file (which - along with the rest of the .css/.js dependencies - is being copied to the bundle inside a /web folder).

Here's the complete code:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>IBAN Validator</title>
        <meta name="viewport" content="width=device-width"/>
        <meta charset="UTF-8">

        <link href="style/font-awesome.min.css" type="text/css" rel="stylesheet"/>
        <link href="style/electriq.css" type="text/css" rel="stylesheet"/>
        <link href="style/custom.css" type="text/css" rel="stylesheet" />
    </head>
    <body>
        <!-- window/ -->
        <div class="window">
            <div class="content" style="text-align: center">
                <div class="panel">
                    <input id="iban" type="text" style="text-align:center;"><br/>
                    <div style="position: relative; max-width: 150px; width: 100%; margin: 0 auto">
                        <a id="validateButton" href="#" class="button" style="width:150px;">Validate</a>
                        <span id="resultValid" style="position:absolute; left: calc(100% + 20px); top: 10%; color: green; font-size: 20px; display:none;"><i class="fa fa-check"></i></span>
                        <span id="resultInvalid" style="position:absolute; left: calc(100% + 20px); top: 10%; color: red; font-size: 20px; display:none;"><i class="fa fa-close"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <!-- /window -->

        <div id="loader_overlay" style="padding-top:10%">
            <i class="fa fa-circle-o-notch fa-spin fa-3x fa-fw"></i><br/>
        </div>

        <!-- scripts/ -->
        <script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
        <script src="jquery.min.js" type="text/javascript"></script>
        <script>
            if (typeof window.jQuery !== 'undefined') {
                window.document.getElementById("loader_overlay").innerHTML += ".";
            } else {
                window.document.getElementById("loader_overlay").innerHTML += "x";
            }
        </script>
        <script src="handlebars.min.js" type="text/javascript"></script>
        <script>
            if (typeof window.Handlebars !== 'undefined') {
                window.document.getElementById("loader_overlay").innerHTML += ".";
            } else {
                window.document.getElementById("loader_overlay").innerHTML += "x";
            }
        </script>
        <script src="bridgecommander.js" type="text/javascript"></script>
        <script>
            if (typeof window.BridgeCommander !== 'undefined') {
                window.document.getElementById("loader_overlay").innerHTML += ".";
            } else {
                window.document.getElementById("loader_overlay").innerHTML += "x";
            }
        </script>
        <script src="iban.js" type="text/javascript"></script>
        <script>
            if (typeof window.IBAN !== 'undefined') {
                window.document.getElementById("loader_overlay").innerHTML += ".";
            } else {
                window.document.getElementById("loader_overlay").innerHTML += "x";
            }
        </script>
        <!-- <script src="app.js" type="text/javascript"></script> -->
        <script>

            // Generated by CoffeeScript 2.0.2
            var doValidate;

            window.appLoaded = true;
            window.document.getElementById("loader_overlay").innerHTML += ".";
            BridgeCommander.call("echo", "Before: onload");
            window.document.getElementById("loader_overlay").innerHTML += ".";

            window.onload = function() {
              BridgeCommander.call("echo", "Inside: onload");
              document.getElementById("loader_overlay").style.display = 'none';
              return $("#validateButton").on("click", doValidate);
            };
            window.document.getElementById("loader_overlay").innerHTML += ".";
            BridgeCommander.call("echo", "After: onload");

            doValidate = function() {
              var iban, valid;
              iban = $("#iban").val();
              valid = IBAN.isValid(iban);
              if (valid) {
                $("#resultValid").show();
                $("#resultInvalid").hide();
                $("#validateButton").removeClass("invalid").addClass("valid");
                BridgeCommander.call("echo", `Validating: ${iban}, Result: valid`);
              } else {
                $("#resultValid").hide();
                $("#resultInvalid").show();
                $("#validateButton").removeClass("valid").addClass("invalid");
                BridgeCommander.call("echo", `Validating: ${iban}, Result: invalid`);
              }
              setTimeout(function() {
                $("#validateButton").removeClass("valid").removeClass("invalid");
                $("#resultValid").hide();
                return $("#resultInvalid").hide();
              }, 3000);
              return false;
            };
            window.document.getElementById("loader_overlay").innerHTML += ".";

            if (typeof window.appLoaded !== 'undefined') {
                window.document.getElementById("loader_overlay").innerHTML += ".";
            } else {
                window.document.getElementById("loader_overlay").innerHTML += "x";
            }
        </script>
        <script>if (window.module) module = window.module;</script>
        <!-- /scripts -->
    </body>

</html>
</code>```

Important Note: Here (meaning on my Mac - and everyone's Mac with 10.3.1 I've tried this on) everything works fine. When I upload the exact same binary to the App Store for review, I keep getting the same "error" screenshot, signifying none of the code within my last  block gets executed. (after the window.appLoaded = true part).

What could be going on? I've literally tried anything to debug this (hence, the numerous window.document.getElementById thing, adding dots to make sure everything worked), but still nothing.

As you can see, I'm loading several scripts (which according to my tests load fine), and I also have several pieces of inline JS code (which still work fine). Except for the last one! (which, no matter what, even from an external file, seems to refuse to load...)

Again, I thought about sth being cached, I don't know, but I remind you that it - apparently -- works everywhere apart from the Review team's machine :S

Any idea would be welcome!

P.S. In case something is not clear, please feel free to ask me anything

Update: (28/11/2017) Tried the whole thing with a simple - old-style - WebView (in case it had to do with the WKWebView) and still my app gets rejected. Or to be precise, my app (exact version, same everything) runs fine everywhere, except for the guy that reviews it.

答:
This could be because the browser does not know how to parse the contents of the script tags

 tags require the type attribute on them most browsers will assume it's the same as the last one but as none of your code containing script tags specifies the type it might not know how to parse them the script support more than javascript for example VBScript to whenever you open a  to inside the .

Following on from this if you have jQuery why are you mixing jQuery and pure Javascript if you have jQuery use it's smaller code and cleaner

```<code> (function($){
     $(function(){
         window.appLoaded = true;
         $("loader_overlay").append(".");
         BridgeCommander.call("echo", "Before: onload");
         $("loader_overlay").append(".");

         $("loader_overlay").append(".");
         BridgeCommander.call("echo", "After: onload");

         function doValidate() {
             var iban, valid;
             iban = $("#iban").val();
             valid = IBAN.isValid(iban);
             if (valid) {
                 $("#resultValid").show();
                 $("#resultInvalid").hide();
                 $("#validateButton").removeClass("invalid")
                                     .addClass("valid");
                 BridgeCommander.call("echo", `Validating: ${iban}, Result: valid`);
             } else {
                 $("#resultValid").hide();
                 $("#resultInvalid").show();
                 $("#validateButton").removeClass("valid")
                                     .addClass("invalid");
                 BridgeCommander.call("echo", `Validating: ${iban}, Result: invalid`);
             }

             setTimeout(function() {
                 $("#validateButton").removeClass("valid")
                                     .removeClass("invalid");
                 $("#resultValid").hide();
                 return $("#resultInvalid").hide();
             }, 3000);
             return false;
        };

         (function(doValidate) {
             BridgeCommander.call("echo", "Inside: onload");
             $("loader_overlay").css("display",'none');
             return $("#validateButton").on("click", doValidate);
         })(doValidate);

         window.document.getElementById("loader_overlay").innerHTML += ".";

         if (typeof window.appLoaded !== 'undefined') {
             window.document.getElementById("loader_overlay").innerHTML += ".";
         } else {
             window.document.getElementById("loader_overlay").innerHTML += "x";
         }
         if (window.module){ module = window.module; }
    });
});
</code>```

On another note please get rid of all your file loading checks. so all of the following code blocks

```<code>if (typeof window.Handlebars !== 'undefined') {
    window.document.getElementById("loader_overlay").innerHTML += ".";
} else {
    window.document.getElementById("loader_overlay").innerHTML += "x";
}
</code>```

They are only needed for debugging and you know it's Web Kit if the file loads on one it loads on all. so you don't need these check's they are just using phone processing power and adding work to your app for no good reason. other than to put a . in the overlay...

and again all

Title: JavaScript not executed in WKWebView

Body:
Since I'm going a bit crazy with this one, I've decided to give it another try and post about it here.

So...

I have a simple Swift/Cocoa application with a WKWebView in it.

I load a local HTML file (which - along with the rest of the .css/.js dependencies - is being copied to the bundle inside a /web folder).

Here's the complete code:

<!DOCTYPE html>

        <title>IBAN Validator</title>
        <meta name="viewport" content="width=device-width"/>
        <meta charset="UTF-8">

        <link href="style/font-awesome.min.css" type="text/css" rel="stylesheet"/>
        <link href="style/electriq.css" type="text/css" rel="stylesheet"/>
        <link href="style/custom.css" type="text/css" rel="stylesheet" />

                    <input id="iban" type="text" style="text-align:center;">

                        Validate

Important Note: Here (meaning on my Mac - and everyone's Mac with 10.3.1 I've tried this on) everything works fine. When I upload the exact same binary to the App Store for review, I keep getting the same "error" screenshot, signifying none of the code within my last  block gets executed. (after the window.appLoaded = true part).

What could be going on? I've literally tried anything to debug this (hence, the numerous window.document.getElementById thing, adding dots to make sure everything worked), but still nothing.

As you can see, I'm loading several scripts (which according to my tests load fine), and I also have several pieces of inline JS code (which still work fine). Except for the last one! (which, no matter what, even from an external file, seems to refuse to load...)

Again, I thought about sth being cached, I don't know, but I remind you that it - apparently -- works everywhere apart from the Review team's machine :S

Any idea would be welcome!

P.S. In case something is not clear, please feel free to ask me anything

Update: (28/11/2017) Tried the whole thing with a simple - old-style - WebView (in case it had to do with the WKWebView) and still my app gets rejected. Or to be precise, my app (exact version, same everything) runs fine everywhere, except for the guy that reviews it.

Body:
This could be because the browser does not know how to parse the contents of the script tags

<script></script> tags require the type attribute on them most browsers will assume it's the same as the last one but as none of your code containing script tags specifies the type it might not know how to parse them the script support more than javascript for example VBScript to whenever you open a <script> for javascript it should be <script type="text/javascript">

The other problem could be the window.onload I would recommend you change it to the DOMContentLoaded event and use a closure to make sure it executes the code.

More so why are you not loading jQuery in the head tag where it's supposed to be loaded move <script src="jquery.min.js" type="text/javascript"></script> to inside the <head></head>.

Following on from this if you have jQuery why are you mixing jQuery and pure Javascript if you have jQuery use it's smaller code and cleaner

 (function($){
     $(function(){
         window.appLoaded = true;
         $("loader_overlay").append(".");
         BridgeCommander.call("echo", "Before: onload");
         $("loader_overlay").append(".");

         $("loader_overlay").append(".");
         BridgeCommander.call("echo", "After: onload");

         function doValidate() {
             var iban, valid;
             iban = $("#iban").val();
             valid = IBAN.isValid(iban);
             if (valid) {
                 $("#resultValid").show();
                 $("#resultInvalid").hide();
                 $("#validateButton").removeClass("invalid")
                                     .addClass("valid");
                 BridgeCommander.call("echo", `Validating: ${iban}, Result: valid`);
             } else {
                 $("#resultValid").hide();
                 $("#resultInvalid").show();
                 $("#validateButton").removeClass("valid")
                                     .addClass("invalid");
                 BridgeCommander.call("echo", `Validating: ${iban}, Result: invalid`);
             }

             setTimeout(function() {
                 $("#validateButton").removeClass("valid")
                                     .removeClass("invalid");
                 $("#resultValid").hide();
                 return $("#resultInvalid").hide();
             }, 3000);
             return false;
        };

         (function(doValidate) {
             BridgeCommander.call("echo", "Inside: onload");
             $("loader_overlay").css("display",'none');
             return $("#validateButton").on("click", doValidate);
         })(doValidate);

         window.document.getElementById("loader_overlay").innerHTML += ".";

         if (typeof window.appLoaded !== 'undefined') {
             window.document.getElementById("loader_overlay").innerHTML += ".";
         } else {
             window.document.getElementById("loader_overlay").innerHTML += "x";
         }
         if (window.module){ module = window.module; }
    });
});

On another note please get rid of all your file loading checks. so all of the following code blocks

if (typeof window.Handlebars !== 'undefined') {
    window.document.getElementById("loader_overlay").innerHTML += ".";
} else {
    window.document.getElementById("loader_overlay").innerHTML += "x";
}

They are only needed for debugging and you know it's Web Kit if the file loads on one it loads on all. so you don't need these check's they are just using phone processing power and adding work to your app for no good reason. other than to put a . in the overlay...

and again all <script src=... should be inside the <head> tags, in this case, all of your code should be inside the script tags and using jQuery read as my above version does.

How are you testing this App on the Mac are you using the iPhone emulator? or a real iPhone to test i would always recommend the latter. and have you tested in on one of these as you don't seem to say you have, if not get a device registered for testing on your developer account create the keys to test and build a test version then use Safari or chromes remote debugging tools on the WebView and make sure it all works.


问:
Efficiently selecting latest charge per patient
I've got three tables in SQL Server 2005 (relevant rows included):

```<code>Patient (560K rows, has many Appts)
    ID (PK, Clustered)
Appt (5.8M rows, has many ApptCPTs)
    ID (PK, Unique, Non-clustered)
    PatientID (Indexed, Non-unique, Non-clustered)
ApptCPT (13.4M rows)
    ID (PK, Clustered)
    ApptID (Indexed, Non-unique, Non-clustered)
    CPTID (Indexed, Non-unique, Non-clustered)
</code>```

I want to get the latest ApptCPT for each CPT code, for each patient, but the query I've got so far takes about a minute to return ~7M rows.

My current query:

```<code>SELECT
    p.ID AS PatientID,
    MAX(ac.ID) AS ApptCPTID,
    ac.CPTID
FROM
    Patient p
INNER JOIN Appt a ON a.PatientID = p.ID
INNER JOIN ApptCPT ac ON ac.ApptID = a.ID
GROUP BY
    p.ID, ac.CPTID
ORDER BY
    p.ID, ac.CPTID
</code>```

Example output:

```<code>PatientID    ApptCPTID    CPTID
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258166      77080
123456789    18627813     80053
123456789    18627814     80061
</code>```

If I take the MAX out and put ac.ID in the GROUP BY clause, I can see that I'm getting the correct data with my original query, because it's getting the last ApptCPT containing that CPTID for that patient, but it's horribly slow. For reference, here's the same output not using the MAX clause:

```<code>PatientID    ApptCPTID    CPTID
123456789    18126508     3088
123456789    4596004      3088
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    4595928      3551
123456789    9989218      3551
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258050      77057
123456789    5258166      77080
123456789    4595932      80053
123456789    18126505     80053
123456789    9989223      80053
123456789    18627813     80053
123456789    18627814     80061
</code>```

Anyone have any ideas for making it (hopefully) much, much faster?

答:
A minute to get back 7m rows? I doubt very much that you'll be able to do better unless you can convince your DBAs to add some indices to these tables and/or do some refactoring.

And while I'm pretty sure you're not able to change things, I'd argue that your data model is incorrect. From an E-R modelling perspective:

Appointments are entities dependent upon the Patient (e.g., the existence of an appointment is predicated upon the existence of the patient who made the appointment. If a particular patient is deleted from the patient table, then any appointments tied to that patient must also be deleted.)

It appears to me that the ApptCPT table is actually an associative entity, dependent on both Appt and CPT, that implements a many:many relationship between Appt and CPT (there is a CPT table, correct?, as defined in the entity-relationship model.

The primary key of a dependent entity is a composition of the primary key of the entity/entities upon which it depends, plus whatever other attributes contribute to the uniqueness of the dependent entity.

This means that PatientID get distributed down to Appt and becomes part of its primary key, and all the components of the new Appt primary key get distributed down to ApptCPT, to become a part of its primary key. Once that refactoring is done, your primary keys should be as follows:

Patient Table. PatientID

Appt. PatientID+ID.

ApptCPT. PatientID+ID+CptID.
This assumes that the combination of appt+cpt is unique. If a given CPT code can be associated multiple times with a single Appt, then, of course, you'll need to add in the ID column.

Now your query is a lot simpler: you just have to look at a single table (ApptCpt) and your query will almost certainly have a covering index.

Cheers!

ContentLicense: CC BY-SA 2.5

Body:
I've got three tables in SQL Server 2005 (relevant rows included):

Patient (560K rows, has many Appts)
    ID (PK, Clustered)
Appt (5.8M rows, has many ApptCPTs)
    ID (PK, Unique, Non-clustered)
    PatientID (Indexed, Non-unique, Non-clustered)
ApptCPT (13.4M rows)
    ID (PK, Clustered)
    ApptID (Indexed, Non-unique, Non-clustered)
    CPTID (Indexed, Non-unique, Non-clustered)

I want to get the latest ApptCPT for each CPT code, for each patient, but the query I've got so far takes about a minute to return ~7M rows.

My current query:

SELECT
    p.ID AS PatientID,
    MAX(ac.ID) AS ApptCPTID,
    ac.CPTID
FROM
    Patient p
INNER JOIN Appt a ON a.PatientID = p.ID
INNER JOIN ApptCPT ac ON ac.ApptID = a.ID
GROUP BY
    p.ID, ac.CPTID
ORDER BY
    p.ID, ac.CPTID

Example output:

PatientID    ApptCPTID    CPTID
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258166      77080
123456789    18627813     80053
123456789    18627814     80061

If I take the MAX out and put ac.ID in the GROUP BY clause, I can see that I'm getting the correct data with my original query, because it's getting the last ApptCPT containing that CPTID for that patient, but it's horribly slow. For reference, here's the same output not using the MAX clause:

PatientID    ApptCPTID    CPTID
123456789    18126508     3088
123456789    4596004      3088
123456789    18627724     3088
123456789    7647238      3388
123456789    18627723     3419
123456789    9989220      3419
123456789    12190141     3448
123456789    4595928      3551
123456789    9989218      3551
123456789    18627721     3551
123456789    17264224     71020
123456789    15933265     77052
123456789    10095897     77057
123456789    5258050      77057
123456789    5258166      77080
123456789    4595932      80053
123456789    18126505     80053
123456789    9989223      80053
123456789    18627813     80053
123456789    18627814     80061

Anyone have any ideas for making it (hopefully) much, much faster?


问:
Pure CSS Parallax Inner Scrollbar Issue
Like a lot of people I saw Keith Clark's pure css implementation of parallax (Keith Clark's Tutorial) and really liked it a lot.

When trying to implement it, I get an inner vertical scrollbar around the overflowed vertical parallax content (not expected), as well as the outer vertical scrollbar that pertains to the static content that extends outside the vertical overflow of the screen (expected). I was wanting only one vertical scrollbar that controls the entire page (parallax group plus static content). When scrolling up/down with this, the parallax effect can be seen in the parallax group as well as moving static content in and out of view.

What changes do I need to make?

.parallax_group {
    position: relative;
    height: 100vh;
    transform-style: preserve-3d;
}

.parallax {
    perspective: 1px;
    perspective-origin-x: 100%;
    height: 100vh;
    overflow-x: hidden;
    overflow-y: auto;
}

.parallax_layer {
    position: absolute;
    transform-origin-x: 100%;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;

    font-size: 200%;

}

.parallax_layer--base {
    transform: translateZ(0) scale(1);
    background-color: red;
}

.parallax_layer--back {
    transform: translateZ(-1px) scale(2);
    background-color: blue;
}

.parallax_layer--deep {
    transform: translateZ(-2px) scale(3);
    background-color: green;
}

.static_content {
  height: 300px;
  background-color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parallax">
  <div class="parallax_group">
    <div class="parallax_layer parallax_layer--back">
      <p>Back Layer</p>
    </div>

    <div class="parallax_layer parallax_layer--base">
      <p>Base Layer</p>
    </div>

    <div class="parallax_layer parallax_layer--deep">
      <p>Deep Layer</p>
    </div>
  </div>

</div>

<div class="static_content">

</div></code>```

答:
I have been trying to solve the same problem. What worked for me was the following:

body, html {
  overflow: hidden;
}

* {
  margin:0;
  padding:0;
}```

You can see this in Keith Clark's demo3 here. It works for me on Chrome and Firefox for Mac, not sure yet about other environments.

Title: Pure CSS Parallax Inner Scrollbar Issue

Body:
Like a lot of people I saw Keith Clark's pure css implementation of parallax (Keith Clark's Tutorial) and really liked it a lot.

When trying to implement it, I get an inner vertical scrollbar around the overflowed vertical parallax content (not expected), as well as the outer vertical scrollbar that pertains to the static content that extends outside the vertical overflow of the screen (expected). I was wanting only one vertical scrollbar that controls the entire page (parallax group plus static content). When scrolling up/down with this, the parallax effect can be seen in the parallax group as well as moving static content in and out of view.

What changes do I need to make?

.parallax_group {
    position: relative;
    height: 100vh;
    transform-style: preserve-3d;
}

.parallax {
    perspective: 1px;
    perspective-origin-x: 100%;
    height: 100vh;
    overflow-x: hidden;
    overflow-y: auto;
}

.parallax_layer {
    position: absolute;
    transform-origin-x: 100%;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;

    font-size: 200%;

}

.parallax_layer--base {
    transform: translateZ(0) scale(1);
    background-color: red;
}

.parallax_layer--back {
    transform: translateZ(-1px) scale(2);
    background-color: blue;
}

.parallax_layer--deep {
    transform: translateZ(-2px) scale(3);
    background-color: green;
}

.static_content {
  height: 300px;
  background-color: black;
}

Back Layer

Base Layer

Deep Layer

Body:
I have been trying to solve the same problem. What worked for me was the following:

body, html {
  overflow: hidden;
}

* {
  margin:0;
  padding:0;
}

You can see this in Keith Clark's demo3 here. It works for me on Chrome and Firefox for Mac, not sure yet about other environments.


问:
Reading lines from a file and splitting them into arrays
I am working on a Linux project in C. I am creating a number a processes and each one writes his information on a file in the following format

PID | NAME | TYPE | GENOME

and the process.txt file looks something like this:

567 | A | B | 20

568 | N | A | 2

569 | Z | B | 12

This information I provide while executing it's code. What i want to do is to let the parent process read the file at the end of the child execution and be able to split this values into arrays in this way:

```<code>    pids[] = {567, 568, 569}
    names[] = {A, N, Z}
    type[] = {B, A, B}
    genome[] = {20, 2, 12}
</code>```

I have been looking for a way to do such thing but haven't found anything specific yet. A runnable code would be appreciated.

答:
I won't be helping you with your entire code, but here's a tip.

Read each line and then use sscanfto read the values into your arrays.

Here's a small code:

```<code>char name;
char type;
int pid;
int genome;

sscanf(line, "%d %c %c %d", &pid, &name, &type, &genome);
</code>```

Body:
I am working on a Linux project in C. I am creating a number a processes and each one writes his information on a file in the following format

PID | NAME | TYPE | GENOME

and the process.txt file looks something like this:

567 | A | B | 20

568 | N | A | 2

569 | Z | B | 12

This information I provide while executing it's code. What i want to do is to let the parent process read the file at the end of the child execution and be able to split this values into arrays in this way:

    pids[] = {567, 568, 569}
    names[] = {A, N, Z}
    type[] = {B, A, B}
    genome[] = {20, 2, 12}

I have been looking for a way to do such thing but haven't found anything specific yet. A runnable code would be appreciated.

Body:
I won't be helping you with your entire code, but here's a tip.

Read each line and then use sscanfto read the values into your arrays.

Here's a small code:

char name;
char type;
int pid;
int genome;

sscanf(line, "%d %c %c %d", &pid, &name, &type, &genome);


问:
How to represent status of light sources in OpenGL
So I want to have multiple light sources in my scene. The basic idea is to simply have an array of a (uniform) struct that has all the properties of light you care about such as positions, color, direction, cutoff and w/e you want. My problem is how to represent which lights are on/off? I will list out all the ways I can think of. Pl

Have a uniform int per light structure to indicate if it's on/off.

Have the number of light struct match multiples of 2, 3, or 4 such that I can use that many bool vectors to indicate their status. For example, 16 lights = 4x4 bvec4.

Instead of using many flags and branch, always go through every single light but with the off ones set to (0,0,0,0) for color

I'm leaning towards the last options as it won't have branching ... but I already read that modern graphics card are more okay with branching now.

答:
None of your ideas is really good because all of them require the shader to evaluate which lightsources are active and which aren't. You should also differentiate between scene information (which lights are present in the scene) and data necessary for rendering (which lights are on and illuminate the scene). Scene information shouldn't be stored in a shader since it is unnecessary and will only slow down the shader.

A better way for handling multiple light sources in a scene and render with only the active ones could be as follows:

In every frame:

Evaluate on CPU side which lights are on. Pass only the lights which are on to the shader uniforms together with the total count of the active lights. In pseudocode:

Shader:

```<code>uniform lightsources active_lightsources[MAX_LIGHTS];
uniform int light_count;
</code>```

CPU:

```<code>i = 0
foreach (light in lightsources)
{
    if (light.state == ON)
    {
         set_uniform("active_lightsources[i]", light);
         i++
    }
}
set_uniform("light_count", i);
</code>```

When illuminating a fragment do the following in the shader

Shader:

```<code>for (int i = 0; i < light_count; i++)
{
    //Calculate illumination from active_lightsources[i]
}
</code>```

The major advantage of this approach is that you store less lights inside the shader and that the loop inside the shader only loops over lightsources that are relevant for the current frame. The evaluation which lights are relevant is done once per frame on the CPU instead of once per vertex/fragment in the shader.

Body:
None of your ideas is really good because all of them require the shader to evaluate which lightsources are active and which aren't. You should also differentiate between scene information (which lights are present in the scene) and data necessary for rendering (which lights are on and illuminate the scene). Scene information shouldn't be stored in a shader since it is unnecessary and will only slow down the shader.

A better way for handling multiple light sources in a scene and render with only the active ones could be as follows:

In every frame:

Evaluate on CPU side which lights are on. Pass only the lights which are on to the shader uniforms together with the total count of the active lights. In pseudocode:

Shader:

uniform lightsources active_lightsources[MAX_LIGHTS];
uniform int light_count;

CPU:

i = 0
foreach (light in lightsources)
{
    if (light.state == ON)
    {
         set_uniform("active_lightsources[i]", light);
         i++
    }
}
set_uniform("light_count", i);

When illuminating a fragment do the following in the shader

Shader:

for (int i = 0; i < light_count; i++)
{
    //Calculate illumination from active_lightsources[i]
}

The major advantage of this approach is that you store less lights inside the shader and that the loop inside the shader only loops over lightsources that are relevant for the current frame. The evaluation which lights are relevant is done once per frame on the CPU instead of once per vertex/fragment in the shader.


问:
mysql fulltext returning odd values
I am trying to create a search tool that takes a text field that can contain some or all of a title, one or more author names in any order, and terms in the abstract and tries to find the most likely publication that the user is looking for.  But the rankings being returned are off.

Even if the text entered is word for word the beginning of the title, if I order by the MATCH results the ideal result is no where near the top of the results.

Any thoughts on a better solution for creating an accurate ranking of results?

SQL

```<code>SELECT `title`, (MATCH (`title`) AGAINST ("Data Trends #55")) AS `rank_title`
FROM `tblPublications`
HAVING (`rank_title`) > 1
  ORDER BY `rank_title`  DESC
</code>```

data

```<code>title   rank_title
Data Trends #140: The Role of Data Collection and Evaluation in Supporting Systems Change.  3.2141819000244
Data Trends #70: From Incarceration to Community.   2.7096807956696
Data Trends #12: Under Court Order. 2.7096807956696
Data Trends #78: Inclusion in Schools.  2.7096807956696
Data Trends #43: Paraprofessionals in Educational Settings. 2.6802139282227
Data Trends #35: Respite Care and Outcome.  2.6802139282227
Data Trends #08: Developments in Systems of Care.   2.6802139282227
Data Trends #07: Development of an Outcome Evaluation.  2.6802139282227
Data Trends #03: Families as Researchers and Evaluators.    2.6802139282227
Data Trends #02: Caregiver Enrichment and Stress.   2.6802139282227
Data Trends #97: The Relationships Between Poverty and Psychopathology. 2.6802139282227
Data Trends #111: Stigma and Mental Illness.    2.6802139282227
Data Trends #115: Building on Caregiver Strengths.  2.6802139282227
Data Trends #142: Defining the Wraparound Process.  2.6802139282227
Data Trends #71: Family Interventions in Serious Mental Illness.    2.6513810157776
Data Trends #63: Implementing IDEA '97 Disciplinary Provisions. 2.6513810157776
Data Trends #57: Using the Parents as Partners Principle with SED Children. 2.6513810157776
Data Trends #49: Cultural Competence: Caregiver Perspectives.   2.6513810157776
Data Trends #47: Service Use & Intensive Family Preservation.   2.6513810157776
Data Trends #44: Mood Disorders: Treatment Patterns in an HMO.  2.6513810157776
Data Trends #38: Adolescent Drug Treatment and Outcome. 2.6513810157776
Data Trends #34: Family-Centered Early Intervention.    2.6513810157776
Data Trends #31: Juvenile Justice and Mental Health.    2.6513810157776
Data Trends #25: Children's Mental Health in the Media. 2.6513810157776
Data Trends #18: Attribution in Children's Mental Health.   2.6513810157776
Data Trends #15:  Mechanisms of Change in Multisystemic Therapy.    2.6513810157776
Data Trends #10: Toxic Threats to Child Development.    2.6513810157776
Data Trends #73: Having a Brother with Emotional and/or Behavioral Challenges.  2.6513810157776
Data Trends #74: Research and Advocacy for Policy Change.   2.6513810157776
Data Trends #79: Family Perspectives on Having a Child with a Disability.   2.6513810157776
Data Trends #81: Explaining the Gap Between Mental Health Need and Service Use. 2.6513810157776
Data Trends #91: The Implications of Incarceration for Families and Children.   2.6513810157776
Data Trends #84: Working Relationships across Diverse Communities.  2.6513810157776
Data Trends #86: Community Interventions and Effective Prevention.  2.6513810157776
Data Trends #95: Maternal Employment when Children Have Disabilities.   2.6513810157776
Data Trends #99: Clinicians and How They Use and View Outcome Measurement.  2.6513810157776
Data Trends #108: Practice and Process in Wraparound Teamwork.  2.6513810157776
Data Trends #122: Outcomes for Youth Following Psychiatric Emergencies. 2.6513810157776
Data Trends #133: Evaluating treatment for homeless adolescents 2.6513810157776
Data Trends #156: Assessing the Sustainability of Systems of Care.  2.6513810157776
Data Trends #159: Out-of-Home Placements Within Systems of Care 2.6513810157776
Data Trends #64: Impact of Poverty on Family Quality of Life.   2.6231617927551
Data Trends #54: Mental Health Referral in Juvenile Justice.    2.6231617927551
Data Trends #53: Clinical Profiles of Youth in a System of Care.    2.6231617927551
Data Trends #45: Mood Disorders: Accuracy of Screening Instruments. 2.6231617927551
Data Trends #39: Violence: Emotional & Behavioral Impact & Prevention.  2.6231617927551
Data Trends #37: Racial Differences in Service Placement Patterns.  2.6231617927551
Data Trends #28: Suicidal Ideation, Depression, and Help-Seeking Among Adolescents. 2.6231617927551
Data Trends #26: Foster Care: Importance of Training and Support.   2.6231617927551
Data Trends #24: Needs Assessment and Service Coordination in an Inner City Neighborhood.   2.6231617927551
Data Trends #19: Custody Relinquishment: Impact of Research on Policy.  2.6231617927551
Data Trends #17: Offering Technical Assistance to Native Families.  2.6231617927551
Data Trends #13: Child Abuse and Neglect in Indian Country. 2.6231617927551
Data Trends #05: Consumer Satisfaction with Mental Health Services. 2.6231617927551
Data Trends #76: Community-Based Interventions for Affective Disorders. 2.6231617927551
Data Trends #77: Adolescent Help-Seeking Behavior: Role of the Internet.    2.6231617927551
Data Trends #80: Impact of Support on Adolescent Mental Health. 2.6231617927551
Data Trends #85: Culture-Centered Practice in Services for Children.    2.6231617927551
Data Trends #90: Exposure to Violence, Stress, Protective Factors, and Well-being.  2.6231617927551
Data Trends #92: Depictions of Mental Illness in Children's Media.  2.6231617927551
Data Trends #105: Collective socialization and child conduct problems.  2.6231617927551
Data Trends #116: Domestic Violence and Children's Mental Health.   2.6231617927551
Data Trends #121: Quality and Individualization in Wraparound Team Planning.    2.6231617927551
Data Trends #124: The Stigmatization of Mental Illness in Children and Families.    2.6231617927551
Data Trends #125: Neighborhood Residence and the Problems of School-Age Children.   2.6231617927551
Data Trends #149: What Constitutes Youth Involvement in Systems of Care?    2.6231617927551
Data Trends #151: Are Brothers and Sisters a Good Source of Support?    2.6231617927551
Data Trends #150: Understanding ADHD: Examining Racial Differences. 2.6231617927551
Data Trends #152: Family Participation in Action: Are Families Actually Involved?   2.6231617927551
Data Trends #158: Children's Perspectives of Their Mental Health Services.  2.6231617927551
Data Trends #160: Peer Stigmatization of Childhood Depression and ADHD  2.6231617927551
Data Trends #68: Prevalence of Psychiatric Disorders in Youth in Juvenile Detention.    2.5955367088318
Data Trends #59: Factors Associated with Response Inconsistency in Structured Diagnostic Interviews.    2.5955367088318
Data Trends #55: Mental Health Screening Instruments for use in Juvenile Justice.   2.5955367088318
</code>```

答:
The default minimum length for words is four as described here.  Information about changing that is described here.

Therefore search Data Trends #55 is probably equivalent to Data Trends.  The verify first row in the shown result set has the word Data a second time in the title, which probably explains why it ranks the highest.

Title: mysql fulltext returning odd values

Body:
I am trying to create a search tool that takes a text field that can contain some or all of a title, one or more author names in any order, and terms in the abstract and tries to find the most likely publication that the user is looking for.  But the rankings being returned are off.

Even if the text entered is word for word the beginning of the title, if I order by the MATCH results the ideal result is no where near the top of the results.

Any thoughts on a better solution for creating an accurate ranking of results?

SQL

SELECT `title`, (MATCH (`title`) AGAINST ("Data Trends #55")) AS `rank_title`
FROM `tblPublications`
HAVING (`rank_title`) > 1
  ORDER BY `rank_title`  DESC

data

title   rank_title
Data Trends #140: The Role of Data Collection and Evaluation in Supporting Systems Change.  3.2141819000244
Data Trends #70: From Incarceration to Community.   2.7096807956696
Data Trends #12: Under Court Order. 2.7096807956696
Data Trends #78: Inclusion in Schools.  2.7096807956696
Data Trends #43: Paraprofessionals in Educational Settings. 2.6802139282227
Data Trends #35: Respite Care and Outcome.  2.6802139282227
Data Trends #08: Developments in Systems of Care.   2.6802139282227
Data Trends #07: Development of an Outcome Evaluation.  2.6802139282227
Data Trends #03: Families as Researchers and Evaluators.    2.6802139282227
Data Trends #02: Caregiver Enrichment and Stress.   2.6802139282227
Data Trends #97: The Relationships Between Poverty and Psychopathology. 2.6802139282227
Data Trends #111: Stigma and Mental Illness.    2.6802139282227
Data Trends #115: Building on Caregiver Strengths.  2.6802139282227
Data Trends #142: Defining the Wraparound Process.  2.6802139282227
Data Trends #71: Family Interventions in Serious Mental Illness.    2.6513810157776
Data Trends #63: Implementing IDEA '97 Disciplinary Provisions. 2.6513810157776
Data Trends #57: Using the Parents as Partners Principle with SED Children. 2.6513810157776
Data Trends #49: Cultural Competence: Caregiver Perspectives.   2.6513810157776
Data Trends #47: Service Use & Intensive Family Preservation.   2.6513810157776
Data Trends #44: Mood Disorders: Treatment Patterns in an HMO.  2.6513810157776
Data Trends #38: Adolescent Drug Treatment and Outcome. 2.6513810157776
Data Trends #34: Family-Centered Early Intervention.    2.6513810157776
Data Trends #31: Juvenile Justice and Mental Health.    2.6513810157776
Data Trends #25: Children's Mental Health in the Media. 2.6513810157776
Data Trends #18: Attribution in Children's Mental Health.   2.6513810157776
Data Trends #15:  Mechanisms of Change in Multisystemic Therapy.    2.6513810157776
Data Trends #10: Toxic Threats to Child Development.    2.6513810157776
Data Trends #73: Having a Brother with Emotional and/or Behavioral Challenges.  2.6513810157776
Data Trends #74: Research and Advocacy for Policy Change.   2.6513810157776
Data Trends #79: Family Perspectives on Having a Child with a Disability.   2.6513810157776
Data Trends #81: Explaining the Gap Between Mental Health Need and Service Use. 2.6513810157776
Data Trends #91: The Implications of Incarceration for Families and Children.   2.6513810157776
Data Trends #84: Working Relationships across Diverse Communities.  2.6513810157776
Data Trends #86: Community Interventions and Effective Prevention.  2.6513810157776
Data Trends #95: Maternal Employment when Children Have Disabilities.   2.6513810157776
Data Trends #99: Clinicians and How They Use and View Outcome Measurement.  2.6513810157776
Data Trends #108: Practice and Process in Wraparound Teamwork.  2.6513810157776
Data Trends #122: Outcomes for Youth Following Psychiatric Emergencies. 2.6513810157776
Data Trends #133: Evaluating treatment for homeless adolescents 2.6513810157776
Data Trends #156: Assessing the Sustainability of Systems of Care.  2.6513810157776
Data Trends #159: Out-of-Home Placements Within Systems of Care 2.6513810157776
Data Trends #64: Impact of Poverty on Family Quality of Life.   2.6231617927551
Data Trends #54: Mental Health Referral in Juvenile Justice.    2.6231617927551
Data Trends #53: Clinical Profiles of Youth in a System of Care.    2.6231617927551
Data Trends #45: Mood Disorders: Accuracy of Screening Instruments. 2.6231617927551
Data Trends #39: Violence: Emotional & Behavioral Impact & Prevention.  2.6231617927551
Data Trends #37: Racial Differences in Service Placement Patterns.  2.6231617927551
Data Trends #28: Suicidal Ideation, Depression, and Help-Seeking Among Adolescents. 2.6231617927551
Data Trends #26: Foster Care: Importance of Training and Support.   2.6231617927551
Data Trends #24: Needs Assessment and Service Coordination in an Inner City Neighborhood.   2.6231617927551
Data Trends #19: Custody Relinquishment: Impact of Research on Policy.  2.6231617927551
Data Trends #17: Offering Technical Assistance to Native Families.  2.6231617927551
Data Trends #13: Child Abuse and Neglect in Indian Country. 2.6231617927551
Data Trends #05: Consumer Satisfaction with Mental Health Services. 2.6231617927551
Data Trends #76: Community-Based Interventions for Affective Disorders. 2.6231617927551
Data Trends #77: Adolescent Help-Seeking Behavior: Role of the Internet.    2.6231617927551
Data Trends #80: Impact of Support on Adolescent Mental Health. 2.6231617927551
Data Trends #85: Culture-Centered Practice in Services for Children.    2.6231617927551
Data Trends #90: Exposure to Violence, Stress, Protective Factors, and Well-being.  2.6231617927551
Data Trends #92: Depictions of Mental Illness in Children's Media.  2.6231617927551
Data Trends #105: Collective socialization and child conduct problems.  2.6231617927551
Data Trends #116: Domestic Violence and Children's Mental Health.   2.6231617927551
Data Trends #121: Quality and Individualization in Wraparound Team Planning.    2.6231617927551
Data Trends #124: The Stigmatization of Mental Illness in Children and Families.    2.6231617927551
Data Trends #125: Neighborhood Residence and the Problems of School-Age Children.   2.6231617927551
Data Trends #149: What Constitutes Youth Involvement in Systems of Care?    2.6231617927551
Data Trends #151: Are Brothers and Sisters a Good Source of Support?    2.6231617927551
Data Trends #150: Understanding ADHD: Examining Racial Differences. 2.6231617927551
Data Trends #152: Family Participation in Action: Are Families Actually Involved?   2.6231617927551
Data Trends #158: Children's Perspectives of Their Mental Health Services.  2.6231617927551
Data Trends #160: Peer Stigmatization of Childhood Depression and ADHD  2.6231617927551
Data Trends #68: Prevalence of Psychiatric Disorders in Youth in Juvenile Detention.    2.5955367088318
Data Trends #59: Factors Associated with Response Inconsistency in Structured Diagnostic Interviews.    2.5955367088318
Data Trends #55: Mental Health Screening Instruments for use in Juvenile Justice.   2.5955367088318


问:
Apex - Interactive Report - Hide Column in CSV Download?
I've got an interactive report in Apex with some columns.
The user has the option to download the report as CSV file with the standard functionality.

Is there a way to hide a column in the export but display it on the screen.

(Background: one column is a custom link  that should not be exported into the CSV)

Thank you !
Paul

答:
This one did not work for me:

NVL(:REQUEST,'EMPTY') NOT IN('CSV','XLS','PDF','XML','RTF','HTMLD')

So another workaround could be the following:

instr(nvl(:REQUEST,'~'),'XLS') = 0 and instr(nvl(:REQUEST,'~'),'PDF') = 0 and instr(nvl(:REQUEST,'~'),'HTMLD') = 0

Same logic applies for csv, rtf, etc.


问:
HTML table horizontal overflow past div in IE8
I'm building an HTML table that could be at most 5 columns wide and any number long; it rests inside a div.  It looks great in FF/Chrome/Safari, but messes up in IE8:

http://img42.imageshack.us/img42/7209/artistlist.png (I'm a new user so I can't post images directly...)

Here's the code:

```<code>     <h2 class="blockhead">14 artists found</h2>

    <div class="blockbody">
      <div class="blockrow">
        <font size="+0">
        <div style="max-width: 99.9%;">
        <center><table style="max-width: 99.9%;"><tr>
<td><center><a href="djdb2.php?id=994"><img src="djdb/artist/0/994.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John '00' Fleming</a></center></td>
<td><center><a href="djdb2.php?id=657"><img src="djdb/artist/0/657.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Acquaviva</a></center></td>
<td><center><a href="djdb2.php?id=1120"><img src="djdb/artist/1/1120.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Askew</a></center></td>
<td><center><a href="djdb2.php?id=474"><img src="djdb/artist/0/474.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Dahlbäck</a></center></td>
<td><center><a href="djdb2.php?id=1164"><img src="djdb/artist/1/1164.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Dalagelis</a></center></td>
</tr><tr>
<td><br><center><a href="djdb2.php?id=250"><img src="djdb/artist/0/250.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Daly</a></center></td>
<td><br><center><a href="djdb2.php?id=935"><img src="djdb/artist/0/935.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Debo</a></center></td>
<td><br><center><a href="djdb2.php?id=2"><img src="djdb/artist/0/2.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Digweed</a></center></td>
<td><br><center><a href="djdb2.php?id=1132"><img src="djdb/artist/1/1132.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Peel</a></center></td>
<td><br><center><a href="djdb2.php?id=338"><img src="djdb/artist/0/338.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Selway</a></center></td>
</tr><tr>
<td><br><center><a href="djdb2.php?id=980"><img src="djdb/artist/0/980.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Talabot</a></center></td>
<td><br><center><a href="djdb2.php?id=335"><img src="djdb/artist/0/335.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>John Tejada</a></center></td>

<td><br><center><a href="djdb2.php?id=863"><img src="djdb/artist/0/863.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>Koen Groeneveld</a></center></td>
<td><br><center><a href="djdb2.php?id=1009"><img src="djdb/artist/1/1009.jpg" style="max-width: 140px; max-height: 140px; border: 2px #414141 solid;" hspace=10><br>Mike Shannon</a></center></td>
</tr></table></center></div>
        </font>
      </div>
    </div>
</code>```

I know it's not pretty, but I'm building this on top of vBulletin so before I edit their code I want to make sure I know exactly what CSS styles I need to edit. I have tried many, many suggestions from Google, and even this site, but nothing has seemed to help IE make the table fit within the div.  Does anybody know how I can do this?  I'm open to trying anything if you're willing to explain something to me!

答:
If I recall correctly(1), IE8 only supports the max-width CSS if you are running in Standards Mode in HTML.

Do you have a DocType specified?

Is it an HTML one? XHTML isn't fully supported in IE8

(1) - Just verified, in Quirks Mode (what you get if no DocType is specified), max-width is ignored in IE8.

Body:
I'm building an HTML table that could be at most 5 columns wide and any number long; it rests inside a div.  It looks great in FF/Chrome/Safari, but messes up in IE8:

http://img42.imageshack.us/img42/7209/artistlist.png (I'm a new user so I can't post images directly...)

Here's the code:

14 artists found

John '00' Fleming

John Acquaviva

John Askew

John Dahlbäck

John Dalagelis

John Daly

John Debo

John Digweed

John Peel

John Selway

John Talabot

John Tejada

Koen Groeneveld

Mike Shannon

I know it's not pretty, but I'm building this on top of vBulletin so before I edit their code I want to make sure I know exactly what CSS styles I need to edit. I have tried many, many suggestions from Google, and even this site, but nothing has seemed to help IE make the table fit within the div.  Does anybody know how I can do this?  I'm open to trying anything if you're willing to explain something to me!


问:
Cloud Functions: Firestore Promise chain
I have Firestore database. Colletions simple:

"tasks/{taskId}": {

  "ownerUid": "task owner Firebase Uid",

  "whoDidUids": ["user_1_FirebaseUid","user_2_FirebaseUid"]

  }

"users/{userUid}": {"fcm_token": "firestore cloud messaging token"}

Want just to write simple Cloud Function which will be triggered on:

```<code>exports.taskDoneNotification = functions.firestore
    .document('tasks/{taskId}')
    .onUpdate((event) => {

       //when another user did task it means
       //userUid will be added to task.whoDidUids array
       //I want to get task owner fcmToken and send him
       // simple notification like "your task done by someone!"
    });
</code>```

I'am new to js syntax, writing on Kotlin for Android.

Please provide me some examples how to do this?

答:
I was trying to do something similar.

Unfortunately the "auth" object where you would get the UserId from is no yet implemented in Firestore Database Triggers. :(

See here:

Question 46912161

Body:
I have Firestore database. Colletions simple:

"tasks/{taskId}": {

  "ownerUid": "task owner Firebase Uid",

  "whoDidUids": ["user_1_FirebaseUid","user_2_FirebaseUid"]

  }

"users/{userUid}": {"fcm_token": "firestore cloud messaging token"}

Want just to write simple Cloud Function which will be triggered on:

exports.taskDoneNotification = functions.firestore
    .document('tasks/{taskId}')
    .onUpdate((event) => {

       //when another user did task it means
       //userUid will be added to task.whoDidUids array
       //I want to get task owner fcmToken and send him
       // simple notification like "your task done by someone!"
    });

I'am new to js syntax, writing on Kotlin for Android.

Please provide me some examples how to do this?


答:
Give a row number for each row partitioned and ordered by the columns [object_id], [status_val]. Then from the result set select the rows which having maximum row number 1.

Query

```<code>;with cte as(
    select [rn] = row_number() over(
        partition by [object_id], [status_val]
        order by [object_id], [status_val]
    ), *
    from [your_table_name]
)
select min([id]) as [id], [object_id], [status_val]
from cte
group by [object_id], [status_val]
having max([rn]) = 1;
</code>```

Find a demo here

Title: Select Except the duplicate Records from the table in SQL Server

Body:
I have a SQL Server table that has duplicate entries in one of the columns  e.g.:

  +----+-----------+------------+
  | id | object_id | status_val |
  +----+-----------+------------+
  |  1 |         1 |          0 |
  |  2 |         1 |          0 |
  |  3 |         1 |          0 |
  |  4 |         2 |          0 |
  |  5 |         3 |          0 |
  |  6 |         4 |          0 |
  |  7 |         4 |          0 |
  +----+-----------+------------+

I need the output to be like this:

  +----+-----------+------------+
  | id | object_id | status_val |
  +----+-----------+------------+
  |  4 |         2 |          0 |
  |  5 |         3 |          0 |
  +----+-----------+------------+

How to resolve this?

Body:
Give a row number for each row partitioned and ordered by the columns [object_id], [status_val]. Then from the result set select the rows which having maximum row number 1.

Query

;with cte as(
    select [rn] = row_number() over(
        partition by [object_id], [status_val]
        order by [object_id], [status_val]
    ), *
    from [your_table_name]
)
select min([id]) as [id], [object_id], [status_val]
from cte
group by [object_id], [status_val]
having max([rn]) = 1;

Find a demo here


问:
Python: How can I draw a bar graph in python using matplotlib?

My goal is to create a bar graph with my .csv data to see the relationship between work year (x) and wage (y) grouped by gender (separate bars).

First off, I want to group the variable'workyear' into three groups:
(1) more than 10 years, (2) just 10 years and (3) less than 10 years
Then I would like to create the bar graph with gender (1=female, 0=male)

Part of my data looks like this:

```<code>...    workyear gender wage
513         12    0  15.00
514         16    0  12.67
515         14    1   7.38
516         16    0  15.56
517         12    1   7.45
518         14    1   6.25
519         16    1   6.25
520         17    0   9.37
....
</code>```

To do this, I tried to replace the variable's value into three groups and I used matplotlib.

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

#load data
df=pd.DataFrame.from_csv('data.csv', index_col=None)
print(df)
df.sort_Values("workyear", ascending=True, inplace=True)

#parameters
bar_width = 0.2

#replacing Education year -> Education level grouped by given criteria.
#But I got an error.
df.loc[df.workyear<10, 'workyear'] = 'G1'
df.loc[df.workyear==10, 'workyear'] = 'G2'
df.loc[df.workyear>10, 'workyear']='G3'

#plotting
plt.bar(x, df.education[df.gender==1], bar_width, yerr=df.wage,color='y', label='female')
plt.bar(x+bar_width, df.education[df.gender==0], bar_width, yerr=df.wage, color='c', label='male')
</code>```

I want to see the bar graph like this (please consider '+' as a bar):

```<code>y=wage|                 + +
      | +        +      + +
      | +      + +      + +
      | + +    + +      + +
      |_______________________ x=work year (3-group)
        >10     10       10<
</code>```

But this is what I actually got... (yes. all errors)

```<code>Traceback (most recent call last):
File "data.py", line 21, in <module>
df.loc[df.workyear>10, 'workyear']='G3'
in wrapper
res = na_op(values, other)
in na_op
result = _comp_method_OBJECT_ARRAY(op, x, y)
in _comp_method_OBJECT_ARRAY
result = lib.scalar_compare(x, y, op)
File "pandas\_libs\lib.pyx", line 769, in pandas._libs.lib.scalar_compare (pandas\_libs\lib.c:13717)
TypeError: unorderable types: str() > int()
</code>```

Could you please advice me?

答:
A more direct way :

```<code>df['Age']=pd.cut(df.workyear,[1,13,14,100])
df['Gender']=df.gender.map({0:'male',1:'female'})
df.pivot_table(values='wage',index='Age',columns='Gender').plot.bar()
</code>```

for :

Body:
My goal is to create a bar graph with my .csv data to see the relationship between work year (x) and wage (y) grouped by gender (separate bars).

First off, I want to group the variable'workyear' into three groups:
(1) more than 10 years, (2) just 10 years and (3) less than 10 years
Then I would like to create the bar graph with gender (1=female, 0=male)

Part of my data looks like this:

...    workyear gender wage
513         12    0  15.00
514         16    0  12.67
515         14    1   7.38
516         16    0  15.56
517         12    1   7.45
518         14    1   6.25
519         16    1   6.25
520         17    0   9.37
....

To do this, I tried to replace the variable's value into three groups and I used matplotlib.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

#load data
df=pd.DataFrame.from_csv('data.csv', index_col=None)
print(df)
df.sort_Values("workyear", ascending=True, inplace=True)

#parameters
bar_width = 0.2

#replacing Education year -> Education level grouped by given criteria.
#But I got an error.
df.loc[df.workyear<10, 'workyear'] = 'G1'
df.loc[df.workyear==10, 'workyear'] = 'G2'
df.loc[df.workyear>10, 'workyear']='G3'

#plotting
plt.bar(x, df.education[df.gender==1], bar_width, yerr=df.wage,color='y', label='female')
plt.bar(x+bar_width, df.education[df.gender==0], bar_width, yerr=df.wage, color='c', label='male')

I want to see the bar graph like this (please consider '+' as a bar):

y=wage|                 + +
      | +        +      + +
      | +      + +      + +
      | + +    + +      + +
      |_______________________ x=work year (3-group)
        >10     10       10<

But this is what I actually got... (yes. all errors)

Traceback (most recent call last):
File "data.py", line 21, in <module>
df.loc[df.workyear>10, 'workyear']='G3'
in wrapper
res = na_op(values, other)
in na_op
result = _comp_method_OBJECT_ARRAY(op, x, y)
in _comp_method_OBJECT_ARRAY
result = lib.scalar_compare(x, y, op)
File "pandas\_libs\lib.pyx", line 769, in pandas._libs.lib.scalar_compare (pandas\_libs\lib.c:13717)
TypeError: unorderable types: str() > int()

Could you please advice me?

Body:
A more direct way :

df['Age']=pd.cut(df.workyear,[1,13,14,100])
df['Gender']=df.gender.map({0:'male',1:'female'})
df.pivot_table(values='wage',index='Age',columns='Gender').plot.bar()

for :


问:
amazon s3 InvalidRequest error in node.js
```<code>var s3 = require('s3');
var client = s3.createClient({
maxAsyncS3: 20,
s3RetryCount: 3,
s3RetryDelay: 1000,
multipartUploadThreshold: 20971520,
multipartUploadSize: 15728640,
s3Options: {
 accessKeyId: "ABC",
  secretAccessKey: "XYZ",
  region: " us-east-2",
  endpoint: 's3-us-east-2.amazonaws.com',
  ACL: ''
  }
 });
  var uploadParams = {
    localFile: '/home/onur/Desktop/cwiz.jpg',
    s3Params: {
        Bucket: 'cwizz',
        Key: '', // How can I found bucked key ?

    }
};

var uploader = client.uploadFile(uploadParams);

uploader.on('error', function(err) {
  return console.error('unable to upload:', err, err.stack);
});
uploader.on('end', function() {
  console.log("done uploading");
});
</code>```

How can I found bucked key ?

unable to upload: { InvalidRequest: The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.

答:
Bucket key is the path inside the bucket where you want your file to be uploaded. e.g. the following will upload your image to images/cwiz.jpg inside the cwizz bucket. Also, you don't need region, endpoint and ACL in the s3Options object.</p>

```<code>var s3 = require('s3');
var client = s3.createClient({
maxAsyncS3: 20,
s3RetryCount: 3,
s3RetryDelay: 1000,
multipartUploadThreshold: 20971520,
multipartUploadSize: 15728640,
s3Options: {
 accessKeyId: "ABC",
  secretAccessKey: "XYZ"
  }
 });
  var uploadParams = {
    localFile: '/home/onur/Desktop/cwiz.jpg',
    s3Params: {
        Bucket: 'cwizz',
        Key: 'images/cwiz.jpg',

    }
};

var uploader = client.uploadFile(uploadParams);

uploader.on('error', function(err) {
  return console.error('unable to upload:', err, err.stack);
});
uploader.on('end', function() {
  console.log("done uploading");
});
</code>```

Body:
var s3 = require('s3');
var client = s3.createClient({
maxAsyncS3: 20,
s3RetryCount: 3,
s3RetryDelay: 1000,
multipartUploadThreshold: 20971520,
multipartUploadSize: 15728640,
s3Options: {
 accessKeyId: "ABC",
  secretAccessKey: "XYZ",
  region: " us-east-2",
  endpoint: 's3-us-east-2.amazonaws.com',
  ACL: ''
  }
 });
  var uploadParams = {
    localFile: '/home/onur/Desktop/cwiz.jpg',
    s3Params: {
        Bucket: 'cwizz',
        Key: '', // How can I found bucked key ?

    }
};

var uploader = client.uploadFile(uploadParams);

uploader.on('error', function(err) {
  return console.error('unable to upload:', err, err.stack);
});
uploader.on('end', function() {
  console.log("done uploading");
});

How can I found bucked key ?

unable to upload: { InvalidRequest: The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.

Body:
Bucket key is the path inside the bucket where you want your file to be uploaded. e.g. the following will upload your image to images/cwiz.jpg inside the cwizz bucket. Also, you don't need region, endpoint and ACL in the s3Options object.

var s3 = require('s3');
var client = s3.createClient({
maxAsyncS3: 20,
s3RetryCount: 3,
s3RetryDelay: 1000,
multipartUploadThreshold: 20971520,
multipartUploadSize: 15728640,
s3Options: {
 accessKeyId: "ABC",
  secretAccessKey: "XYZ"
  }
 });
  var uploadParams = {
    localFile: '/home/onur/Desktop/cwiz.jpg',
    s3Params: {
        Bucket: 'cwizz',
        Key: 'images/cwiz.jpg',

    }
};

var uploader = client.uploadFile(uploadParams);

uploader.on('error', function(err) {
  return console.error('unable to upload:', err, err.stack);
});
uploader.on('end', function() {
  console.log("done uploading");
});


问:
Segfault when using *this
I'm getting a segfault when I try to access a member of a class from within a method of that same class, which does not make sense to me at all.

I have the Tree class:

```<code>class Tree
{

public:

Coord* root;

Tree(int x, int y)
{
    root = new Coord(x, y);
    populateTree();
}

void populateTree()
{
    queue<Coord*> nodes;
    nodes.push(root);

    while (nodes.size() > 0)
    {
        Coord* currnode = nodes.front();
        nodes.pop();

        if ( !(currnode->getValidMoves()) )
        {
            return;
        }

        else
        {
            for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
            {
                if (currnode->children[i] != NULL)
                {
                    nodes.push(currnode->children[i]);
                }
            }
        }
    }
}
</code>```

...and the Coord class...

```<code>class Coord : public Loc
{
    public:

    Coord(int xPos, int yPos);

    Coord* children[MAX_CHILDREN_PER_COORD];

    bool getValidMoves();

    bool operator==(Coord coord);
    bool operator==(Loc loc);

};

Coord::Coord(int xPos, int yPos) : Loc(xPos, yPos) {}

bool Coord::getValidMoves()
{
    //This line segfaults
    Coord test = *this;

    //Global boolean method. Checks found
    if (!foundTrue())
    {
        for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
        {
            //If the above segfaulting line is commented out, this is the first place that segfaults
            int newX = x + knightPositions[i].x;
            int newY = y + knightPositions[i].y;

            if ( !(newX > GRID_X || newX < 0 || newY > GRID_Y || newY < 0) )
            {
                //knightPositions is a Loc array of length MAX_CHILDREN_PER_COORD
                children[i] = new Coord(x + knightPositions[i].x, y + knightPositions[i].y);
                //Global 2d array of ints. Gets checked by foundTrue()
                found[x + knightPositions[i].x][y + knightPositions[i].y] = true;
            }
        }

        return true;
    }

    else
    {
        return false;
    }

    //Otherwise, just leave it as a blank array
}

bool Coord::operator==(Coord coord)
{
    return coord.x == x && coord.y == y;
}

bool Coord::operator==(Loc loc)
{
    return loc.x == x && loc.y == y;
}
</code>```

... and the Loc class, from which Coord inheirits...

```<code>class Loc
{
    public:
        int x, y;

        //Constructor
        Loc(int xPos, int yPos) : x(xPos), y(yPos) {}
};
</code>```

The segfault occurs in Coord::getValidMoves() as indicated by the comments. If step through the code to that point, then make a watch for *this or x or this->x, I get a "Cannot access memory at 0xbaadf00d"

Why is this happening? Where have I messed up? I just don't understand how trying to access *this in a method could possibly result in a segfault.

答:
A segfault when accessing data members is a common problem when a method is called on an invalid (or invalidated) pointer. While the language provides the abstraction of objects and methods, the underlying implementation still has functions and data, where methods are functions (code) that applies to an data (implicit *this).

Check that the pointers are valid (not null, not freed) before calling the method, as that is surely the problem:

```<code>struct test {
   int x;
   void foo( int y ) {
      x = y;       // [1]
   }
};
int main() {
   test *p = 0;
   //p->foo();     // segfault in x=y above: this == 0
   p = new test;
   p->foo();
   delete p;
   // p->foo();    // undefined behavior, can be a segfault or not
   p = reinterpret_cast<test*>( "This is a literal" );
   p->foo();       // undefined behavior, probably segfault
                   // writing to read-only memory (this depends on compiler/environment)
}
</code>```

In the code above, all errors will most be detected at the line marked as [1]

Title: Segfault when using *this

Body:
I'm getting a segfault when I try to access a member of a class from within a method of that same class, which does not make sense to me at all.

I have the Tree class:

class Tree
{

public:

Coord* root;

Tree(int x, int y)
{
    root = new Coord(x, y);
    populateTree();
}

void populateTree()
{
    queue<Coord*> nodes;
    nodes.push(root);

    while (nodes.size() > 0)
    {
        Coord* currnode = nodes.front();
        nodes.pop();

        if ( !(currnode->getValidMoves()) )
        {
            return;
        }

        else
        {
            for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
            {
                if (currnode->children[i] != NULL)
                {
                    nodes.push(currnode->children[i]);
                }
            }
        }
    }
}

...and the Coord class...

class Coord : public Loc
{
    public:

    Coord(int xPos, int yPos);

    Coord* children[MAX_CHILDREN_PER_COORD];

    bool getValidMoves();

    bool operator==(Coord coord);
    bool operator==(Loc loc);

};

Coord::Coord(int xPos, int yPos) : Loc(xPos, yPos) {}

bool Coord::getValidMoves()
{
    //This line segfaults
    Coord test = *this;

    //Global boolean method. Checks found
    if (!foundTrue())
    {
        for (int i = 0; i < MAX_CHILDREN_PER_COORD; i++)
        {
            //If the above segfaulting line is commented out, this is the first place that segfaults
            int newX = x + knightPositions[i].x;
            int newY = y + knightPositions[i].y;

            if ( !(newX > GRID_X || newX < 0 || newY > GRID_Y || newY < 0) )
            {
                //knightPositions is a Loc array of length MAX_CHILDREN_PER_COORD
                children[i] = new Coord(x + knightPositions[i].x, y + knightPositions[i].y);
                //Global 2d array of ints. Gets checked by foundTrue()
                found[x + knightPositions[i].x][y + knightPositions[i].y] = true;
            }
        }

        return true;
    }

    else
    {
        return false;
    }

    //Otherwise, just leave it as a blank array
}

bool Coord::operator==(Coord coord)
{
    return coord.x == x && coord.y == y;
}

bool Coord::operator==(Loc loc)
{
    return loc.x == x && loc.y == y;
}

... and the Loc class, from which Coord inheirits...

class Loc
{
    public:
        int x, y;

        //Constructor
        Loc(int xPos, int yPos) : x(xPos), y(yPos) {}
};

The segfault occurs in Coord::getValidMoves() as indicated by the comments. If step through the code to that point, then make a watch for *this or x or this->x, I get a "Cannot access memory at 0xbaadf00d"

Why is this happening? Where have I messed up? I just don't understand how trying to access *this in a method could possibly result in a segfault.

Body:
A segfault when accessing data members is a common problem when a method is called on an invalid (or invalidated) pointer. While the language provides the abstraction of objects and methods, the underlying implementation still has functions and data, where methods are functions (code) that applies to an data (implicit *this).

Check that the pointers are valid (not null, not freed) before calling the method, as that is surely the problem:

struct test {
   int x;
   void foo( int y ) {
      x = y;       // [1]
   }
};
int main() {
   test *p = 0;
   //p->foo();     // segfault in x=y above: this == 0
   p = new test;
   p->foo();
   delete p;
   // p->foo();    // undefined behavior, can be a segfault or not
   p = reinterpret_cast<test*>( "This is a literal" );
   p->foo();       // undefined behavior, probably segfault
                   // writing to read-only memory (this depends on compiler/environment)
}

In the code above, all errors will most be detected at the line marked as [1]


问:
Add logger to an existing chat app
I'd like to log usernames/dates of people coming in and out a let's chat server instance. I was told bunyan and winston are good candidates but I have no clue on how to implement them on this specific project.

I'm not sure on which file I have to instantiate them and how to catch username when login and when logout. My bet is in controllers/account.js but it's clearly out of my knowledge.

As a result I'd really like to obtain a rotated file with :

```<code>20171104-15:10:14 - LOGIN username with IP x
[...]
20171104-19:23:15 - LOGOUT username
</code>```

答:
Got something I'm happy with :

added console.log('LOGIN', d); and console.log('LOGOUT', d); in
room.js

use pm2 and pm2-logrotate module to start my app, store logs
end rotate them

Thanks to @VtoCorleone for his indications

Since there are certainly better ways to achieve this, I welcome other ideas.

Title: Add logger to an existing chat app

Body:
I'd like to log usernames/dates of people coming in and out a let's chat server instance. I was told bunyan and winston are good candidates but I have no clue on how to implement them on this specific project.

I'm not sure on which file I have to instantiate them and how to catch username when login and when logout. My bet is in controllers/account.js but it's clearly out of my knowledge.

As a result I'd really like to obtain a rotated file with :

20171104-15:10:14 - LOGIN username with IP x
[...]
20171104-19:23:15 - LOGOUT username


问:
How to get the latitude and longitude between two points in sequence?
Explanation: I have some requirement two get the all the latitude and longitude between origin and destination.I have got it. The problem is it's not coming into the sequence.

For Example: If I have set origin is "Delhi" and my destination is "Mumbai". So I need a lat & long between these two points. First must be near to the Delhi because of my origin is "Delhi". Google Direction API provided me the arbitrary way. Sometimes it takes near to the "Mumbai" and then it is going back to return the near of the Delhi.

Please help me solve this problem or if you know how to get all the lat & long in sequence please put your comment.

答:
You can use the direction api

```<code>// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

// Sensor enabled
String sensor = "sensor=false";

// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;

// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
</code>```

download the lat long list from the above url and use that list to get specific lat long.

Body:
You can use the direction api

// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;

// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;

// Sensor enabled
String sensor = "sensor=false";

// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;

// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;

download the lat long list from the above url and use that list to get specific lat long.


问:
Java custom class loader issue
I'm sending a Class object from client to server side. Every time the server needs to load the Class object sent by the client instead of reusing it by parent delegation model (when it was loaded during the 1st iteration).

I'm trying to use a custom class loader on the server side whose loadClass(String) simply calls findClass() instead of checking with parent hierarchy.
To achieve this, I'm doing following:

Generate byte[] by reading the .class file on the client side as following:

```<code>Class cl = com.example.XYZ.class;
String path = cl.getName().replace('.', '/') + ".class";
InputStream is = cl.getClassLoader().getResourceAsStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data = -1;
while((data=is.read())!=-1)
  bos.write(data);
byte[] classBinaryData = bos.toByteArray();
</code>```

I'm sending classBinaryData to the server side.

On the server side, every time I retrieve the byte[], verify if it's the same as on client side by matching MD5 checksum, then I create a new instance of my custom class loader and pass the byte array so it could be used in calling defineClass from within findClass.

However, I'm getting either of the errors (depending on the way I create byte[] out of .class)

Incompatible magic value ..... in class file <Unknown>

OR

com/example/XYZ (wrong name: com/example/XYZ) coming from defineClass

I need help in figuring out the mistake in my approach/code.

答:
Your byte[] generation code looks fine.

When I used the byte array generated form your code to load the class with following class loader code, it was able to load the class successfully.

```<code>class CustomClassLoader extends ClassLoader {

    public Class loadTheClass(String name, byte[] bytes) {

        return defineClass(name, bytes, 0, bytes.length);
    }
}
</code>```

Using this classloader like this

```<code>CustomClassLoader ccl = new CustomClassLoader();
        Class cz = ccl.loadTheClass("com.example.XYZ", classBinaryData);
        Object o = cz.newInstance();
</code>```

I think you must use '.' instead of '/' in the name when you are loading the class at server side.

And ensure that the byte array data is not changed in your other code.

Title: Java custom class loader issue

Body:
I'm sending a Class object from client to server side. Every time the server needs to load the Class object sent by the client instead of reusing it by parent delegation model (when it was loaded during the 1st iteration).

I'm trying to use a custom class loader on the server side whose loadClass(String) simply calls findClass() instead of checking with parent hierarchy.
To achieve this, I'm doing following:

Generate byte[] by reading the .class file on the client side as following:

Class cl = com.example.XYZ.class;
String path = cl.getName().replace('.', '/') + ".class";
InputStream is = cl.getClassLoader().getResourceAsStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data = -1;
while((data=is.read())!=-1)
  bos.write(data);
byte[] classBinaryData = bos.toByteArray();

I'm sending classBinaryData to the server side.

On the server side, every time I retrieve the byte[], verify if it's the same as on client side by matching MD5 checksum, then I create a new instance of my custom class loader and pass the byte array so it could be used in calling defineClass from within findClass.

However, I'm getting either of the errors (depending on the way I create byte[] out of .class)

Incompatible magic value ..... in class file <Unknown>

OR

com/example/XYZ (wrong name: com/example/XYZ) coming from defineClass

I need help in figuring out the mistake in my approach/code.

Body:
Your byte[] generation code looks fine.

When I used the byte array generated form your code to load the class with following class loader code, it was able to load the class successfully.

class CustomClassLoader extends ClassLoader {

    public Class loadTheClass(String name, byte[] bytes) {

        return defineClass(name, bytes, 0, bytes.length);
    }
}

Using this classloader like this

CustomClassLoader ccl = new CustomClassLoader();
        Class cz = ccl.loadTheClass("com.example.XYZ", classBinaryData);
        Object o = cz.newInstance();

I think you must use '.' instead of '/' in the name when you are loading the class at server side.

And ensure that the byte array data is not changed in your other code.