问:
junit: no tests found
I have inherited a Java project and am new to Java development. I feel a good way for me to get comfortable with the code is to write some tests around it. I'm writing my code using IntelliJ.

My existing project has a folder structure like this:

```<code>/myProject
  /src
    /main
      /java
        /com.lexcorp
          /core
            /email
              /providers
                emailProvider.java
</code>```

I created a new project that will hold tests for this project. I would like this project to hold both unit and integration tests. Currently, my new project has a structure like this:

```<code>/myProjectTests
  /src
    /main
      /java
        /com.lexcorp.core.email.providers
          emailProviderTest.java
</code>```

The emailProviderTest.java file looks like the following:

```<code>package com.lexcorp.core.email.providers;

import junit.framework.TestCase;
import org.junit.Test;

public class EmailProviderTest extends TestCase {

    private final String username = "[testAccount]";

    private final String password = "[testPassword]";

    @Test
    public void thisAlwaysPasses() {
        assertTrue(true);
    }
}
</code>```

This project has a Run/Debug configuration with the following properties:

Test kind: All in package

Search for tests: In whole project

When I run this configuration, I get an error that says:

```<code>junit.framework.AssertionFailedError: No tests found in com.lexcorp.core.email.providers.EmailProviderTest
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
    at org.junit.runners.Suite.runChild(Suite.java:127)
    at org.junit.runners.Suite.runChild(Suite.java:26)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:202)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
</code>```

I do not understand why I'm getting an error that boils down to: "No tests found". While my project structures differ, the folder structures on the OS match (which is another thing that confuses me). Why am I getting this error and how do I fix it?

答:
Test method name public void testName() {}

Where  name() in source naming name methods.

Title: junit: no tests found

Body:
I have inherited a Java project and am new to Java development. I feel a good way for me to get comfortable with the code is to write some tests around it. I'm writing my code using IntelliJ.

My existing project has a folder structure like this:

/myProject
  /src
    /main
      /java
        /com.lexcorp
          /core
            /email
              /providers
                emailProvider.java

I created a new project that will hold tests for this project. I would like this project to hold both unit and integration tests. Currently, my new project has a structure like this:

/myProjectTests
  /src
    /main
      /java
        /com.lexcorp.core.email.providers
          emailProviderTest.java

The emailProviderTest.java file looks like the following:

package com.lexcorp.core.email.providers;

import junit.framework.TestCase;
import org.junit.Test;

public class EmailProviderTest extends TestCase {

    private final String username = "[testAccount]";

    private final String password = "[testPassword]";

    @Test
    public void thisAlwaysPasses() {
        assertTrue(true);
    }
}

This project has a Run/Debug configuration with the following properties:

Test kind: All in package

Search for tests: In whole project

When I run this configuration, I get an error that says:

junit.framework.AssertionFailedError: No tests found in com.lexcorp.core.email.providers.EmailProviderTest
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
    at org.junit.runners.Suite.runChild(Suite.java:127)
    at org.junit.runners.Suite.runChild(Suite.java:26)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:202)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

I do not understand why I'm getting an error that boils down to: "No tests found". While my project structures differ, the folder structures on the OS match (which is another thing that confuses me). Why am I getting this error and how do I fix it?


来源: stackexchange

问:
I am learning selenium framework while creating framework with testing and pagefactory I am getting followed error
My files and error which iI am getting are as follows:

url_title.properties

```<code>username=rakeshm@techved.com
password=123456
chrome_driver_path=D://rakesh//software//selenium browser//chrome 2.28//chromedriver.exe
</code>```

BrowserFactory class file

```<code>package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class BrowserFactory
{
    static Properties browserfactory_properties_obj;
    static WebDriver driver;
public static WebDriver browser_factory_getter(String browser, String url) throws IOException
{
    File browserfactory_file_obj = new  File(".\\src\\property_folder\\url_title.properties");
    FileInputStream browserfactory_fileinput_obj = new FileInputStream(browserfactory_file_obj);
    browserfactory_properties_obj = new Properties();
    browserfactory_properties_obj.load(browserfactory_fileinput_obj);
    if(browser.equalsIgnoreCase("firefox"))
    {
        ProfilesIni profile = new ProfilesIni();
        FirefoxProfile fire_profile = profile.getProfile("selenium_browser");
        driver = new  FirefoxDriver(fire_profile);
    }
    else if(browser.equalsIgnoreCase("chrome"))
    {
        System.setProperty("webdriver.chrome.driver",browserfactory_properties_obj.getProperty("chrome_driver_path"));
        driver = new ChromeDriver();
    }
    driver.manage().window().maximize();
    driver.get(url);
    return driver;
}
}
</code>```

home_login_elements class file

```<code>package utilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class home_login_elements
{
    WebDriver driver;
    @FindBy(how=How.CLASS_NAME, using="login")
    WebElement login_link_ele;

    @FindBy(how=How.ID, using="email")
    WebElement username_ele;

    @FindBy(how=How.ID, using="passwd")
    WebElement password_ele;

    @FindBy(how=How.ID, using="SubmitLogin")
    WebElement login_submint_ele;

public WebElement login_link()
{
    login_link_ele.click();
    return login_link_ele;
}

public void login_fun(String username, String password)
{
    username_ele.sendKeys(username);
    password_ele.sendKeys(password);
    login_link_ele.submit();
}
}
</code>```

login_class class file

```<code>package utilities;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;

public class login_class
{
WebDriver driver;
Properties login_class_url_title;
public login_class() throws Exception
{
    File login_class_url_title_file = new File(".\\src\\property_folder\\url_title.properties");
    FileInputStream login_class_url_title_fis = new FileInputStream(login_class_url_title_file);
    login_class_url_title = new Properties();
    login_class_url_title.load(login_class_url_title_fis);
    home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
    home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
}
}
</code>```

Add_to_wishlist testng file(executable file)

```<code>package wishlist;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import utilities.BrowserFactory;
import utilities.home_login_elements;
import utilities.login_class;

public class Add_to_wishlist extends home_login_elements
{
WebDriver driver;
@Test
public void first_testcase() throws Exception
{
    driver = BrowserFactory.browser_factory_getter("chrome", "http://automationpractice.com/index.php");
    login_class obj =new login_class();
    driver.findElement(By.xpath("//ul[@class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']/li[3]")).click();
}
}
</code>```

After executing Add_to_wishlist testng file i am getting following error

```<code>Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 6905
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: first_testcase
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.sendKeys(Unknown Source)
at utilities.home_login_elements.login_fun(home_login_elements.java:36)
at utilities.login_class.<init>(login_class.java:20)
at wishlist.Add_to_wishlist.first_testcase(Add_to_wishlist.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
</code>```

答:
The problem is, you are not in login/sign in page. you have missed to click on sign in link in home page. please call the method login_link before calling the login_fun in the class login_class as given below.</p>

```<code>driver=BrowserFactory.driver;
home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
home_login_elements_login_class_obj.login_link();//This is missing in your code
home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My files and error which iI am getting are as follows:

url_title.properties

username=rakeshm@techved.com
password=123456
chrome_driver_path=D://rakesh//software//selenium browser//chrome 2.28//chromedriver.exe

BrowserFactory class file

package utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class BrowserFactory
{
    static Properties browserfactory_properties_obj;
    static WebDriver driver;
public static WebDriver browser_factory_getter(String browser, String url) throws IOException
{
    File browserfactory_file_obj = new  File(".\\src\\property_folder\\url_title.properties");
    FileInputStream browserfactory_fileinput_obj = new FileInputStream(browserfactory_file_obj);
    browserfactory_properties_obj = new Properties();
    browserfactory_properties_obj.load(browserfactory_fileinput_obj);
    if(browser.equalsIgnoreCase("firefox"))
    {
        ProfilesIni profile = new ProfilesIni();
        FirefoxProfile fire_profile = profile.getProfile("selenium_browser");
        driver = new  FirefoxDriver(fire_profile);
    }
    else if(browser.equalsIgnoreCase("chrome"))
    {
        System.setProperty("webdriver.chrome.driver",browserfactory_properties_obj.getProperty("chrome_driver_path"));
        driver = new ChromeDriver();
    }
    driver.manage().window().maximize();
    driver.get(url);
    return driver;
}
}

home_login_elements class file

package utilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class home_login_elements
{
    WebDriver driver;
    @FindBy(how=How.CLASS_NAME, using="login")
    WebElement login_link_ele;

    @FindBy(how=How.ID, using="email")
    WebElement username_ele;

    @FindBy(how=How.ID, using="passwd")
    WebElement password_ele;

    @FindBy(how=How.ID, using="SubmitLogin")
    WebElement login_submint_ele;

public WebElement login_link()
{
    login_link_ele.click();
    return login_link_ele;
}

public void login_fun(String username, String password)
{
    username_ele.sendKeys(username);
    password_ele.sendKeys(password);
    login_link_ele.submit();
}
}

login_class class file

package utilities;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;

public class login_class
{
WebDriver driver;
Properties login_class_url_title;
public login_class() throws Exception
{
    File login_class_url_title_file = new File(".\\src\\property_folder\\url_title.properties");
    FileInputStream login_class_url_title_fis = new FileInputStream(login_class_url_title_file);
    login_class_url_title = new Properties();
    login_class_url_title.load(login_class_url_title_fis);
    home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
    home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));
}
}

Add_to_wishlist testng file(executable file)

package wishlist;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import utilities.BrowserFactory;
import utilities.home_login_elements;
import utilities.login_class;

public class Add_to_wishlist extends home_login_elements
{
WebDriver driver;
@Test
public void first_testcase() throws Exception
{
    driver = BrowserFactory.browser_factory_getter("chrome", "http://automationpractice.com/index.php");
    login_class obj =new login_class();
    driver.findElement(By.xpath("//ul[@class='sf-menu clearfix menu-content sf-js-enabled sf-arrows']/li[3]")).click();
}
}

After executing Add_to_wishlist testng file i am getting following error

Starting ChromeDriver 2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41) on port 6905
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: first_testcase
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy5.sendKeys(Unknown Source)
at utilities.home_login_elements.login_fun(home_login_elements.java:36)
at utilities.login_class.<init>(login_class.java:20)
at wishlist.Add_to_wishlist.first_testcase(Add_to_wishlist.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:639)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
at org.testng.TestRunner.privateRun(TestRunner.java:774)
at org.testng.TestRunner.run(TestRunner.java:624)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
at org.testng.SuiteRunner.run(SuiteRunner.java:261)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.run(TestNG.java:1048)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)

Body:
The problem is, you are not in login/sign in page. you have missed to click on sign in link in home page. please call the method login_link before calling the login_fun in the class login_class as given below.

driver=BrowserFactory.driver;
home_login_elements home_login_elements_login_class_obj = PageFactory.initElements(driver, home_login_elements.class);
home_login_elements_login_class_obj.login_link();//This is missing in your code
home_login_elements_login_class_obj.login_fun(login_class_url_title.getProperty("username"), login_class_url_title.getProperty("password"));


问:
SpreadsheetApp.getActiveSpreadsheet() returning null
I need a quick function to loop through the rows of one of my sheets so I constructed this:

```<code>function getTotalsOf(name, type) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
  var data = sheet.getDataRange().getValues();
  var total = 0.00;
  for (var i = 0; i < data.length; i++) {
    if (data[i][0]== "") break;
    if (data[i][2] == type) {
      var temp = (Number(data[i][4]) + Number(data[i][5]) + Number(data[i][6])) * data [i][3];
        total = Number(total) + total;
        }
  }
  return total;
}
</code>```

SpreadsheetApp.getActiveSpreadsheet() seems to return null when I try to execute the function. It also returns null when I try to get the spreadsheet by id. Am I missing something?

EDIT:
I retried using my spreadsheet id (https://docs.google.com/spreadsheets/d/STRINGFROMHERE/edit#gid=1235572150) with the same results.

```<code>function getTotalsOf(name, type) {
  var sheet = SpreadsheetApp.openById("**STRINGFROMURL**").getSheetByName(name);
  var data = sheet.getDataRange().getValues();
  var total = 0.00;
  for (var i = 0; i < data.length; i++) {
    if (data[i][0]== "") break;
    if (data[i][2] == type) {
      var temp = (Number(data[i][4]) + Number(data[i][5]) + Number(data[i][6])) * data [i][3];
        total = Number(total) + temp;
        }
  }
  return total;
}
</code>```

答:
I think you just missed a few concepts with regard to looping through spreadsheets. Hope this demo will help and get you what you want. Always remember that rows and cols in spreadsheets starts with 1,1 not 0,0.

```<code>  function loopThroughCells() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var data = sheet.getDataRange().getValues();
      Logger.log(data[0].length);

  for(var i=0; i< data.length; i++){
    for(var j=0; j<data[i].length; j++){
      if(data[i][j] == "HELIOS"){
           if (data[i][j]== "") break;
           Logger.log("HELIOS data found in range "+ (i+1) + " "+(j+1));
      }
    }
  }
</code>```

Log

```<code>[17-07-07 21:45:17:157 HKT] HELIOS data found in range 3 3
</code>```

Body:
I need a quick function to loop through the rows of one of my sheets so I constructed this:

function getTotalsOf(name, type) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
  var data = sheet.getDataRange().getValues();
  var total = 0.00;
  for (var i = 0; i < data.length; i++) {
    if (data[i][0]== "") break;
    if (data[i][2] == type) {
      var temp = (Number(data[i][4]) + Number(data[i][5]) + Number(data[i][6])) * data [i][3];
        total = Number(total) + total;
        }
  }
  return total;
}

SpreadsheetApp.getActiveSpreadsheet() seems to return null when I try to execute the function. It also returns null when I try to get the spreadsheet by id. Am I missing something?

EDIT:
I retried using my spreadsheet id (https://docs.google.com/spreadsheets/d/STRINGFROMHERE/edit#gid=1235572150) with the same results.

function getTotalsOf(name, type) {
  var sheet = SpreadsheetApp.openById("**STRINGFROMURL**").getSheetByName(name);
  var data = sheet.getDataRange().getValues();
  var total = 0.00;
  for (var i = 0; i < data.length; i++) {
    if (data[i][0]== "") break;
    if (data[i][2] == type) {
      var temp = (Number(data[i][4]) + Number(data[i][5]) + Number(data[i][6])) * data [i][3];
        total = Number(total) + temp;
        }
  }
  return total;
}

Body:
I think you just missed a few concepts with regard to looping through spreadsheets. Hope this demo will help and get you what you want. Always remember that rows and cols in spreadsheets starts with 1,1 not 0,0.

  function loopThroughCells() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var data = sheet.getDataRange().getValues();
      Logger.log(data[0].length);

  for(var i=0; i< data.length; i++){
    for(var j=0; j<data[i].length; j++){
      if(data[i][j] == "HELIOS"){
           if (data[i][j]== "") break;
           Logger.log("HELIOS data found in range "+ (i+1) + " "+(j+1));
      }
    }
  }

Log

[17-07-07 21:45:17:157 HKT] HELIOS data found in range 3 3


问:
How do I know when HTML has fully rendered
case 1:

I load a very large HTML page that includes a lot of complex layout and fonts.
The page will take some unknown time to render.

case 2:

I use jquery .html() function to make significant changes to my DOM.
The modified DOM will take some unknown time to render.

In both cases, I want to be able to cover the whole screen with a spinner until the page has completely finished rendering.

In searching for answers to this question, I have found similar questions asked but the answers are not relevant. To be clear:

I don't want to know when the DOM is ready.

I don't want to know when the HTTP data has been fetched.

I want to know when everything in the DOM has been completely drawn to the screen.

Setting some worst-case timeout is not an acceptable solution.

I need a solution for WebKit based browsers.

答:
For case one I think you can use:</p>

```<code><BODY onLoad="alert('Page Fully Loaded')">
</code>```

ContentLicense: CC BY-SA 2.5

Body:
For case one I think you can use:

<BODY onLoad="alert('Page Fully Loaded')">


问:
Get values from hashmap in Eclipse
I am adding to a project done in Eclipse that displays data pulled from various databases to a webpage.  I am trying to figure out how to use a hashmap.  I have a variable/column called "description" that will show a description based on the value of the column just before it.  The descriptions are in my hashmap.  I just don't know how to pull the "description" value.

Here is part of the DtoBuilder -

```<code>private HashMap<String,String> itemDescrMap = null;

public VersionsDto build(Versions oneVersion){

    VersionsDto result = null;
    if(itemDescrMap==null){
        itemDescrMap = loadItemDescrMap();
    }

    // Create instance of versions object and build it.
    if(oneVersion != null){
        result = new VersionsDto();
        result.setStore(oneVersion.getStore());
        result.setUpdatePackage(oneVersion.getUpdatePackage());
        result.setDescription(oneVersion.getDescription());
</code>```

and here is part of the hashmap -

```<code>private static HashMap<String,String> loadItemDescrMap(){
    HashMap<String,String> map = new HashMap<String,String>();

    map.put("CDSA", "Color Match");
    map.put("CDSB", "New Formula Book");
    map.put("CDSC", "Base Assignments");
    map.put("CDSD", "Product Formulation");
    map.put("CDSE", "Old TAC");
    map.put("CDSF", "Colorant Systems");
    map.put("CDSG", "Miscellaneous");
    map.put("CDSH", "AFCD");
</code>```

Initially, I was just grabbing the same data for "description" as I was for "updatePackage", just to test that it would populate all the fields and display it to the webpage.  So now I need to know how to set the "description" value based on the hash map, where the first values (CDSD, CDSE, etc) are all the possible values in the "updatePackage" column and the second value is the corresponding "description" that I need.

答:
Look at the javadoc https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

I think itemDescrMap.get(oneVersion.getUpdatePackage()) should do the job

Title: Get values from hashmap in Eclipse

Body:
I am adding to a project done in Eclipse that displays data pulled from various databases to a webpage.  I am trying to figure out how to use a hashmap.  I have a variable/column called "description" that will show a description based on the value of the column just before it.  The descriptions are in my hashmap.  I just don't know how to pull the "description" value.

Here is part of the DtoBuilder -

private HashMap<String,String> itemDescrMap = null;

public VersionsDto build(Versions oneVersion){

    VersionsDto result = null;
    if(itemDescrMap==null){
        itemDescrMap = loadItemDescrMap();
    }

    // Create instance of versions object and build it.
    if(oneVersion != null){
        result = new VersionsDto();
        result.setStore(oneVersion.getStore());
        result.setUpdatePackage(oneVersion.getUpdatePackage());
        result.setDescription(oneVersion.getDescription());

and here is part of the hashmap -

private static HashMap<String,String> loadItemDescrMap(){
    HashMap<String,String> map = new HashMap<String,String>();

    map.put("CDSA", "Color Match");
    map.put("CDSB", "New Formula Book");
    map.put("CDSC", "Base Assignments");
    map.put("CDSD", "Product Formulation");
    map.put("CDSE", "Old TAC");
    map.put("CDSF", "Colorant Systems");
    map.put("CDSG", "Miscellaneous");
    map.put("CDSH", "AFCD");

Initially, I was just grabbing the same data for "description" as I was for "updatePackage", just to test that it would populate all the fields and display it to the webpage.  So now I need to know how to set the "description" value based on the hash map, where the first values (CDSD, CDSE, etc) are all the possible values in the "updatePackage" column and the second value is the corresponding "description" that I need.


问:
How to include git branch name as variable for ant build.xml
I'm trying to use the git branch name as a variable so that I can include it in the SonarQube project key.
Does anyone know of how I can do this? I'm on Windows if that helps.
I've tried doing things like this:

```<code>property name="sonar.projectKey" value="${GIT_BRANCH}"
</code>```

or setting environment variables in Jenkins and calling those but I can't seem to get it.

Thanks in advance :)

Additional info:

I'm building the project from Jenkins and the part where it fails is when I call ant sonar.
Using ${GIT_BRANCH} results in this:

```<code>"C:\Program Files (x86)\Jenkins\jobs\PR Projects\jobs\PR_JmxMonitor_RPM\workspace\projects\JmxMonitor\build.xml:132: Validation of project reactor failed: o "${GIT_BRANCH}" is not a valid project or module key. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit."
</code>```

答:
When I went to localhost:8080/job/TEST/10/injectedEnvVars (for example) I couldn't see GIT_BRANCH as an environment variable. I realized I hadn't selected 'inject environment variables to the build process' in the build environment.

Then in build.xml, I made value="$(branch)" and added -Dbranch=%GIT_BRANCH% to my command line.

Thanks all for the help :)

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use the git branch name as a variable so that I can include it in the SonarQube project key.
Does anyone know of how I can do this? I'm on Windows if that helps.
I've tried doing things like this:

property name="sonar.projectKey" value="${GIT_BRANCH}"

or setting environment variables in Jenkins and calling those but I can't seem to get it.

Thanks in advance :)

Additional info:

I'm building the project from Jenkins and the part where it fails is when I call ant sonar.
Using ${GIT_BRANCH} results in this:

"C:\Program Files (x86)\Jenkins\jobs\PR Projects\jobs\PR_JmxMonitor_RPM\workspace\projects\JmxMonitor\build.xml:132: Validation of project reactor failed: o "${GIT_BRANCH}" is not a valid project or module key. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit."


问:
How to send keywords with html form to express app.js route to create a SELECT query with them?
I'm pretty new to node and express, but i have set up an app with html files that i route between with app.sendFile(). I also have a working heroku postgreSQL database which i successfully can fetch from and write to.

I want the form below to send som query keywords which i send to a predefined query but with some variating parameters.

My question is how do I route and what methods I should use in app.js for this to work.

```<code><form id="query-form" method="post" action="/dbquery">
    <label>Value1</label>
    <input class="form-control sendout-input" type="text" name="value1" placeholder="Filter sendout by Source"/>
    <br>
    <label>Value2</label>
    <input class="form-control sendout-input" type="text" name="value2" placeholder="Filter sendout by Country"/>
    <br>
    <label>Value3</label>
    <input class="form-control sendout-input" type="text" name="value3" placeholder="Filter sendout by Lanuage"/>
    <br>
    <button class="btn btn-default" type="submit">Submit</button>
</form>
</code>```

How do i get the value of these input fields in my app.js?
My guess is something similar to this:

```<code>app.post('/dbquery', function(request, response) {
     var first = request.myInputvalues.value1
     var second = request.myInputvalues.value2
     var third = request.myInputvalues.value3

     // Send query with these variables to the
});
</code>```

答:
If you post to that route you should be able to access the body of the request you sent in request.body inside of the handler.

See this related question: How do you extract POST data in Node.js?

Body:
I'm pretty new to node and express, but i have set up an app with html files that i route between with app.sendFile(). I also have a working heroku postgreSQL database which i successfully can fetch from and write to.

I want the form below to send som query keywords which i send to a predefined query but with some variating parameters.

My question is how do I route and what methods I should use in app.js for this to work.

<form id="query-form" method="post" action="/dbquery">
    Value1
    <input class="form-control sendout-input" type="text" name="value1" placeholder="Filter sendout by Source"/>

    Value2
    <input class="form-control sendout-input" type="text" name="value2" placeholder="Filter sendout by Country"/>

    Value3
    <input class="form-control sendout-input" type="text" name="value3" placeholder="Filter sendout by Lanuage"/>

    <button class="btn btn-default" type="submit">Submit</button>
</form>

How do i get the value of these input fields in my app.js?
My guess is something similar to this:

app.post('/dbquery', function(request, response) {
     var first = request.myInputvalues.value1
     var second = request.myInputvalues.value2
     var third = request.myInputvalues.value3

     // Send query with these variables to the
});


问:
How to make a foreach of an object in javascript?
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

```<code>var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);
</code>```

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

```<code>for(var index in CurrentSelec) {
    console.log(index.qSelected);
}
</code>```

I have tried with jQuery:

```<code>$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});
</code>```

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

答:
It seems like you mixed up Arrays and Objects.
Looking at the picture you provided I think you have an Array which contains Objects.

```<code>//Naming indicates mutliple selections
app1.selectionState().selections;
</code>```

Looping over an array is easy, accessing a object value too:

```<code>// CurrentSelec = [{qSelected : '1'},{qSelected : '2'}];
CurrentSelec.forEach ( selection => console.log(selection.qSelected) );
</code>```

Body:
I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

var CurrentSelec = app1.selectionState().selections;
console.log(CurrentSelec);`
console.log(typeof CurrentSelec);

This is what I get on my browser console :

I'm trying to show the qSelected value in a Foreach :

I have tried with Javascript :

for(var index in CurrentSelec) {
    console.log(index.qSelected);
}

I have tried with jQuery:

$.each(CurrentSelec, function(i, index) {
  console.log(index.qSelected)
});

But my browser console do not show the log of my foreach.

Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

Regards.

Body:
It seems like you mixed up Arrays and Objects.
Looking at the picture you provided I think you have an Array which contains Objects.

//Naming indicates mutliple selections
app1.selectionState().selections;

Looping over an array is easy, accessing a object value too:

// CurrentSelec = [{qSelected : '1'},{qSelected : '2'}];
CurrentSelec.forEach ( selection => console.log(selection.qSelected) );


问:
Automatically passing own type to function call
I'd like to pass a value when calling a function but want to omit to actually add it as a parameter.

To be more precise I'd like to write a logger that also prints which class called the logging function but don't want to always pass a "this" as a parameter.

Example code:

```<code>class static Logger{
    public static void LogMsg(string msg, object objectCalling){
         Print(objectCalling.GetType().Name + ": " + msg);
    }
    private void Print(string msg){
        // print it
    }
}

class SomeClass{
    private void WriteTestLog() {
        Logger.LogMsg("Testing!");
    }
}
</code>```

This should then create an output like: "SomeClass: Testing!"

I am not sure how to tackle this maybe I am just missing sth.

答:
You could create an extension method to do that as well as the answers above :</p>

```<code>void Main()
{
SomeClass x = new SomeClass();
x.WriteTestLog();

int i = 1;
i.LogMsg("abc");
}

public static class Logger
{
  public static void LogMsg(this object objectCalling, string msg)
  {
      Print(objectCalling.GetType().Name + ": " + msg);
  }
  private static void Print(string msg)
  {
    Console.WriteLine(msg);  // print it
  }
}

public class SomeClass
{
  public void WriteTestLog()
  {
    this.LogMsg("Testing!");
  }
}
</code>```

Body:
I'd like to pass a value when calling a function but want to omit to actually add it as a parameter.

To be more precise I'd like to write a logger that also prints which class called the logging function but don't want to always pass a "this" as a parameter.

Example code:

class static Logger{
    public static void LogMsg(string msg, object objectCalling){
         Print(objectCalling.GetType().Name + ": " + msg);
    }
    private void Print(string msg){
        // print it
    }
}

class SomeClass{
    private void WriteTestLog() {
        Logger.LogMsg("Testing!");
    }
}

This should then create an output like: "SomeClass: Testing!"

I am not sure how to tackle this maybe I am just missing sth.

Body:
You could create an extension method to do that as well as the answers above :

void Main()
{
SomeClass x = new SomeClass();
x.WriteTestLog();

int i = 1;
i.LogMsg("abc");
}

public static class Logger
{
  public static void LogMsg(this object objectCalling, string msg)
  {
      Print(objectCalling.GetType().Name + ": " + msg);
  }
  private static void Print(string msg)
  {
    Console.WriteLine(msg);  // print it
  }
}

public class SomeClass
{
  public void WriteTestLog()
  {
    this.LogMsg("Testing!");
  }
}


问:
How can I check if the user char input is contained in 2 Strings?
The question seems confusing. The program does this: It asks the user for input in char form and then stores it in 2 variables. There are 2 Strings which I've already created. One contains the letters a-g and the other for the letters h-o. These are basically 2 routes which a user can go, but the user can't put for example "a" as start and "h" as destination since they are from a different String. He/She has to have the start and destination in the same String. If the start is and destination aren't in the same String, there will be an error.

This method I have looks as follows:

```<code>private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while((a == 0 && b == 0) || (c == 0 && d ==0)){

        System.out.println("Put in a starting point please: ");
        start = in.next().charAt(0);

        while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
              start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
              start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
              start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
              start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
              start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
              start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
              start != 'o' && start != 'O') {
            System.out.println("Put in a correct starting point please: ");
            start = in.next().charAt(0);
        }

        System.out.println("Put in a destination point please: ");
        ziel = in.next().charAt(0);

        while(ziel != 'a' && ziel != 'A' && ziel != 'b' && ziel != 'B' &&
              ziel != 'c' && ziel != 'C' && ziel != 'd' && ziel != 'D' &&
              ziel != 'e' && ziel != 'E' && ziel != 'f' && ziel != 'F' &&
              ziel != 'g' && ziel != 'G' && ziel != 'h' && ziel != 'H' &&
              ziel != 'i' && ziel != 'I' && ziel != 'j' && ziel != 'J' &&
              ziel != 'k' && ziel != 'K' && ziel != 'l' && ziel != 'L' &&
              ziel != 'm' && ziel != 'M' && ziel != 'n' && ziel != 'N' &&
              ziel != 'o' && ziel != 'O') {
            System.out.println("Put in a correct destination point please: ");
            ziel = in.next().charAt(0);
        }

        a = bereich1.indexOf(start);
        b = bereich2.indexOf(ziel);

        c = bereich2.indexOf(start);
        d = bereich1.indexOf(ziel);

    }
}
</code>```

I tried using .indexOf() today, which I have here with this while loop:

```<code>while((a == 0 && b == 0) || (c == 0 && d ==0)){
</code>```

And these variables:

```<code>a = bereich1.indexOf(start);
b = bereich2.indexOf(ziel);

c = bereich2.indexOf(start);
d = bereich1.indexOf(ziel);
</code>```

I just can't get it to work and it's been working my mind for a couple of days. Any help or pinpointing in the right direction is greatly appreciated. Please let me know if there is anything insufficient given by me or if you need any more information.

Thank you.

答:
To find out whether a single character is in a range, you don't need a regular expression, nor a long list of checks. You can compare chars as if they were numbers (which they are, really).

```<code> char start = input.charAt(0);
 if( start >= 'a' && start <= 'o' ) {
     // do stuff
 }
</code>```

To make it case-insensitive, convert it to a case before comparing:

```<code> char start = Character.toLowerCase(input.charAt(0));
</code>```

I suggest spending a couple of hours reading through the Javadocs for general-purpose classes like String, Character, Math and so on, in the spirit of spotting methods that "might come in handy", and getting a general feel for the sort of methods that you can expect to find if you look.

Body:
The question seems confusing. The program does this: It asks the user for input in char form and then stores it in 2 variables. There are 2 Strings which I've already created. One contains the letters a-g and the other for the letters h-o. These are basically 2 routes which a user can go, but the user can't put for example "a" as start and "h" as destination since they are from a different String. He/She has to have the start and destination in the same String. If the start is and destination aren't in the same String, there will be an error.

This method I have looks as follows:

private void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    char start = ' ';
    char ziel = ' ';
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while((a == 0 && b == 0) || (c == 0 && d ==0)){

        System.out.println("Put in a starting point please: ");
        start = in.next().charAt(0);

        while(start != 'a' && start != 'A' && start != 'b' && start != 'B' &&
              start != 'c' && start != 'C' && start != 'd' && start != 'D' &&
              start != 'e' && start != 'E' && start != 'f' && start != 'F' &&
              start != 'g' && start != 'G' && start != 'h' && start != 'H' &&
              start != 'i' && start != 'I' && start != 'j' && start != 'J' &&
              start != 'k' && start != 'K' && start != 'l' && start != 'L' &&
              start != 'm' && start != 'M' && start != 'n' && start != 'N' &&
              start != 'o' && start != 'O') {
            System.out.println("Put in a correct starting point please: ");
            start = in.next().charAt(0);
        }

        System.out.println("Put in a destination point please: ");
        ziel = in.next().charAt(0);

        while(ziel != 'a' && ziel != 'A' && ziel != 'b' && ziel != 'B' &&
              ziel != 'c' && ziel != 'C' && ziel != 'd' && ziel != 'D' &&
              ziel != 'e' && ziel != 'E' && ziel != 'f' && ziel != 'F' &&
              ziel != 'g' && ziel != 'G' && ziel != 'h' && ziel != 'H' &&
              ziel != 'i' && ziel != 'I' && ziel != 'j' && ziel != 'J' &&
              ziel != 'k' && ziel != 'K' && ziel != 'l' && ziel != 'L' &&
              ziel != 'm' && ziel != 'M' && ziel != 'n' && ziel != 'N' &&
              ziel != 'o' && ziel != 'O') {
            System.out.println("Put in a correct destination point please: ");
            ziel = in.next().charAt(0);
        }

        a = bereich1.indexOf(start);
        b = bereich2.indexOf(ziel);

        c = bereich2.indexOf(start);
        d = bereich1.indexOf(ziel);

    }
}

I tried using .indexOf() today, which I have here with this while loop:

while((a == 0 && b == 0) || (c == 0 && d ==0)){

And these variables:

a = bereich1.indexOf(start);
b = bereich2.indexOf(ziel);

c = bereich2.indexOf(start);
d = bereich1.indexOf(ziel);

I just can't get it to work and it's been working my mind for a couple of days. Any help or pinpointing in the right direction is greatly appreciated. Please let me know if there is anything insufficient given by me or if you need any more information.

Thank you.

Body:
To find out whether a single character is in a range, you don't need a regular expression, nor a long list of checks. You can compare chars as if they were numbers (which they are, really).

 char start = input.charAt(0);
 if( start >= 'a' && start <= 'o' ) {
     // do stuff
 }

To make it case-insensitive, convert it to a case before comparing:

 char start = Character.toLowerCase(input.charAt(0));

I suggest spending a couple of hours reading through the Javadocs for general-purpose classes like String, Character, Math and so on, in the spirit of spotting methods that "might come in handy", and getting a general feel for the sort of methods that you can expect to find if you look.


问:
How to mock a module that is required in another module with Jasmine
```<code>const Client = require('./src/http/client');

module.exports.handler = () => {
    const client = new Client();
    const locationId = client.getLocationId(123);
};
</code>```

How can I test this module asserting that the client.getLocationId has been called with the 123 argument in Jasmine?

I know how to achieve that with Sinon, but I have no clue about Jasmine.

答:
Where with Sinon you would do:

```<code>Sinon.spy(client, 'getLocationId');

...

Sinon.assert.calledWith(client.getLocationId, 123);
</code>```

with Jasmine you do:

```<code>spyOn(client, 'getLocationId');

...

expect(client.getLocationId).toHaveBeenCalledWith(123);
</code>```

Update: So, what you need is to mock the Client module when it's required by the module you're testing. I suggest using Proxyquire for this:

```<code>const proxyquire = require('proxyquire');
const mockedClientInstance = {
  getLocationId: () => {}
};
const mockedClientConstructor = function() {
  return mockedClientInstance;
};

const moduleToTest = proxyquire('moduleToTest.js', {
  './src/http/client': mockedClientConstructor
});
</code>```

This will inject your mock as a dependency so that when the module you're testing requires ./src/http/client, it will get your mock instead of the real Client module. After this you just spy on the method in mockedClientInstance as normal:

```<code>spyOn(mockedClientInstance, 'getLocationId');
moduleToTest.handler();
expect(mockedClientInstance.getLocationId).toHaveBeenCalledWith(123);
</code>```

Body:
const Client = require('./src/http/client');

module.exports.handler = () => {
    const client = new Client();
    const locationId = client.getLocationId(123);
};

How can I test this module asserting that the client.getLocationId has been called with the 123 argument in Jasmine?

I know how to achieve that with Sinon, but I have no clue about Jasmine.

Body:
Where with Sinon you would do:

Sinon.spy(client, 'getLocationId');

...

Sinon.assert.calledWith(client.getLocationId, 123);

with Jasmine you do:

spyOn(client, 'getLocationId');

...

expect(client.getLocationId).toHaveBeenCalledWith(123);

Update: So, what you need is to mock the Client module when it's required by the module you're testing. I suggest using Proxyquire for this:

const proxyquire = require('proxyquire');
const mockedClientInstance = {
  getLocationId: () => {}
};
const mockedClientConstructor = function() {
  return mockedClientInstance;
};

const moduleToTest = proxyquire('moduleToTest.js', {
  './src/http/client': mockedClientConstructor
});

This will inject your mock as a dependency so that when the module you're testing requires ./src/http/client, it will get your mock instead of the real Client module. After this you just spy on the method in mockedClientInstance as normal:

spyOn(mockedClientInstance, 'getLocationId');
moduleToTest.handler();
expect(mockedClientInstance.getLocationId).toHaveBeenCalledWith(123);


问:
How to set some spaces before a link without moving the link position?
I need to higlight a div 5 pixels before its current position on mouse over. That is to say if the user passes the pointer over it the div would be highlighted 5 pixels before, but without changing its content position.

.container {
  width: 100%;
  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
  Click me!
</div></code>```

On mouse over it highlights but the "Click me!" message moves 5 pixels to the right. How can I achieve this?

答:
I've had a go at this as it looked fun.

Moving the element 5px left whilst preserving the contents with padding (and adding 5px to the width to offset the shift)

You should have something that looks like this:

```<code>.container:hover {
  position:relative;
  width:calc(100% + 5px);
  left:-5px;
  box-sizing:border-box;
  padding-left:5px;
}
</code>```

Code pen here

Body:
I need to higlight a div 5 pixels before its current position on mouse over. That is to say if the user passes the pointer over it the div would be highlighted 5 pixels before, but without changing its content position.

.container {
  width: 100%;
  &:hover {
    background-color: rgba(0, 0, 0, 0.1);
    position: relative;
    padding-left: 5px;
  }
}

  Click me!

On mouse over it highlights but the "Click me!" message moves 5 pixels to the right. How can I achieve this?

Body:
I've had a go at this as it looked fun.

Moving the element 5px left whilst preserving the contents with padding (and adding 5px to the width to offset the shift)

You should have something that looks like this:

.container:hover {
  position:relative;
  width:calc(100% + 5px);
  left:-5px;
  box-sizing:border-box;
  padding-left:5px;
}

Code pen here


问:
onchange() function not defined (inaccessible from index.html?)
i am assigning an 'onchange' attribute to a <select> tag in my html. I have done so successfully in my main.js file (which is bundled into bundle.js). My bundle.js is then referenced in the index.html.

Whenever the onchange event tries to use the function i have defined
 filterChanged(), it provides a reference error: "filterChanged is not defined
    at HTMLSelectElement.onchange"

i originally thought it may be due to the function not being a global variable, so i assigned to to a var and the issue persists.

see below the code -

main.js

```<code>var filterChanged = function() {
    console.log('filter changed');
}

window.onload = function() {
    let filter = document.getElementById('filter-list');
    filter.setAttribute('onchange', 'filterChanged()');
}
</code>```

index.html

```<code><!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>TestProj</title>
    <script type="text/javascript" charset="UTF-8" src="build/bundle.js"></script>
</head>
<body>
    <h3>Todos</h3>
    <p>Number of items to show</p>
    <select id="filter-list" name="filter">
            <option selected="true" value="list10">10</option>
            <option value="list20">20</option>
            <option value="list30">30</option>
    </select>
    <ul id="todo_list">
        <!-- Inject list here with JS (main.js getTodos()) -->
    </ul>
</body>
</html>
</code>```

答:
Please use:</p>

```<code>filter.addEventListener("change", filterChanged);
</code>```

Body:
i am assigning an 'onchange' attribute to a <select> tag in my html. I have done so successfully in my main.js file (which is bundled into bundle.js). My bundle.js is then referenced in the index.html.

Whenever the onchange event tries to use the function i have defined
 filterChanged(), it provides a reference error: "filterChanged is not defined
    at HTMLSelectElement.onchange"

i originally thought it may be due to the function not being a global variable, so i assigned to to a var and the issue persists.

see below the code -

main.js

var filterChanged = function() {
    console.log('filter changed');
}

window.onload = function() {
    let filter = document.getElementById('filter-list');
    filter.setAttribute('onchange', 'filterChanged()');
}

index.html

<!doctype html>

    <meta charset="UTF-8">
    <title>TestProj</title>

Todos

Number of items to show

    <select id="filter-list" name="filter">
            <option selected="true" value="list10">10</option>
            <option value="list20">20</option>
            <option value="list30">30</option>
    </select>

Body:
Please use:

filter.addEventListener("change", filterChanged);


问:
Incorrect output for UTF8 conversion using iconv
I am trying to convert string encoded in ISO-8859-1 to UTF-8 on Linux. I am using iconv function to do that in C++. This is the code that I have:

```<code>//Conversion from ISO-8859-1 to UTF-8
iconv_t cd = iconv_open("UTF-8","ISO-8859-1");

char *input = "€"; // the byte value is 128 in ISO-8859-1
char *inputbuf= input;
size_t inputSize=1;

char *output = (char*)malloc(inputSize*4); // maximum size of a character in UTF8 is 4
char *outputbuf = output;
size_t outputSize = inputSize*4;

//Conversion Function
iconv (cd, &inputbuf, &inputSize, &outputbuf, &outputSize);

//Display input bytes(ISO-8859-1)
cout << "input bytes(ISO-8859-1):"
for (int i=0; i<inputSize; i++)
{
    cout <<(int) *(input+i) << ", ";
}
cout<< std::endl;

//Display Converted bytes(UTF-8)
cout << "output bytes(UTF-8):"
for (int i=0; i<outputSize; i++) //displaying all the 4 bytes allocated
{
    cout <<(int) *(output+i) << ", ";
}
cout<< std::endl;
iconv(cd);
</code>```

This is the output I observe:

```<code>input bytes(ISO-8859-1): 128
output bytes(UTF-8): 194, 128, 0, 0
</code>```

As you can see, the output UTF-8 converted bytesis 194,128. However, the expected UTF-8 output is 226,130,172. I verified that there is no error thrown by any of the iconv functions.

Can anyone please help me figure out if I am missing anything here?

答: You can either use the utfcpp library: http://utfcpp.sourceforge.net/ or Boost.Locale for that purpose</p>

Body:
I am trying to convert string encoded in ISO-8859-1 to UTF-8 on Linux. I am using iconv function to do that in C++. This is the code that I have:

//Conversion from ISO-8859-1 to UTF-8
iconv_t cd = iconv_open("UTF-8","ISO-8859-1");

char *input = "€"; // the byte value is 128 in ISO-8859-1
char *inputbuf= input;
size_t inputSize=1;

char *output = (char*)malloc(inputSize*4); // maximum size of a character in UTF8 is 4
char *outputbuf = output;
size_t outputSize = inputSize*4;

//Conversion Function
iconv (cd, &inputbuf, &inputSize, &outputbuf, &outputSize);

//Display input bytes(ISO-8859-1)
cout << "input bytes(ISO-8859-1):"
for (int i=0; i<inputSize; i++)
{
    cout <<(int) *(input+i) << ", ";
}
cout<< std::endl;

//Display Converted bytes(UTF-8)
cout << "output bytes(UTF-8):"
for (int i=0; i<outputSize; i++) //displaying all the 4 bytes allocated
{
    cout <<(int) *(output+i) << ", ";
}
cout<< std::endl;
iconv(cd);

This is the output I observe:

input bytes(ISO-8859-1): 128
output bytes(UTF-8): 194, 128, 0, 0

As you can see, the output UTF-8 converted bytesis 194,128. However, the expected UTF-8 output is 226,130,172. I verified that there is no error thrown by any of the iconv functions.

Can anyone please help me figure out if I am missing anything here?


问:
I am trying to get the DateTimeFormatter for a date string in joda time
I need the format string for a date that is formatted like this: 2017-06-14T00:00:00Z.

Currently, I have:

```<code>DateTimeFormatter DT_SCHEDULE_FORMATTER_START_TIME = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
</code>```

If I parse a the string 2017-06-14T00:00:00Z with this, it gives me the right time in UTC.

But when I take a DateTime object and try to do:

```<code>String strNow = new DateTime().toString(DT_SCHEDULE_FORMATTER_START_TIME);
</code>```

I get something like 2017-06-14T00:00:00 -07:00

I've looked in the documentation and can't seem to find the right formatting string.

答:
That's because the DateTime() constructor uses your system's default timezone, and the Z pattern in the formatter prints the timezone offset.

Your system's default timezone offset is -07:00, that's why you get this output.

If you want exactly the output with Z in the end, you must convert the DateTime object to an org.joda.time.Instant:

```<code>String strNow = new DateTime("2017-06-14T00:00:00Z").toInstant().toString();
</code>```

strNow will be 2017-06-14T00:00:00.000Z.

If you want to get the current time in UTC (instead of parsing a String), you must tell explicity to DateTime constructor to use UTC, using new DateTime(DateTimeZone.UTC).

The code above also prints the milliseconds. If you don't want this, another alternative is to use a DateTimeFormatterBuilder:

```<code>DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd'T'HH:mm:ss")
    // append Z if offset is zero (UTC)
    .appendTimeZoneOffset("Z", true, 2, 2)
    // create formatter
    .toFormatter();
String strNow = new DateTime("2017-06-14T00:00:00Z").toInstant().toString(formatter);
</code>```

This will format the date accordinlgy (without the milliseconds):

2017-06-14T00:00:00Z

Body:
I need the format string for a date that is formatted like this: 2017-06-14T00:00:00Z.

Currently, I have:

DateTimeFormatter DT_SCHEDULE_FORMATTER_START_TIME = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");

If I parse a the string 2017-06-14T00:00:00Z with this, it gives me the right time in UTC.

But when I take a DateTime object and try to do:

String strNow = new DateTime().toString(DT_SCHEDULE_FORMATTER_START_TIME);

I get something like 2017-06-14T00:00:00 -07:00

I've looked in the documentation and can't seem to find the right formatting string.

Body:
That's because the DateTime() constructor uses your system's default timezone, and the Z pattern in the formatter prints the timezone offset.

Your system's default timezone offset is -07:00, that's why you get this output.

If you want exactly the output with Z in the end, you must convert the DateTime object to an org.joda.time.Instant:

String strNow = new DateTime("2017-06-14T00:00:00Z").toInstant().toString();

strNow will be 2017-06-14T00:00:00.000Z.

If you want to get the current time in UTC (instead of parsing a String), you must tell explicity to DateTime constructor to use UTC, using new DateTime(DateTimeZone.UTC).

The code above also prints the milliseconds. If you don't want this, another alternative is to use a DateTimeFormatterBuilder:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .appendPattern("yyyy-MM-dd'T'HH:mm:ss")
    // append Z if offset is zero (UTC)
    .appendTimeZoneOffset("Z", true, 2, 2)
    // create formatter
    .toFormatter();
String strNow = new DateTime("2017-06-14T00:00:00Z").toInstant().toString(formatter);

This will format the date accordinlgy (without the milliseconds):

2017-06-14T00:00:00Z


问:
How can we manipulate std class in php?
Is it possible to add elements to stdclasses like we do for arrays?

```<code>Array (
  [0] => item 1
  [1] => item 2
)

Stdclass (
  [0] => item 1
  [1] => item 2
)
</code>```

Is it generally harder to manipulate objects as compared to arrays? Since we have lots of array functions to make use of etc.

答:
Well, the documentation states:

Created by typecasting to object.

As such, you can cast back and forth between (array) and (object) to work stdClass instances with array functions.

Title: How can we manipulate std class in php?

Body:
Is it possible to add elements to stdclasses like we do for arrays?

Array (
  [0] => item 1
  [1] => item 2
)

Stdclass (
  [0] => item 1
  [1] => item 2
)

Is it generally harder to manipulate objects as compared to arrays? Since we have lots of array functions to make use of etc.


答:
Don't do this:

```<code>filter.setAttribute('onchange', 'filterChanged()');
</code>```

but do:

```<code>filter.addEventListener('change', filterChanged);
</code>```

Title: onchange() function not defined (inaccessible from index.html?)

Body:
Don't do this:

filter.setAttribute('onchange', 'filterChanged()');

but do:

filter.addEventListener('change', filterChanged);


问:
403 forbideen error while doing authentication using openid
When i was trying to open

http://localhost:8000/openid/login

i am facing 403 forbideen error

答:
Cause of 403 Forbidden Errors
403 errors are almost always caused by issues where you're trying to access something that you don't have access to.

follow this link how to fixe it : https://www.lifewire.com/g00/403-forbidden-error-explained-2617989?i10c.referrer=https%3A%2F%2Fwww.google.lu%2F


问:
How to get value of selected in ddSlick dropdown
I use some ddslick drop down menus in a form and I want to get the selected values when submit that form.

Already try to create a hidden input near that menus:

```<code><input type="hidden" name="hiddeninput" id="hiddeninput"  />
</code>```

then I assign the selected value to that input name:

```<code>    $(document).ready(function() {

                //Dropdown Básico
                for (var i=0;i<10;i++){
                $('#dropdownBasico'+i).ddslick({
                    data: ddData,
                    width: 150,
                    imagePosition: "left",
                    selectText: "some texts",
                    onSelected: function(data){
                     if(data.selectedIndex > 0) {
                              $('#hiddeninput').val=selectedData.value;
                            alert(selectedData.value);
                        }
                    }
                });
}
</code>```

But the value I get is always empty. Please advice the solution, and note that I have several menus here (thats why I use for loop to change the name accordingly). I already research some similar questions like: Get value of selected <option> in ddSlick dropdown and ddslick select options won'st post value of selected option - jquery plugin and tried them but get no working solution ! Thanks a lot!

答:
```<code>$(document).ready(function() {
      //Dropdown Básico
      for (var i=0;i<10;i++){
      $('#dropdownBasico'+i).ddslick({
          data: ddData,
          width: 150,
          imagePosition: "left",
          selectText: "some texts",
          onSelected: function(data){
             alert(data.selectedData.value);
          }
      });
}
</code>```

Body:
I use some ddslick drop down menus in a form and I want to get the selected values when submit that form.

Already try to create a hidden input near that menus:

<input type="hidden" name="hiddeninput" id="hiddeninput"  />

then I assign the selected value to that input name:

    $(document).ready(function() {

                //Dropdown Básico
                for (var i=0;i<10;i++){
                $('#dropdownBasico'+i).ddslick({
                    data: ddData,
                    width: 150,
                    imagePosition: "left",
                    selectText: "some texts",
                    onSelected: function(data){
                     if(data.selectedIndex > 0) {
                              $('#hiddeninput').val=selectedData.value;
                            alert(selectedData.value);
                        }
                    }
                });
}

But the value I get is always empty. Please advice the solution, and note that I have several menus here (thats why I use for loop to change the name accordingly). I already research some similar questions like: Get value of selected <option> in ddSlick dropdown and ddslick select options won'st post value of selected option - jquery plugin and tried them but get no working solution ! Thanks a lot!


问:
How to convert a NSString to long double?
I am dealing with a long double value that can have huge values.

At one time I have this number represented as NSString and I need to convert it to long double. I see that the only API I have is

```<code>[myString doubleValue];
</code>```

I don't see a longDoubleValue.

Trying to convert this number using doubleValue...

```<code>long double x = (long double)[@"3765765765E933" doubleValue];
</code>```

gives me inf and the number in question is a legit long double value, as these numbers can go up to 1.18973149535723176502E+4932.

How do I do that?

答:
In fact the answer of mag_zbc is almost there. The last line is incorrect.

Considering that the string has exponent, the correct is:

```<code>- (long double)longDoubleValue {
  NSArray *array = [string componentsSeparatedByString:@"E"];
  long double mantis = (long double)[array[0] doubleValue];
  long double exponent = (long double)[array[1] doubleValue];
  long double multiplier = powl(10.0L, exponent);
  return mantis * multiplier;
}
</code>```

Body:
I am dealing with a long double value that can have huge values.

At one time I have this number represented as NSString and I need to convert it to long double. I see that the only API I have is

[myString doubleValue];

I don't see a longDoubleValue.

Trying to convert this number using doubleValue...

long double x = (long double)[@"3765765765E933" doubleValue];

gives me inf and the number in question is a legit long double value, as these numbers can go up to 1.18973149535723176502E+4932.

How do I do that?

Body:
In fact the answer of mag_zbc is almost there. The last line is incorrect.

Considering that the string has exponent, the correct is:

- (long double)longDoubleValue {
  NSArray *array = [string componentsSeparatedByString:@"E"];
  long double mantis = (long double)[array[0] doubleValue];
  long double exponent = (long double)[array[1] doubleValue];
  long double multiplier = powl(10.0L, exponent);
  return mantis * multiplier;
}


问:
Calling a function in a separate function file - matlab
From what I understood of matlab, if you want to define a function and use it in your "main file" you need to write the function in a separate file and to call it at the beginning of your "main file" with addpath('...\myfunction.m').

Now let's say I define a function f1 in a file f1.m that I use in main.m, if I want to define a function f2 (in another file) that needs to call f1, can I use addpath()...\f1.m in my f2.m file ? Or what is the best way of calling f1 in f2 ?

答:
The best way to do that is having your functions at same folder, or you'll need to add folder by folder.
So if you put f1.m, f2.m, f3.m at different folders, you have to call a addpath for every function.
If you have a folder 'myfunctions', all you need to do is addpath('...\myfunctions\').

If you have a folder named myfunctions with your functions at same folder of you main script, you just have to add that folder to path.
For example:

```<code>%Main script
addpath('myfunctions')
x = -0.5 + rand(100,1);
y = -0.5 + rand(100,1);
[a,b] = f1(x,y);
</code>```

Inside the folder myfunctions you have the files f1.m and f2.m:

```<code>function [a,b] = f1(x,y)
a = x + y;
b = f2(a);
end
</code>```

```<code>function b = f2(inp)
b = inp<0;
end
</code>```

You can't use addpath with a file, it has to be a folder.

Body:
The best way to do that is having your functions at same folder, or you'll need to add folder by folder.
So if you put f1.m, f2.m, f3.m at different folders, you have to call a addpath for every function.
If you have a folder 'myfunctions', all you need to do is addpath('...\myfunctions\').

If you have a folder named myfunctions with your functions at same folder of you main script, you just have to add that folder to path.
For example:

%Main script
addpath('myfunctions')
x = -0.5 + rand(100,1);
y = -0.5 + rand(100,1);
[a,b] = f1(x,y);

Inside the folder myfunctions you have the files f1.m and f2.m:

function [a,b] = f1(x,y)
a = x + y;
b = f2(a);
end

function b = f2(inp)
b = inp<0;
end

You can't use addpath with a file, it has to be a folder.


问:
How can I convert this javascript class to something react can use?
```<code>const Component = require('../Component')

class PlayerComponent extends Component {
    constructor(uid, username){
        super('PlayerComponent');
        this.username = username;
        this.uid = uid;
    }
}

module.exports = PlayerComponent;
</code>```

<p>This is in a folder called shared that I want to use on the server and the client, right now it's working fine on the server but I can't seem to figure out how to transpile the whole shared folder so I can also use it on the client. </p>

答: You should inherit from React.Component on the client.  </p>

Body:
const Component = require('../Component')

class PlayerComponent extends Component {
    constructor(uid, username){
        super('PlayerComponent');
        this.username = username;
        this.uid = uid;
    }
}

module.exports = PlayerComponent;

This is in a folder called shared that I want to use on the server and the client, right now it's working fine on the server but I can't seem to figure out how to transpile the whole shared folder so I can also use it on the client.


问:
Rails Uploading multiple images with Carrierwave
I have been following this tutorial to upload multiple images with carrier wave.

It works as expected but it is displaying the following below the image:

```<code>[#<ImageUploader:0xaeb3490 @model=#<Post id: 19, created_at: "2017-07-07 09:33:50", updated_at: "2017-07-07 09:33:50", lat: 54.635, long: -5.84582, images: ["87a8c63a9be6af171244299fc0b0a27e--stunning-art-street-art-illusions.jpg"], artist: "Vemeer", year: nil>, @mounted_as=:images, @storage=#<CarrierWave::Storage::File:0xaeb3430 @uploader=#<ImageUploader:0xaeb3490 ...>>, @file=#<CarrierWave::SanitizedFile:0xaeb3100 @file="C:/path/public/uploads/post/images/19/87a8c63a9be6af171244299fc0b0a27e--stunning-art-street-art-illusions.jpg", @original_filename=nil, @content_type=nil>, @versions={}>]
</code>```

As explained in the tutorial to get the multiple uploads I did the following:

Rails Migration to create array of images:

```<code>class AddImagesToGallery < ActiveRecord::Migration
  def change
    add_column :posts, :images, :string, array: true, default: []
  end
end
</code>```

Edited posts/_form.html.haml:

```<code>= f.file_field :images, multiple: true
</code>```

Edited post_params

```<code>def post_params
    post_params.require(:post).permit(:artist, :year, :long, :lat, {images: []})
end
</code>```

Display the images in posts/show.html.haml

```<code>=@mural.images.each do |image|
    = image_tag(image.url)
</code>```

Any help is appreciated!

答:
It works as expected but it is displaying the following below the image:

```<code>[#<ImageUploader:0xaeb3490 @model=#<Post id: 19, created_at: "2017-07-07 09:33:50", updated_at: "2017-07-07 09:33:50", lat: 54.635, long: -5.84582, images: ["87a8c63a9be6af171244299fc0b0a27e--stunning-art-street-art-illusions.jpg"], artist: "Vemeer", year: nil>, @mounted_as=:images, @storage=#<CarrierWave::Storage::File:0xaeb3430 @uploader=#<ImageUploader:0xaeb3490 ...>>, @file=#<CarrierWave::SanitizedFile:0xaeb3100 @file="C:/path/public/uploads/post/images/19/87a8c63a9be6af171244299fc0b0a27e--stunning-art-street-art-illusions.jpg", @original_filename=nil, @content_type=nil>, @versions={}>]
</code>```

This line

```<code>=@mural.images.each do |image|
    = image_tag(image.url)
</code>```

should be

```<code>- @mural.images.each do |image|
    = image_tag(image.url)
</code>```

Notice the difference between = and -. = is used to display the output. - is used to iterate over the object.

Body:
I have been following this tutorial to upload multiple images with carrier wave.

It works as expected but it is displaying the following below the image:

[#<ImageUploader:0xaeb3490 @model=#<Post id: 19, created_at: "2017-07-07 09:33:50", updated_at: "2017-07-07 09:33:50", lat: 54.635, long: -5.84582, images: ["87a8c63a9be6af171244299fc0b0a27e--stunning-art-street-art-illusions.jpg"], artist: "Vemeer", year: nil>, @mounted_as=:images, @storage=#<CarrierWave::Storage::File:0xaeb3430 @uploader=#<ImageUploader:0xaeb3490 ...>>, @file=#<CarrierWave::SanitizedFile:0xaeb3100 @file="C:/path/public/uploads/post/images/19/87a8c63a9be6af171244299fc0b0a27e--stunning-art-street-art-illusions.jpg", @original_filename=nil, @content_type=nil>, @versions={}>]

As explained in the tutorial to get the multiple uploads I did the following:

Rails Migration to create array of images:

class AddImagesToGallery < ActiveRecord::Migration
  def change
    add_column :posts, :images, :string, array: true, default: []
  end
end

Edited posts/_form.html.haml:

= f.file_field :images, multiple: true

Edited post_params

def post_params
    post_params.require(:post).permit(:artist, :year, :long, :lat, {images: []})
end

Display the images in posts/show.html.haml

=@mural.images.each do |image|
    = image_tag(image.url)

Any help is appreciated!

Body:
It works as expected but it is displaying the following below the image:

[#<ImageUploader:0xaeb3490 @model=#<Post id: 19, created_at: "2017-07-07 09:33:50", updated_at: "2017-07-07 09:33:50", lat: 54.635, long: -5.84582, images: ["87a8c63a9be6af171244299fc0b0a27e--stunning-art-street-art-illusions.jpg"], artist: "Vemeer", year: nil>, @mounted_as=:images, @storage=#<CarrierWave::Storage::File:0xaeb3430 @uploader=#<ImageUploader:0xaeb3490 ...>>, @file=#<CarrierWave::SanitizedFile:0xaeb3100 @file="C:/path/public/uploads/post/images/19/87a8c63a9be6af171244299fc0b0a27e--stunning-art-street-art-illusions.jpg", @original_filename=nil, @content_type=nil>, @versions={}>]

This line

=@mural.images.each do |image|
    = image_tag(image.url)

should be

- @mural.images.each do |image|
    = image_tag(image.url)

Notice the difference between = and -. = is used to display the output. - is used to iterate over the object.


问:
Very strange problem about NSString
A very strange behavior about this function,

```<code>void* getNSString(const NSString* str){

str = @"This is new test";
//NSString* str1 = @"so strange test";

return;
}
</code>```

Then

```<code>NSLog(@"%@",getNSString(@"test"));
</code>```

The result will be

```<code>This is new test
</code>```

if uncomment

```<code>NSString* str1 = @"so strange test";
</code>```

My understanding is that nothing is returned, so that should be NULL , why print out those string ?

Then result will be

```<code>so strange test
</code>```

答:
I don't believe that nothing is returned. I believe that it's undefined. In other words, anything could be returned.

In this case, it looks like it's returning whatever happened to be on the stack at a given location. That happens to be one of the strings you modified or created but I can assure you this is a fortunate accident (or unfortunate since a crash would probably be better).

If you want nothing to be returned, you need to change:

```<code>void* getNSString(const NSString* str){
</code>```

to:

```<code>void getNSString(const NSString* str){
</code>```

Title: Very strange problem about NSString

Body:
A very strange behavior about this function,

void* getNSString(const NSString* str){

str = @"This is new test";
//NSString* str1 = @"so strange test";

return;
}

Then

NSLog(@"%@",getNSString(@"test"));

The result will be

This is new test

if uncomment

NSString* str1 = @"so strange test";

My understanding is that nothing is returned, so that should be NULL , why print out those string ?

Then result will be

so strange test

Body:
I don't believe that nothing is returned. I believe that it's undefined. In other words, anything could be returned.

In this case, it looks like it's returning whatever happened to be on the stack at a given location. That happens to be one of the strings you modified or created but I can assure you this is a fortunate accident (or unfortunate since a crash would probably be better).

If you want nothing to be returned, you need to change:

void* getNSString(const NSString* str){

to:

void getNSString(const NSString* str){


问:
Mixing parentheses and square brackets in array initialization
The following code snippet assigns some values by mixing parentheses and square brackets without any error, however most of the other combinations (e.g. parentheses inside square brackets) don't work at all.

```<code>var myItems = [];
myItems[5] = ("A1", "B1", ["C1","C2","C3"]);
</code>```

When I print the values, they are exactly the same in two different browsers.

```<code>myItems[5]: C1,C2,C3
myItems[5][0]: C1
myItems[5][1]: C2
myItems[5][2]: C3
myItems[5][2][0]: C
myItems[5][2][1]: 3
myItems[5][2][2]: undefined
</code>```

It seems that only the part inside square brackets is considered. Is this outcome defined by the JavaScript standard (ECMA-262)? Or is it just what the interpreter/engine (Chrome and Firefox in my case) did in the face of an illegal use?

var myItems = [];

//myItems[5] = ["A1", "B1", ["C1","C2","C3"]];
myItems[5] = ("A1", "B1", ["C1","C2","C3"]);

document.getElementById("demo").innerHTML =
"myItems[5]:       " + myItems[5]       + "
" +
"myItems[5][0]:    " + myItems[5][0]    + "
" +
"myItems[5][1]:    " + myItems[5][1]    + "
" +
"myItems[5][2]:    " + myItems[5][2]    + "
" +
"myItems[5][2][0]: " + myItems[5][2][0] + "
" +
"myItems[5][2][1]: " + myItems[5][2][1] + "
" +
"myItems[5][2][2]: " + myItems[5][2][2] + "
" +
"";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo"></p></code>```

EDIT: I know the correct use of brackets (my fiddle already had it), but I'm asking if the outcome is deterministic at such a wrong use. Since the interpreters I've tried don't produce any error and give the same results, I want to know if these results are ensured by the standard and/or all the other interpreters will do the same.

答:
From MDN on comma operator

The comma operator evaluates each of its operands (from left to right)
  and returns the value of the last operand.

So

```<code>myItems[5] = ("A1", "B1", ["C1","C2","C3"]);
</code>```

Turns to

```<code>myItems[5] = (["C1","C2","C3"]);
</code>```

Now you've got yourself an array with 6 elements (5x undefined and the array of three strings you assigned at sixth position).

And it is exactly what you're getting printed out.

Body:
The following code snippet assigns some values by mixing parentheses and square brackets without any error, however most of the other combinations (e.g. parentheses inside square brackets) don't work at all.

var myItems = [];
myItems[5] = ("A1", "B1", ["C1","C2","C3"]);

When I print the values, they are exactly the same in two different browsers.

myItems[5]: C1,C2,C3
myItems[5][0]: C1
myItems[5][1]: C2
myItems[5][2]: C3
myItems[5][2][0]: C
myItems[5][2][1]: 3
myItems[5][2][2]: undefined

It seems that only the part inside square brackets is considered. Is this outcome defined by the JavaScript standard (ECMA-262)? Or is it just what the interpreter/engine (Chrome and Firefox in my case) did in the face of an illegal use?

var myItems = [];

//myItems[5] = ["A1", "B1", ["C1","C2","C3"]];
myItems[5] = ("A1", "B1", ["C1","C2","C3"]);

document.getElementById("demo").innerHTML =
"myItems[5]:       " + myItems[5]       + "
" +
"myItems[5][0]:    " + myItems[5][0]    + "
" +
"myItems[5][1]:    " + myItems[5][1]    + "
" +
"myItems[5][2]:    " + myItems[5][2]    + "
" +
"myItems[5][2][0]: " + myItems[5][2][0] + "
" +
"myItems[5][2][1]: " + myItems[5][2][1] + "
" +
"myItems[5][2][2]: " + myItems[5][2][2] + "
" +
"";

EDIT: I know the correct use of brackets (my fiddle already had it), but I'm asking if the outcome is deterministic at such a wrong use. Since the interpreters I've tried don't produce any error and give the same results, I want to know if these results are ensured by the standard and/or all the other interpreters will do the same.

Body:
From MDN on comma operator

The comma operator evaluates each of its operands (from left to right)
  and returns the value of the last operand.

So

myItems[5] = ("A1", "B1", ["C1","C2","C3"]);

Turns to

myItems[5] = (["C1","C2","C3"]);

Now you've got yourself an array with 6 elements (5x undefined and the array of three strings you assigned at sixth position).

And it is exactly what you're getting printed out.


问:
Replace script tag that has a dynamic version number which keeps changing
I would like to remove or replace this string in an HTML file using javascript.

```<code>'<script src="../assets/js/somejs.js?1.0.953"></script>'
</code>```

Trouble is, the version number "1.0.953" keeps changing so I can't use a simple string.replace

答:
Ok this is messy but it works...</p>

```<code>String.prototype.replaceAnyVersionOfScript = function(target, replacement) {

    // 1. Build the string we need to replace (target + xxx + ></script>)
    var targetLength = target.length;
    var targetStartPos = this.indexOf(target);
    var dynamicStartPos = targetStartPos + targetLength;
    var dynamicEndPos = this.indexOf('></script>', dynamicStartPos) + 10;
    var dynamicString = this.substring(dynamicStartPos, dynamicEndPos);
    var dymamicStringToReplace = target + dynamicString;

    // 2. Now we know what we are looking for. We can replace it.
    return this.replace(dymamicStringToReplace, replacement);

};

shellHTML = shellHTML.replaceAnyVersionOfScript('<script src="./assets/js/CloudZoom.js', '');
</code>```

Body:
I would like to remove or replace this string in an HTML file using javascript.

''

Trouble is, the version number "1.0.953" keeps changing so I can't use a simple string.replace

Body:
Ok this is messy but it works...

String.prototype.replaceAnyVersionOfScript = function(target, replacement) {

    // 1. Build the string we need to replace (target + xxx + ></script>)
    var targetLength = target.length;
    var targetStartPos = this.indexOf(target);
    var dynamicStartPos = targetStartPos + targetLength;
    var dynamicEndPos = this.indexOf('></script>', dynamicStartPos) + 10;
    var dynamicString = this.substring(dynamicStartPos, dynamicEndPos);
    var dymamicStringToReplace = target + dynamicString;

    // 2. Now we know what we are looking for. We can replace it.
    return this.replace(dymamicStringToReplace, replacement);

};

shellHTML = shellHTML.replaceAnyVersionOfScript('<script src="./assets/js/CloudZoom.js', '');


问:
How to select bottom most rows?
I can do SELECT TOP (200) ... but why not BOTTOM (200)?

Well not to get into philosophy what I mean is, how can I do the equivalent of TOP (200) but in reverse (from the bottom, like you'd expect BOTTOM to do...)?

答:
"Tom H" answer above is correct and it works for me in getting Bottom 5 rows.

```<code>SELECT [KeyCol1], [KeyCol2], [Col3]
FROM
(SELECT TOP 5 [KeyCol1],
       [KeyCol2],
       [Col3]
  FROM [dbo].[table_name]
  ORDER BY [KeyCol1],[KeyCol2] DESC) SOME_ALAIS
  ORDER BY [KeyCol1],[KeyCol2] ASC
</code>```

Thanks.

Title: How to select bottom most rows?

Body:
"Tom H" answer above is correct and it works for me in getting Bottom 5 rows.

SELECT [KeyCol1], [KeyCol2], [Col3]
FROM
(SELECT TOP 5 [KeyCol1],
       [KeyCol2],
       [Col3]
  FROM [dbo].[table_name]
  ORDER BY [KeyCol1],[KeyCol2] DESC) SOME_ALAIS
  ORDER BY [KeyCol1],[KeyCol2] ASC

Thanks.


问:
bounce and zoom only first cell of uitableview like 'OYO' app of iOS
I have uitableview in my iphone application.

My UITableViewCell has only one imageView.

There are such 7 uitableviewcells available with my uitableview.

Upto now I have done correctly. Below is the image where I have problem. The first cell not getting stacked to top edge of UITableView. See below image. Thus Not getting actual zooming effect when pulls down and drag scroll in downward direction (i.e. contentOffset.Y negative). Part of first cell hides behind second cell.

below is my code

```<code>- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _tvMaharajPics) {

        if (scrollView.contentOffset.y <= 0) {
            UITableViewCell *cell = [_tvMaharajPics cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            CGRect frame = cell.frame;
            frame.size.height = (self.view.frame.size.width * (3.0 / 4.0)) - scrollView.contentOffset.y;
            cell.frame = frame;
        }
    }

    // To disable bounce in bottom direction of UITableView
    if (scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.frame.size.height) {
        CGPoint offset = scrollView.contentOffset;
        offset.y = scrollView.contentSize.height - scrollView.frame.size.height;
        scrollView.contentOffset = offset;
    }
}
</code>```

I only want to bounce and show zoom image effect in first cell only when user pulls down and drag scroll in downward direction (i.e. contentOffset.Y negative).

"SIMILAR EFFECT IS DEMONSTRATED IN 'OYO' APP WHEN USER LOOKS INTO ROOM IMAGES"

答:
You can swap the contents of the tableview cell (1st) to the tableview header and use this library to achieve this effect easily.

GSKStretchyHeaderView

Or if you want to code yourself then use this tutorial to create this effect
Tuturial
. Just remove the masking part from it.

Body:
I have uitableview in my iphone application.

My UITableViewCell has only one imageView.

There are such 7 uitableviewcells available with my uitableview.

Upto now I have done correctly. Below is the image where I have problem. The first cell not getting stacked to top edge of UITableView. See below image. Thus Not getting actual zooming effect when pulls down and drag scroll in downward direction (i.e. contentOffset.Y negative). Part of first cell hides behind second cell.

below is my code

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _tvMaharajPics) {

        if (scrollView.contentOffset.y <= 0) {
            UITableViewCell *cell = [_tvMaharajPics cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            CGRect frame = cell.frame;
            frame.size.height = (self.view.frame.size.width * (3.0 / 4.0)) - scrollView.contentOffset.y;
            cell.frame = frame;
        }
    }

    // To disable bounce in bottom direction of UITableView
    if (scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.frame.size.height) {
        CGPoint offset = scrollView.contentOffset;
        offset.y = scrollView.contentSize.height - scrollView.frame.size.height;
        scrollView.contentOffset = offset;
    }
}

I only want to bounce and show zoom image effect in first cell only when user pulls down and drag scroll in downward direction (i.e. contentOffset.Y negative).

"SIMILAR EFFECT IS DEMONSTRATED IN 'OYO' APP WHEN USER LOOKS INTO ROOM IMAGES"


问:
Create a multidimensional array in a loop
I am trying to create an array like this in a loop:

```<code>$dataPoints = array(
    array('x' => 4321, 'y' => 2364),
    array('x' => 3452, 'y' => 4566),
    array('x' => 1245, 'y' => 3452),
    array('x' => 700, 'y' => 900),
    array('x' => 900, 'y' => 700));
</code>```

with this code

```<code>$dataPoints = array();
$brands = array("COCACOLA","DellChannel","ebayfans","google",
    "microsoft","nikeplus","amazon");
foreach ($brands as $value) {
    $resp = GetTwitter($value);
    $dataPoints = array(
        "x"=>$resp['friends_count'],
        "y"=>$resp['statuses_count']);
}
</code>```

but when loop completes my array looks like this:

```<code>Array ( [x] => 24 [y] => 819 )
</code>```

答:
use array_merge($array1,$array2) make it simple use two array one for use in iteration and another for storing the final result. checkout the code.

```<code>$dataPoints = array();
$dataPoint = array();

$brands = array(
    "COCACOLA","DellChannel","ebayfans","google","microsoft","nikeplus","amazon");
foreach($brands as $value){
    $resp = GetTwitter($value);
    $dataPoint = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);
    $dataPoints = array_merge($dataPoints,$dataPoint);
}
</code>```

Body:
I am trying to create an array like this in a loop:

$dataPoints = array(
    array('x' => 4321, 'y' => 2364),
    array('x' => 3452, 'y' => 4566),
    array('x' => 1245, 'y' => 3452),
    array('x' => 700, 'y' => 900),
    array('x' => 900, 'y' => 700));

with this code

$dataPoints = array();
$brands = array("COCACOLA","DellChannel","ebayfans","google",
    "microsoft","nikeplus","amazon");
foreach ($brands as $value) {
    $resp = GetTwitter($value);
    $dataPoints = array(
        "x"=>$resp['friends_count'],
        "y"=>$resp['statuses_count']);
}

but when loop completes my array looks like this:

Array ( [x] => 24 [y] => 819 )

Body:
use array_merge($array1,$array2) make it simple use two array one for use in iteration and another for storing the final result. checkout the code.

$dataPoints = array();
$dataPoint = array();

$brands = array(
    "COCACOLA","DellChannel","ebayfans","google","microsoft","nikeplus","amazon");
foreach($brands as $value){
    $resp = GetTwitter($value);
    $dataPoint = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);
    $dataPoints = array_merge($dataPoints,$dataPoint);
}


答:
this is common format to addEventListener()

```<code>object.addEventListener("change", myScript);
</code>```

so update your code

```<code>filter.setAttribute('onchange', 'filterChanged()');
</code>```

to

```<code>filter.addEventListener('change', filterChanged);
</code>```

for more information

https://www.w3schools.com/jsref/met_document_addeventlistener.asp

Body:
i am assigning an 'onchange' attribute to a <select> tag in my html. I have done so successfully in my main.js file (which is bundled into bundle.js). My bundle.js is then referenced in the index.html.

Whenever the onchange event tries to use the function i have defined
 filterChanged(), it provides a reference error: "filterChanged is not defined
    at HTMLSelectElement.onchange"

i originally thought it may be due to the function not being a global variable, so i assigned to to a var and the issue persists.

see below the code -

main.js

var filterChanged = function() {
    console.log('filter changed');
}

window.onload = function() {
    let filter = document.getElementById('filter-list');
    filter.setAttribute('onchange', 'filterChanged()');
}

index.html

<!doctype html>

    <meta charset="UTF-8">
    <title>TestProj</title>

Todos

Number of items to show

    <select id="filter-list" name="filter">
            <option selected="true" value="list10">10</option>
            <option value="list20">20</option>
            <option value="list30">30</option>
    </select>

Body:
this is common format to addEventListener()

object.addEventListener("change", myScript);

so update your code

filter.setAttribute('onchange', 'filterChanged()');

to

filter.addEventListener('change', filterChanged);

for more information

https://www.w3schools.com/jsref/met_document_addeventlistener.asp


问:
C# LINQ OrderBy several clauses
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

```<code>public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}
</code>```

My project status enum:

```<code>public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}
</code>```

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

```<code>projects = projects.OrderBy(x => x.StatusId).ToList();
</code>```

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

答:
Just use several orderings, the first one with OrderByDescending, then the rest with ThenByDescending:

```<code>projects = projects
    .OrderByDescending(p => p.StatusId == Status.Draft)
    .ThenByDescending(p => p.StatusId == Status.Pending)
    .ThenByDescending(p => p.StatusId == Status.Refused)
    .ThenByDescending(p => p.StatusId == Status.Validated)
    .ToList();
</code>```

Title: C# LINQ OrderBy several clauses

Body:
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}

My project status enum:

public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

projects = projects.OrderBy(x => x.StatusId).ToList();

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

Body:
Just use several orderings, the first one with OrderByDescending, then the rest with ThenByDescending:

projects = projects
    .OrderByDescending(p => p.StatusId == Status.Draft)
    .ThenByDescending(p => p.StatusId == Status.Pending)
    .ThenByDescending(p => p.StatusId == Status.Refused)
    .ThenByDescending(p => p.StatusId == Status.Validated)
    .ToList();


问:
Random.Range and how to getRandom

These 9 balls are generated randomly according to the code below.

```<code>   for(int i=0;i<balls.Length; i++)
    {
        getBallsRandom = new Randomizer(balls[i].sprites);
        balls[i].setCurrentSpriteIndex(getBallsRandom.getRandom());
    }
</code>```

All I want is that every time you generate 3 balls of each color. For example in the image below.

答:
Make a list of your balls list_balls = [Green, Green, Green, Red, Red, Red, Grey, Grey, Grey].

Here the idea in pseudocode:

```<code>for i=1 to 3: // for each tube
  for j=1 to 3: // 3 balls in each tube
    Pick a random ball from `list_balls`
    Remove the chosen ball from `list_balls`
</code>```

I let you the pleasure to write that in C#

Title: Random.Range and how to getRandom

Body:
These 9 balls are generated randomly according to the code below.

   for(int i=0;i<balls.Length; i++)
    {
        getBallsRandom = new Randomizer(balls[i].sprites);
        balls[i].setCurrentSpriteIndex(getBallsRandom.getRandom());
    }

All I want is that every time you generate 3 balls of each color. For example in the image below.

Body:
Make a list of your balls list_balls = [Green, Green, Green, Red, Red, Red, Grey, Grey, Grey].

Here the idea in pseudocode:

for i=1 to 3: // for each tube
  for j=1 to 3: // 3 balls in each tube
    Pick a random ball from `list_balls`
    Remove the chosen ball from `list_balls`

I let you the pleasure to write that in C#


答:
Sure, you can add new elements...

```<code>$Object = new StdClass();
$Object->item1 = 1;
$Object->item2 = 2;
</code>```

If you want to iterate object as array you should use PHP SPL ArrayIterator or RecursiveArrayIterator.

Also you can use typecasting to move from array to object and back...

```<code>$array = array('item1', 'item2');
$Object = (object)$array;
var_dump($object);
$array = (array)$Object;
var_dump($array);
</code>```

Title: How can we manipulate std class in php?

Body:
Is it possible to add elements to stdclasses like we do for arrays?

Array (
  [0] => item 1
  [1] => item 2
)

Stdclass (
  [0] => item 1
  [1] => item 2
)

Is it generally harder to manipulate objects as compared to arrays? Since we have lots of array functions to make use of etc.

Body:
Sure, you can add new elements...

$Object = new StdClass();
$Object->item1 = 1;
$Object->item2 = 2;

If you want to iterate object as array you should use PHP SPL ArrayIterator or RecursiveArrayIterator.

Also you can use typecasting to move from array to object and back...

$array = array('item1', 'item2');
$Object = (object)$array;
var_dump($object);
$array = (array)$Object;
var_dump($array);