问:
@RolesAllowed etc. without web.xml
I am currently working on a quite modular application where we have many jars that will be packaged and glued together in a war file.

Some of these jar files have REST resources that want to be secured. Common way is the @RolesAllowed annotation etc.

From my current knowledge this implies an existing web.xml in the WAR. This way we would have to implement jar-specific information (e.g. context roots) inside the WAR, not in the place where it belongs.

Like the most things nowadays - is there a way to programmatically set up security contexts etc. without a web.xml?

答:
You can restrict access to your REST resources by registering RolesAllowedDynamicFeature in your REST configuration class that extends from ResourceConfig

```<code>public class ApplicationConfig extends ResourceConfig {
  public ApplicationConfig() {
    super(ApplicationConfig.class);
    register(RolesAllowedDynamicFeature.class);
  }
}
</code>```

So you can use your application roles on your resources methods like this

```<code>import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

@Path("secured")
@PermitAll
public class SecuredResource {

  @GET
  @Path("user")
  @RolesAllowed("user")
  public String user(@Context SecurityContext sc) {
    boolean test = sc.isUserInRole("user");
    return (test) ? "true": "false";
  }

  @GET
  @Path("admin")
  @RolesAllowed("admin")
  public String admin(@Context SecurityContext sc) {
    boolean test = sc.isUserInRole("admin");
    return (test) ? "true": "false";
  }
}
</code>```

Jersey documentation has more details on securing REST resources using annotations here

https://jersey.github.io/documentation/latest/security.html#d0e12428

Title: @RolesAllowed etc. without web.xml

Body:
You can restrict access to your REST resources by registering RolesAllowedDynamicFeature in your REST configuration class that extends from ResourceConfig

public class ApplicationConfig extends ResourceConfig {
  public ApplicationConfig() {
    super(ApplicationConfig.class);
    register(RolesAllowedDynamicFeature.class);
  }
}

So you can use your application roles on your resources methods like this

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

@Path("secured")
@PermitAll
public class SecuredResource {

  @GET
  @Path("user")
  @RolesAllowed("user")
  public String user(@Context SecurityContext sc) {
    boolean test = sc.isUserInRole("user");
    return (test) ? "true": "false";
  }

  @GET
  @Path("admin")
  @RolesAllowed("admin")
  public String admin(@Context SecurityContext sc) {
    boolean test = sc.isUserInRole("admin");
    return (test) ? "true": "false";
  }
}

Jersey documentation has more details on securing REST resources using annotations here

https://jersey.github.io/documentation/latest/security.html#d0e12428


来源: stackexchange

问:
I need to trigger a script when a specific slide is shown (flexslider)
In flexslider when a on specific slide (like just slide #2) i need to excecute some javascript when that slide is shown. </p>

答:
Try to use callback function of Flexslide, which fires after each slider animation completes.
Try to use setTimeout() function if your jQuery gets executed few micro-seconds before stable slide view.
https://woocommerce.com/flexslider/

after: function(){
}

ContentLicense: CC BY-SA 3.0


问:
Schema.org markup for questions & answers inside 'Product'
Could somebody advise the best way to add correct Schema.org markup for the page where the user can buy some product? I am adding the Product tag there (for Rich Snippets).

I would like to add possibility to ask questions about this product, but I didn't find what properties I could use as embedded items.

Example:

    <meta itemprop="brand" content="Brand">
    <meta itemprop="url" content="URL">
    ......

         ......

....

....

    ...

        ......

....

....

```

答:
There is no property to add a Question to a Product.

But there is a property to convey that a Question is about a Product: about.

There are different ways how this can be marked up with Microdata. Here is an example using itemref:

```

To link an Answer to a Question, you can use suggestedAnswer/acceptedAnswer.

Body:
There is no property to add a Question to a Product.

But there is a property to convey that a Question is about a Product: about.

There are different ways how this can be marked up with Microdata. Here is an example using itemref:

<div id="product-42" itemprop="about" itemscope itemtype="http://schema.org/Product">
</div>

<div itemscope itemtype="http://schema.org/Question" itemref="product-42">
</div>

<div itemscope itemtype="http://schema.org/Question" itemref="product-42">
</div>

To link an Answer to a Question, you can use suggestedAnswer/acceptedAnswer.


问:
HTML5 file ignore CSS
I just approached HTML and CSS.

I wrote a little HTML5 file and a CSS file, but my HTML doesn't get any info from CSS because nothing is styled.

I'm using Eclipse, there is a directory "WebContent" where there is the HTML file, and the CSS is in WebContent/WEB_INF/CSS/file.css.

HTML file:

```<code><html lang="it">

    <head>
    <link rel="stylesheet" href="/WEB-INF/CSS/NewFile.css" type="text/css">

        <title>Strumenti musicali</title>
        <meta charset="UTF-8">
        <meta name="description" content="Negozio di strumenti musicali">
        <meta name="keywords" content="strumenti, musicali, negozio">
        <meta name="author" content="Paolo">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>

    <body>

        <nav>
            <a href="/html/">HTML</a> |
            <a href="/css/">CSS</a> |
            <a href="/js/">JavaScript</a> |
            <a href="/jquery/">jQuery</a>
        </nav>

    <h2>The title attribute</h2>

    <p title="I'm a tooltip">
        Mouse over this paragraph, to display the title attribute as a tooltip.
    </p>

    </body>

</html>
</code>```

and the CSS file:

```<code>head {
    display: none;
}

body {
    background-color: lightblue;
    display: block;
    margin: 8px;
}

body:focus {
    outline: none;
}

h1 {
    color: white;
    text-align: center;
}

nav {
    display: block;
}

p {
    font-family: verdana;
    font-size: 20px;
}
</code>```

I don't know how the CSS file has to be indicated, because the file .html is in the directory "WebContent"; The CSS file in WebContent/WEB-INF/CSS/NewFile.css; The path I used is "/WEB-INF/CSS/NewFile.css" and still doesn't work.

EDIT:

It seems to work on Chrome and Edge, but neither in Firefox, nor in Eclipse.

答: Try to use the path "/WEB-INF/CSS/NewFile.css", that's to say a relative path from the html file to the css one.</p>

Title: HTML5 file ignore CSS

Body:
I just approached HTML and CSS.

I wrote a little HTML5 file and a CSS file, but my HTML doesn't get any info from CSS because nothing is styled.

I'm using Eclipse, there is a directory "WebContent" where there is the HTML file, and the CSS is in WebContent/WEB_INF/CSS/file.css.

HTML file:

    <link rel="stylesheet" href="/WEB-INF/CSS/NewFile.css" type="text/css">

        <title>Strumenti musicali</title>
        <meta charset="UTF-8">
        <meta name="description" content="Negozio di strumenti musicali">
        <meta name="keywords" content="strumenti, musicali, negozio">
        <meta name="author" content="Paolo">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

            HTML |
            CSS |
            JavaScript |
            jQuery

The title attribute

        Mouse over this paragraph, to display the title attribute as a tooltip.

and the CSS file:

head {
    display: none;
}

body {
    background-color: lightblue;
    display: block;
    margin: 8px;
}

body:focus {
    outline: none;
}

h1 {
    color: white;
    text-align: center;
}

nav {
    display: block;
}

p {
    font-family: verdana;
    font-size: 20px;
}

I don't know how the CSS file has to be indicated, because the file .html is in the directory "WebContent"; The CSS file in WebContent/WEB-INF/CSS/NewFile.css; The path I used is "/WEB-INF/CSS/NewFile.css" and still doesn't work.

EDIT:

It seems to work on Chrome and Edge, but neither in Firefox, nor in Eclipse.


问:
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>```

答:
Your login_class doesn't seem to know about your initialized driver, hence it is NULL.

In your case, make these changes:

In login_class change your constructor to take a driver:

```<code>public login_class(WebDriver webDriver) throws Exception
{
    driver = webDriver;
    ...
}
</code>```

In first_testcase():

```<code>{
    ...
    login_class obj =new login_class(driver);
    ...
}
</code>```

That being said... this is a weird implementation, and I would suggest looking at a few more examples of how others get this set up initially. But if it works for you then that's great :)

For what it's worth, I think the answer provided by @murthi would be sufficient to set the driver properly, and should probably be the accepted answer because it's the simplest way to do what you're asking.

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:
Your login_class doesn't seem to know about your initialized driver, hence it is NULL.

In your case, make these changes:

In login_class change your constructor to take a driver:

public login_class(WebDriver webDriver) throws Exception
{
    driver = webDriver;
    ...
}

In first_testcase():

{
    ...
    login_class obj =new login_class(driver);
    ...
}

That being said... this is a weird implementation, and I would suggest looking at a few more examples of how others get this set up initially. But if it works for you then that's great :)

For what it's worth, I think the answer provided by @murthi would be sufficient to set the driver properly, and should probably be the accepted answer because it's the simplest way to do what you're asking.


问:
How to create button with text and image in bootstrap

Hi Friends,

I am working project in bootstrap. Can anyone please tell me how to create button with text and image as i shown in the image.

Thanks in advance

Regards,
Sathish

答:
You don't need Bootstrap to do this.

Simple example:

.flag {
  border-right: 1px #000 solid;
  padding-right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>
  <span class="flag">flag</span>
  My button
</button></code>```

Create your style with this structure.
span.flag is only a example to your flag image/icon.

Body:
You don't need Bootstrap to do this.

Simple example:

.flag {
  border-right: 1px #000 solid;
  padding-right: 10px;
}

<button>
  <span class="flag">flag</span>
  My button
</button>

Create your style with this structure.
span.flag is only a example to your flag image/icon.


问:
Max, Min, Avg function for an array in C++
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg.  My function must:  process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.</p>

```<code>#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    max = 0;
    min = 0;
    //int amount = size;
    int count = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i=0; i < size; i++)
    {
        count++;
        sum += i;

        if ( i > max)
        {
            i=max;
        }

        else if (i < min)
        {
            i=min;
        }
    }
    avg = sum/count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};

    cout << normalizeMinMaxAvg (data, 4, min, max, avg);
    return 0;
}
</code>```

答:
There are a couple of issues with your code. You need to understand how passing arguments by reference works in C++.

```<code>void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
</code>```

normalizeMinMaxAvg doesn't return anything - note the void return type - it modifies 3 already existing double variables, so if you are going to call it form main you have to define those variables.

```<code>int main()
{
    double data[]={10.0,0.0,20.0,30.0};
    double min = 0, max = 0, avg = 0; //variables defined and initialized here
    //Note the '= 0' on all variables, it's important else they'll have random values
    normalizeMinMaxAvg(data, sizeof(data)/sizeof(data[0]), min, max, avg);

    //Your function has modified min, max, and avg, so you use them here
    std::cout << min << ", " << max << ", " << avg << std::endl;
    return 0;
}
</code>```

Your normalizeMinMaxAvg function also has problems:

```<code>void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
    if (size <= 0) //Nothing to do. Might want to add a return error code
        return;

    //0 is not a sensible value for init, what if all your values are negative?
    min = data[0];
    max = data[0];
    avg = 0;

    int sum = 0;

    for (i=0; i < size; i++)
    {
        sum += data[i];
        if ( data[i] > max) { //have to access your data by data[i]
            max=data[i]; //NOT i=max, you're assigning to max
        }

        if (data[i] < min) {
            min=data[i];
        }
    }
    avg = sum/size;
}
</code>```

Body:
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg.  My function must:  process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.

#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    max = 0;
    min = 0;
    //int amount = size;
    int count = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i=0; i < size; i++)
    {
        count++;
        sum += i;

        if ( i > max)
        {
            i=max;
        }

        else if (i < min)
        {
            i=min;
        }
    }
    avg = sum/count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};

    cout << normalizeMinMaxAvg (data, 4, min, max, avg);
    return 0;
}

Body:
There are a couple of issues with your code. You need to understand how passing arguments by reference works in C++.

void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)

normalizeMinMaxAvg doesn't return anything - note the void return type - it modifies 3 already existing double variables, so if you are going to call it form main you have to define those variables.

int main()
{
    double data[]={10.0,0.0,20.0,30.0};
    double min = 0, max = 0, avg = 0; //variables defined and initialized here
    //Note the '= 0' on all variables, it's important else they'll have random values
    normalizeMinMaxAvg(data, sizeof(data)/sizeof(data[0]), min, max, avg);

    //Your function has modified min, max, and avg, so you use them here
    std::cout << min << ", " << max << ", " << avg << std::endl;
    return 0;
}

Your normalizeMinMaxAvg function also has problems:

void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
    if (size <= 0) //Nothing to do. Might want to add a return error code
        return;

    //0 is not a sensible value for init, what if all your values are negative?
    min = data[0];
    max = data[0];
    avg = 0;

    int sum = 0;

    for (i=0; i < size; i++)
    {
        sum += data[i];
        if ( data[i] > max) { //have to access your data by data[i]
            max=data[i]; //NOT i=max, you're assigning to max
        }

        if (data[i] < min) {
            min=data[i];
        }
    }
    avg = sum/size;
}


问:
iOS 10, Local notification show when app is in foreground?
I want to show notification when app is in forground. Below is the code I did for new usernotificationdelegate method.

In app delegate :

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

        //iOS 10 handling
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
          if (!error) {
                 NSLog(@"request authorization succeeded!");
          } }];
     }
}

#pragma mark - User notification delegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {

    NSLog(@"willPresentNotification");
    NSLog(@"%@", notification.request.content.userInfo);
    completionHandler (UNNotificationPresentationOptionAlert);
}
</code>```

And this is my method to trigger local notification

```<code>-(void) fireLocalNotification:(NSString *) message
{

    NSLog(@"fire Local Notification");
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

        //Notification Content
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.body =  [NSString stringWithFormat:@"%@",message];
        content.sound = [UNNotificationSound defaultSound];

        //Set Badge Number
        content.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

        // Deliver the notification in five seconds.
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                      triggerWithTimeInterval:1.0f repeats:NO];

        //Notification Request
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"LocalNotification" content:content trigger:trigger];

        //schedule localNotification
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
                NSLog(@"add Notification Request succeeded!");
            }
        }];

    }
 }
</code>```

now after doing this still I am not getting notification in forground.

thanks in advance.

答:
For displaying banner message while app is in foreground, use the following method.

Add it to your delegate methods in the AppDelegate and conform to this protocol - UNUserNotificationCenterDelegate

iOS 10, Swift 3:

```<code>@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(UNNotificationPresentationOptions.alert)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to show notification when app is in forground. Below is the code I did for new usernotificationdelegate method.

In app delegate :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

        //iOS 10 handling
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
          if (!error) {
                 NSLog(@"request authorization succeeded!");
          } }];
     }
}

#pragma mark - User notification delegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {

    NSLog(@"willPresentNotification");
    NSLog(@"%@", notification.request.content.userInfo);
    completionHandler (UNNotificationPresentationOptionAlert);
}

And this is my method to trigger local notification

-(void) fireLocalNotification:(NSString *) message
{

    NSLog(@"fire Local Notification");
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {

        //Notification Content
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.body =  [NSString stringWithFormat:@"%@",message];
        content.sound = [UNNotificationSound defaultSound];

        //Set Badge Number
        content.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);

        // Deliver the notification in five seconds.
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                      triggerWithTimeInterval:1.0f repeats:NO];

        //Notification Request
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"LocalNotification" content:content trigger:trigger];

        //schedule localNotification
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
                NSLog(@"add Notification Request succeeded!");
            }
        }];

    }
 }

now after doing this still I am not getting notification in forground.

thanks in advance.

Body:
For displaying banner message while app is in foreground, use the following method.

Add it to your delegate methods in the AppDelegate and conform to this protocol - UNUserNotificationCenterDelegate

iOS 10, Swift 3:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler(UNNotificationPresentationOptions.alert)
}


问:
Read once and then set to nil
I'd like to implement such property, that it's value is available for reading only one time, and then the property should be set to nil.

I've implemented it in such way:

```<code>private var _readOnce: String?

var readOnce: String? {
    get {
        let value = _readOnce
        _readOnce = nil
        return value
        }
    set {
        _readOnce = newValue
    }
}

readOnce = "Andrej"

print("read once = \(readOnce)")  // prints read once = Optional("Andrej")\n"
print("read once = \(readOnce)")  // prints read once = nil\n"
</code>```

But I'feel like using a separate property _readOnce is not the "swifty" / "most elegant" way to do it.

Does anyone know of a different way, that wouldn't require to use a separate property?

I can confirm that the above code works, it's only that I feel it could be more elegant with less lines to achieve the same behaviour.

答:
I don't know that there's a way to avoid having a backing property, but what I'd probably do is to make a helper type to wrap up the behavior. Something like this:

```<code>struct OneTimeValue<T>
{
    private var isUnread = true

    private let value : T

    init(_ value: T)
    {
        self.value = value
    }

    func get() -> T?
    {
        guard isUnread else {
            return nil
        }
        self.isUnread = false
        return self.value
    }
}
</code>```

You could also write this a little differently if you prefer, by nilling out value inside of get(), for example, but the general plan holds.

Then your class becomes:

```<code>class Miser
{
    var readOnce : String?
    {
        return self._readOnce.get()
    }
    private let _readOnce = OneTimeValue("Can't touch this (twice)")
}
</code>```

I've also used this pattern for a UserDefaultsValue (storage to/from user defaults) and a SynchronizedValue (read-write lock on a property) and I think it works well.

Title: Read once and then set to nil

Body:
I'd like to implement such property, that it's value is available for reading only one time, and then the property should be set to nil.

I've implemented it in such way:

private var _readOnce: String?

var readOnce: String? {
    get {
        let value = _readOnce
        _readOnce = nil
        return value
        }
    set {
        _readOnce = newValue
    }
}

readOnce = "Andrej"

print("read once = \(readOnce)")  // prints read once = Optional("Andrej")\n"
print("read once = \(readOnce)")  // prints read once = nil\n"

But I'feel like using a separate property _readOnce is not the "swifty" / "most elegant" way to do it.

Does anyone know of a different way, that wouldn't require to use a separate property?

I can confirm that the above code works, it's only that I feel it could be more elegant with less lines to achieve the same behaviour.

Body:
I don't know that there's a way to avoid having a backing property, but what I'd probably do is to make a helper type to wrap up the behavior. Something like this:

struct OneTimeValue<T>
{
    private var isUnread = true

    private let value : T

    init(_ value: T)
    {
        self.value = value
    }

    func get() -> T?
    {
        guard isUnread else {
            return nil
        }
        self.isUnread = false
        return self.value
    }
}

You could also write this a little differently if you prefer, by nilling out value inside of get(), for example, but the general plan holds.

Then your class becomes:

class Miser
{
    var readOnce : String?
    {
        return self._readOnce.get()
    }
    private let _readOnce = OneTimeValue("Can't touch this (twice)")
}

I've also used this pattern for a UserDefaultsValue (storage to/from user defaults) and a SynchronizedValue (read-write lock on a property) and I think it works well.


问:
what will be the mime type for java application if I want to show both image and html content?
In my java web application i need to show the image that exits in the database as well as a
anchor tag for moving to another jsp page.

In my jsp page it is mentioned response.setContentType("image/jpg;");

So while running the jsp page is shows the image but do not show the html below or anywhere.

What i want that my jsp page should show the image as well as html content at a single jsp page. So please tell what mime type should i use so that to get desire result.

Thank you,

答: Mime types in HTML headers are intended to help browser distinguish between types of binary content transferred from the server. So, if you transfer just HTML, you should specify text/html. You should use image/jpg only if you transfer image binary data to browser using this page.</p>

ContentLicense: CC BY-SA 2.5


问:
Add-in Error: Something went wrong and we couldn't start this add-in.
I am using Create React App to build an add-in for Excel. The add-in works well in the Excel for macOS.

The Repo

However, when I try to load it in Excel Online. After uploading the manifest file and opening the add-in, it shows

Add-in Error: Something went wrong and we couldn't start this add-in. Please try again later or contact your system administrator.

The console shows

Error while parsing the 'sandbox' attribute: 'ms-allow-popups' is an invalid sandbox flag.

I am already using HTTPS in development by HTTPS=true npm start.

What else may cause this? Thanks

答:
It sounds like you're hitting a timeout error. Make sure you're always handling calling Office.initialize() before any other code.

For example, I would call registerServiceWorker() from within your init method. You have a lot of things going on in there and it is firing off at the same time as initialize at the moment.

```<code>Office.initialize = () => {

  registerServiceWorker();
  ReactDOM.render(<App />, document.getElementById('root'));

};
</code>```

Body:
It sounds like you're hitting a timeout error. Make sure you're always handling calling Office.initialize() before any other code.

For example, I would call registerServiceWorker() from within your init method. You have a lot of things going on in there and it is firing off at the same time as initialize at the moment.

Office.initialize = () => {

  registerServiceWorker();
  ReactDOM.render(<App />, document.getElementById('root'));

};


问:
Concatenate variable name in python
I have a set of table names

```1. EOM
2.STMT
3.LOOKUP etc```

I want to associate these table names with some variables names such as

```1. start_time,
2. end_time,
3. total_time etc. ```

The way I want to write these variable names is something like

```1. start_time_EOM, end_time_EOM, total_time_EOM
2. start_time_STMT, end_time_STMT,total_time_STMT
3. start_time_LOOKUP,end_time_LOOKUP,total_time_LOOKUP```

Can this be done in python, and how?
(Note: I am new to Python, and still trying to learn).

答:
Yup, dictionaries are solution:

```<code>tables=["A","B","C"]
vars = ["var1","var2","var3"]
dict={}
for val in tables:
  for val2 in vars:
    dict[val2+"_"+val] = foo
    dict[val2+"_"+val] = bar
    dict[val2+"_"+val] = foobar
#and so
</code>```

Hope if helps

Title: Concatenate variable name in python

Body:
I have a set of table names

1. EOM
2.STMT
3.LOOKUP etc

I want to associate these table names with some variables names such as

1. start_time,
2. end_time,
3. total_time etc.

The way I want to write these variable names is something like

1. start_time_EOM, end_time_EOM, total_time_EOM
2. start_time_STMT, end_time_STMT,total_time_STMT
3. start_time_LOOKUP,end_time_LOOKUP,total_time_LOOKUP

Can this be done in python, and how?
(Note: I am new to Python, and still trying to learn).

Body:
Yup, dictionaries are solution:

tables=["A","B","C"]
vars = ["var1","var2","var3"]
dict={}
for val in tables:
  for val2 in vars:
    dict[val2+"_"+val] = foo
    dict[val2+"_"+val] = bar
    dict[val2+"_"+val] = foobar
#and so

Hope if helps


答:
The path to your CSS file is incorrect. Assure that the relative path and filename match that of your intended CSS file.

In your case the path specified in html file points to "NewFile.css" which does not match "file.css", as Blackbam has mentioned. Other issues exist in the directory names as well. Fixing this will fix your issue.

I would also add that StackOverflow is not intended as a website to debug your issues.

Title: HTML5 file ignore CSS


问:
How do I store total points after user input in Javascript?
I'm coding my first JavaScript create your own adventure game. I have an input field for the user to enter his actions, a button to submit the action and an output text field for the story. When the button is clicked it starts a function to calculate the effectiveness of the user action.

Each action has a certain amount of points (25, 50, 75). If the user reaches 100 points after a few tries, he wins. If he reaches over 100 he loses. As long as 100 points aren't met, the user may keep on trying different actions.

The problem is that the function needs to store the current total points in a global variable, but it doesn't do that. After every button click the check function checks if the 100 points are met and gives hints to the user. But right now, it just says "You did it!" which is what it says when you meet 100 total points. What am I doing wrong?

I'm a total beginner at JavaScript, so I hope my code isn't a complete mess. Any help and advice is welcome. :)

Here is my HTML code:

```<code><form>
<fieldset>
<label>Enter your answer here:</label>
<input id="userInput" type="text" name="userInput">
<input id="submit" type="button" name="submit" value="Click!" onclick="userAction()">
<textarea id="txtOutput" type="text" readonly="readonly" name="txtOutput">
</textarea>
</fieldset>
</code>```

And my Javascript code:

```<code>var userInput = document.getElementById("userInput");
var txtOutput = document.getElementById("txtOutput");

txtOutput.value = "(\This is just a test and not the actual game.\) \n\nChoose your method to convince the merchant: \n\nA. compliment him on his work \nB. bribe him with money \nC. initmidate him \nD. blackmail him";

var totalPoints = 0;

function add(points) {
  totalPoints += points;
}

window.userAction = function() {
  var input = userInput.value.toUpperCase();
  var compliment = "A";
  var bribe = "B";
  var intimidate = "C";
  var blackmail = "D";

    if (input == compliment) {
        add(25);
    }
    else if (input == bribe) {
        add(25);
    }
    else if (input == intimidate) {
        add(50);
    }
    else if (input == blackmail) {
        add(75);
    }
    else {
        txtOutput = "Method not found. Choose either A, B, C or D.";
    }
    check();
}

    window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";
        userAction();
    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
        userAction();
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";
        userAction();
    }
    else if (totalPoints = 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }
}
</code>```

The JSfiddle

答:
Here is a solution

https://jsfiddle.net/exa2k8vq/1/

You had 2 errors:

else if (totalPoints = 100) while you need ==

you called userAction() in your if, so player got point twice

Body:
I'm coding my first JavaScript create your own adventure game. I have an input field for the user to enter his actions, a button to submit the action and an output text field for the story. When the button is clicked it starts a function to calculate the effectiveness of the user action.

Each action has a certain amount of points (25, 50, 75). If the user reaches 100 points after a few tries, he wins. If he reaches over 100 he loses. As long as 100 points aren't met, the user may keep on trying different actions.

The problem is that the function needs to store the current total points in a global variable, but it doesn't do that. After every button click the check function checks if the 100 points are met and gives hints to the user. But right now, it just says "You did it!" which is what it says when you meet 100 total points. What am I doing wrong?

I'm a total beginner at JavaScript, so I hope my code isn't a complete mess. Any help and advice is welcome. :)

Here is my HTML code:

<form>
<fieldset>
Enter your answer here:
<input id="userInput" type="text" name="userInput">
<input id="submit" type="button" name="submit" value="Click!" onclick="userAction()">
<textarea id="txtOutput" type="text" readonly="readonly" name="txtOutput">
</textarea>
</fieldset>

And my Javascript code:

var userInput = document.getElementById("userInput");
var txtOutput = document.getElementById("txtOutput");

txtOutput.value = "(\This is just a test and not the actual game.\) \n\nChoose your method to convince the merchant: \n\nA. compliment him on his work \nB. bribe him with money \nC. initmidate him \nD. blackmail him";

var totalPoints = 0;

function add(points) {
  totalPoints += points;
}

window.userAction = function() {
  var input = userInput.value.toUpperCase();
  var compliment = "A";
  var bribe = "B";
  var intimidate = "C";
  var blackmail = "D";

    if (input == compliment) {
        add(25);
    }
    else if (input == bribe) {
        add(25);
    }
    else if (input == intimidate) {
        add(50);
    }
    else if (input == blackmail) {
        add(75);
    }
    else {
        txtOutput = "Method not found. Choose either A, B, C or D.";
    }
    check();
}

    window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";
        userAction();
    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
        userAction();
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";
        userAction();
    }
    else if (totalPoints = 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }
}

The JSfiddle


问:
How to use Git and Dropbox together?
Is it possible to use Git and Dropbox together?</p>

答:
Without using third-party integration tools, I could enhance the condition a bit and use DropBox and other similar cloud disk services such as SpiderOak with Git.

The goal is to avoid the synchronization in the middle of these files modifications, as it can upload a partial state and will then download it back, completely corrupting your git state.

To avoid this issue, I did:

Bundle my git index in one file using git bundle create my_repo.git --all.

Set a delay for the file monitoring, eg 5 minutes, instead of instantaneous. This reduces the chances DropBox synchronizes a partial state in the middle of a change. It also helps greatly when modifying files on the cloud disk on-the-fly (such as with instantaneous saving note-taking apps).

It's not perfect as there is no guarantee it won't mess up the git state again, but it helps and for the moment I did not get any issue.

Title: How to use Git and Dropbox together?


问:
How could I get django query from one model and add the information from the model ForeignKey to it?
I want to get all Blogs in one query, and at the same time, I want to know each Blog's Entry(or Entries), if the Blog has.

```<code>class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
</code>```

Like access the blog.ENTRY attributes. Here is the way come to mind at first. 1) get all Blogs, 2) set each Blog ENTRY attr with its entries:

```<code>for blog in Blog.objects.all():
    entry = Entry.objects.filter(blog=blog)
    setattr(blog, 'ENTRY', entry)
</code>```

But I want to do this in just one query, because I don't want to do Entry filter query in the for loop.

答:
Code:

```<code>Entry.objects.all().select_related('blog')
</code>```

will fetch all Entry objects and populate it's blog attribute in single quest.

Doing same with Blog model is not possible in single query as relation is one-to-many.

To get better idea of what is possible and what is not, look at recommended in comments topics related to select_related and prefetch_related. Especially second one.

Body:
I want to get all Blogs in one query, and at the same time, I want to know each Blog's Entry(or Entries), if the Blog has.

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)

Like access the blog.ENTRY attributes. Here is the way come to mind at first. 1) get all Blogs, 2) set each Blog ENTRY attr with its entries:

for blog in Blog.objects.all():
    entry = Entry.objects.filter(blog=blog)
    setattr(blog, 'ENTRY', entry)

But I want to do this in just one query, because I don't want to do Entry filter query in the for loop.

Body:
Code:

Entry.objects.all().select_related('blog')

will fetch all Entry objects and populate it's blog attribute in single quest.

Doing same with Blog model is not possible in single query as relation is one-to-many.

To get better idea of what is possible and what is not, look at recommended in comments topics related to select_related and prefetch_related. Especially second one.


答:
Remove your calls to UserAction from within window.check

it is calling the same action multiple times and hence you get you did it on first click

change this

```<code>window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";
        userAction();
    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
        userAction();
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";
        userAction();
    }
    else if (totalPoints == 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }
</code>```

to this

```<code>    window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";

    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";

    }
    else if (totalPoints = 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }
}
</code>```

here is a fiddle https://jsfiddle.net/0mo7peoc/15/

also change this line

else if (totalPoints = 100) {

to this

else if (totalPoints == 100) {

Title: How do I store total points after user input in Javascript?

Body:
Remove your calls to UserAction from within window.check

it is calling the same action multiple times and hence you get you did it on first click

change this

window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";
        userAction();
    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
        userAction();
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";
        userAction();
    }
    else if (totalPoints == 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }

to this

    window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";

    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";

    }
    else if (totalPoints = 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }
}

here is a fiddle https://jsfiddle.net/0mo7peoc/15/

also change this line

else if (totalPoints = 100) {

to this

else if (totalPoints == 100) {


问:
Reading floats from file with python
My input file has the form:

```<code>5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
</code>```

where every number is essentially in a line.

What I want to do is read all the floats, and then append only columns 7 through 10 to an array.

Here's what I've written:

```<code>T=[]
with open("test.txt", "r") as file1:
    for line in file1.readlines():
        f_list = [float(i) for i in line.split(",")]
        T.append(float(f_list[7]))
        T.append(float(f_list[8]))
        T.append(float(f_list[9]))
        T.append(float(f_list[10]))
</code>```

When I run the above I get:

```<code>ValueError: could not convert string to float:
</code>```

I think there's something wrong with the float(i) part, but I can't find a way around it.

I've seen people having similar problems here, but none of the fixes I've tried so far have helped. Any help is greatly appreciated.

答:
No the problem is that your first line ends with a comma:

```<code>5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650
</code>```

As a result, you want to process a string that only contains spaces (like ' '). And float(' ') fails since it is not a number (it actually reports this):

```<code>>>> float(' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
>>> float('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'
</code>```

But a space simply is invisible when printed.

You can solve it by adding a filter statement to the list comprehension:

```<code>T = []
with open("test.txt", "r") as file1:
    for line in file1.readlines():
        f_list = [float(i) for i in line.split(",")<b> if i.strip()</b>]
        T += f_list[7:11]</code>```

Furthermore this will not work since none of the lines has 7-11 floats. So you will never add these floats anyway.

You can however use the following code:

```<code>with open("test.txt", "r") as file1:
    f_list = [float(i) for line in file1 for i in line.split(',') if i.strip()]
    T = f_list[7:11]
</code>```

This will result in T being equal to:

```<code>>>> T
[1.053e-09, 1.839e-09, 1.632e-10, 1.959e-12]
</code>```

Title: Reading floats from file with python

Body:
My input file has the form:

5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650

where every number is essentially in a line.

What I want to do is read all the floats, and then append only columns 7 through 10 to an array.

Here's what I've written:

T=[]
with open("test.txt", "r") as file1:
    for line in file1.readlines():
        f_list = [float(i) for i in line.split(",")]
        T.append(float(f_list[7]))
        T.append(float(f_list[8]))
        T.append(float(f_list[9]))
        T.append(float(f_list[10]))

When I run the above I get:

ValueError: could not convert string to float:

I think there's something wrong with the float(i) part, but I can't find a way around it.

I've seen people having similar problems here, but none of the fixes I've tried so far have helped. Any help is greatly appreciated.

Body:
No the problem is that your first line ends with a comma:

5.0, 1000.0, 100000000000000.0, 115.2712, 230.538, 345.796, 461.0408,
1.053E-09, 1.839E-09, 1.632E-10, 1.959E-12, 4.109, 3.683, 3.586, 3.650

As a result, you want to process a string that only contains spaces (like ' '). And float(' ') fails since it is not a number (it actually reports this):

>>> float(' ')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
>>> float('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'a'

But a space simply is invisible when printed.

You can solve it by adding a filter statement to the list comprehension:

T = []
with open("test.txt", "r") as file1:
    for line in file1.readlines():
        f_list = [float(i) for i in line.split(",") if i.strip()]
        T += f_list[7:11]

Furthermore this will not work since none of the lines has 7-11 floats. So you will never add these floats anyway.

You can however use the following code:

with open("test.txt", "r") as file1:
    f_list = [float(i) for line in file1 for i in line.split(',') if i.strip()]
    T = f_list[7:11]

This will result in T being equal to:

>>> T
[1.053e-09, 1.839e-09, 1.632e-10, 1.959e-12]


问:
Calling same model function with different parameters not returning values
Soooo....long time reader first time poster. For the first time, can't find the answer!

I've got a model that returns an array of results (working). Then I loop through the results with a foreach and append the array with additional values from a second function in my model. Problem is that only the first of my several function calls return any results. The function get_offering_total() only returns the value for the first listed call (cash). This is returning the correct value, but any subsequent attempts to use the same function returns nothing. A var_dump shows that the array is structured correctly on the output, but the values are all null. Is there an issue with calling the same model method with different parameters? Something needs to be cleared/reset?

Here's the code...

//$data['offerings'] stores the results from my first query

foreach( $data['offerings'] as $key => $value ) {

//Set filters

$cash_filter = array( 'method' => '5' );
  $checks_filter = array( 'method' => '6' );

//Get totals

$data['offerings'][$key]['cash'] =
    $this->model_records->get_offering_total( $value['offering_id'], $cash_filter);
  $data['offerings'][$key]['checks'] =
    $this->model_records->get_offering_total( $value['offering_id'], $checks_filter);

...other stuff...
}

Thanks for your help!

答:
Here's a simple test to see if all the code you wrote is correct. Surround everything in your function (in the model) within a try/catch block, and see if it throws any kind of exception. You'd be surprised how many exceptions get thrown but PHP doesn't show them because you have error reporting off in your PHP config. You can do the same for the two lines on which you call the method in your controller and see if they are all good.

PHP Exceptions Reference


问:
Docker LVM plugin install issues
im trying to install docker lvm plugin given in this link and when I execute the make command it throws me the following error.

```<code>pr@pr-ubuntu:~/ba/docker-lvm-plugin$ make
go-md2man -in man/docker-lvm-plugin.8.md -out docker-lvm-plugin.8
/usr/bin/go build -o docker-lvm-plugin .
utils.go:14:2: cannot find package "github.com/docker/docker/pkg/system" in any of:
    /usr/local/go/src/github.com/docker/docker/pkg/system (from $GOROOT)
    /home/pr/programming/go/packages/src/github.com/docker/docker/pkg/system (from $GOPATH)
driver.go:10:2: cannot find package "github.com/docker/go-plugins-helpers/volume" in any of:
    /usr/local/go/src/github.com/docker/go-plugins-helpers/volume (from $GOROOT)
    /home/pr/programming/go/packages/src/github.com/docker/go-plugins-helpers/volume (from $GOPATH)
make: *** [lvm-plugin-build] Error 1
</code>```

I believe its looking for docker go-plugin-helpers, I see those packages here but not sure how to install in my GOPATH.

https://github.com/docker/go-plugins-helpers

答:
If you're trying to build a Go program, you should read the Go documentation, at least the basics. To install a package:</p>

```<code>go get github.com/docker/go-plugins-helpers
</code>```

Title: Docker LVM plugin install issues

Body:
im trying to install docker lvm plugin given in this link and when I execute the make command it throws me the following error.

pr@pr-ubuntu:~/ba/docker-lvm-plugin$ make
go-md2man -in man/docker-lvm-plugin.8.md -out docker-lvm-plugin.8
/usr/bin/go build -o docker-lvm-plugin .
utils.go:14:2: cannot find package "github.com/docker/docker/pkg/system" in any of:
    /usr/local/go/src/github.com/docker/docker/pkg/system (from $GOROOT)
    /home/pr/programming/go/packages/src/github.com/docker/docker/pkg/system (from $GOPATH)
driver.go:10:2: cannot find package "github.com/docker/go-plugins-helpers/volume" in any of:
    /usr/local/go/src/github.com/docker/go-plugins-helpers/volume (from $GOROOT)
    /home/pr/programming/go/packages/src/github.com/docker/go-plugins-helpers/volume (from $GOPATH)
make: *** [lvm-plugin-build] Error 1

I believe its looking for docker go-plugin-helpers, I see those packages here but not sure how to install in my GOPATH.

https://github.com/docker/go-plugins-helpers

Body:
If you're trying to build a Go program, you should read the Go documentation, at least the basics. To install a package:

go get github.com/docker/go-plugins-helpers


问:
Running alembic in a python container that depends upon a mysql container
I have a project in which I use the following docker-compose.yml file:

```<code>version: '3'
services:
    python:
        restart: always
        build: ./budget/dockerfiles/python/
        ports:
            - "5000:5000"
        links:
            - db
        depends_on:
            - db
        volumes:
            - ./budget/:/app:z
        entrypoint:
            - python
            - -u
            - /app/run.py

    db:
        build: ./budget/dockerfiles/mysql/
        environment:
            MYSQL_ROOT_PASSWORD: rainmakers
            MYSQL_DATABASE: forecast
            MYSQL_USER: rain
            MYSQL_PASSWORD: rainmakers
        volumes:
            - ./Dump.sql:/db/Dump.sql:z
            - ./Dump_Test.sql:/db/Dump_Test.sql:z
            - ./big_fc.sql:/db/big_fc.sql:z
        ports:
            - "3306:3306"
</code>```

I also have the following alembi.ini file:

```<code># A generic, single database configuration.

[alembic]
sqlalchemy.url = mysql://username:password@localhost/database_name

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
</code>```

I need to run the command alembic upgrade head inside my Python container, but when I run it I am getting the following error:

```<code>Traceback (most recent call last):
  File "/usr/local/bin/alembic", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/alembic/config.py", line 479, in main
    CommandLine(prog=prog).main(argv=argv)
  File "/usr/local/lib/python2.7/dist-packages/alembic/config.py", line 473, in main
    self.run_cmd(cfg, options)
  File "/usr/local/lib/python2.7/dist-packages/alembic/config.py", line 456, in run_cmd
    **dict((k, getattr(options, k, None)) for k in kwarg)
  File "/usr/local/lib/python2.7/dist-packages/alembic/command.py", line 254, in upgrade
    script.run_env()
  File "/usr/local/lib/python2.7/dist-packages/alembic/script/base.py", line 421, in run_env
    util.load_python_file(self.dir, 'env.py')
  File "/usr/local/lib/python2.7/dist-packages/alembic/util/pyfiles.py", line 93, in load_python_file
    module = load_module_py(module_id, path)
  File "/usr/local/lib/python2.7/dist-packages/alembic/util/compat.py", line 75, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "alembic/env.py", line 70, in <module>
    run_migrations_online()
  File "alembic/env.py", line 58, in run_migrations_online
    with connectable.connect() as connection:
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2085, in connect
    return self._connection_cls(self, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 90, in __init__
    if connection is not None else engine.raw_connection()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2171, in raw_connection
    self.pool.unique_connection, _connection)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2145, in _wrap_pool_connect
    e, dialect, self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1456, in _handle_dbapi_exception_noconnection
    exc_info
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 202, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2141, in _wrap_pool_connect
    return fn()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 328, in unique_connection
    return _ConnectionFairy._checkout(self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 766, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 516, in checkout
    rec = pool._do_get()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 1229, in _do_get
    return self._create_connection()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 333, in _create_connection
    return _ConnectionRecord(self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 461, in __init__
    self.__connect(first_connect_check=True)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 651, in __connect
    connection = pool._invoke_creator(self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/strategies.py", line 105, in connect
    return dialect.connect(*cargs, **cparams)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 385, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 193, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
</code>```

I guess the error is that this command is trying to find mysql inside my python container, but this is not here, so I wonder what I can do to make it run properly.

答:
From the point of view of python container, the mysql IP is resolved with the name of the mysql service: db. Fix the issue as this:

```<code>[alembic]
sqlalchemy.url = mysql://username:password@db/database_name
</code>```

Body:
I have a project in which I use the following docker-compose.yml file:

version: '3'
services:
    python:
        restart: always
        build: ./budget/dockerfiles/python/
        ports:
            - "5000:5000"
        links:
            - db
        depends_on:
            - db
        volumes:
            - ./budget/:/app:z
        entrypoint:
            - python
            - -u
            - /app/run.py

    db:
        build: ./budget/dockerfiles/mysql/
        environment:
            MYSQL_ROOT_PASSWORD: rainmakers
            MYSQL_DATABASE: forecast
            MYSQL_USER: rain
            MYSQL_PASSWORD: rainmakers
        volumes:
            - ./Dump.sql:/db/Dump.sql:z
            - ./Dump_Test.sql:/db/Dump_Test.sql:z
            - ./big_fc.sql:/db/big_fc.sql:z
        ports:
            - "3306:3306"

I also have the following alembi.ini file:

# A generic, single database configuration.

[alembic]
sqlalchemy.url = mysql://username:password@localhost/database_name

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

I need to run the command alembic upgrade head inside my Python container, but when I run it I am getting the following error:

Traceback (most recent call last):
  File "/usr/local/bin/alembic", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/alembic/config.py", line 479, in main
    CommandLine(prog=prog).main(argv=argv)
  File "/usr/local/lib/python2.7/dist-packages/alembic/config.py", line 473, in main
    self.run_cmd(cfg, options)
  File "/usr/local/lib/python2.7/dist-packages/alembic/config.py", line 456, in run_cmd
    **dict((k, getattr(options, k, None)) for k in kwarg)
  File "/usr/local/lib/python2.7/dist-packages/alembic/command.py", line 254, in upgrade
    script.run_env()
  File "/usr/local/lib/python2.7/dist-packages/alembic/script/base.py", line 421, in run_env
    util.load_python_file(self.dir, 'env.py')
  File "/usr/local/lib/python2.7/dist-packages/alembic/util/pyfiles.py", line 93, in load_python_file
    module = load_module_py(module_id, path)
  File "/usr/local/lib/python2.7/dist-packages/alembic/util/compat.py", line 75, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "alembic/env.py", line 70, in <module>
    run_migrations_online()
  File "alembic/env.py", line 58, in run_migrations_online
    with connectable.connect() as connection:
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2085, in connect
    return self._connection_cls(self, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 90, in __init__
    if connection is not None else engine.raw_connection()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2171, in raw_connection
    self.pool.unique_connection, _connection)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2145, in _wrap_pool_connect
    e, dialect, self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1456, in _handle_dbapi_exception_noconnection
    exc_info
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 202, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 2141, in _wrap_pool_connect
    return fn()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 328, in unique_connection
    return _ConnectionFairy._checkout(self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 766, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 516, in checkout
    rec = pool._do_get()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 1229, in _do_get
    return self._create_connection()
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 333, in _create_connection
    return _ConnectionRecord(self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 461, in __init__
    self.__connect(first_connect_check=True)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/pool.py", line 651, in __connect
    connection = pool._invoke_creator(self)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/strategies.py", line 105, in connect
    return dialect.connect(*cargs, **cparams)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 385, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 193, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")

I guess the error is that this command is trying to find mysql inside my python container, but this is not here, so I wonder what I can do to make it run properly.

Body:
From the point of view of python container, the mysql IP is resolved with the name of the mysql service: db. Fix the issue as this:

[alembic]
sqlalchemy.url = mysql://username:password@db/database_name


问:
Microservices, Dependencies and Events
I’ve been doing a lot of googling regarding managing dependencies between microservices. We’re trying to move away from big monolithic app into micro-services in order to scale organizationally and be able to develop faster and with multiple teams working in parallel.
However, as we’re trying to functionally partition the monolith into the microservices, we see how intertwined business logic and data really is. This was not a problem when we were sitting on top of one big DB and were able to do big relational joins. But with microservices, this becomes a problem.

One solution is to make microservice-A go to 5-10 other microservices to get necessary data (this is equivalent of DB view with join). Another solution is to make microservice-A listen to events from 5-10 other services and populate local storage with relevant into (this is an equivalent of materialized view). Either way, microservice-A is coupled with 5-10 other services, and if new info is needed in microservice-A, the some of the services that it depends upon might will need to be release prior to microservice-A. Please note that microservice-A is itself depended upon by other services. Bottom line, we end up with DISTRIBUTED dependency hell.

Many articles advocate for second solution – i.e. something along the lines of Event Sourcing, Choreography, etc.

I would appreciate any shared experiences, recommendations and insights.

Philometor.

答:
While not technically an "answer", I can definitely share some of my observations and experiences. Your question concerning services calling other services for database operations reminded me of a project where an architect sold senior management on the idea of "decoupling" persistence from the rest of the applications by implementing hundreds of REST interfaces in what essentially was a distributed DAO pattern in front of a very large enterprise database.  The project ended up exactly the way I predicted - a dismal failure.

Microservices aren't about turning a monolithic application into a distributed monolithic application.  In my example project above, the monolith was turned into a stove-piped, fragile, chaotic mess, with the coupling only moved to service contracts instead of Java class method signatures, and with a performance hit so bad the application was unusable. Last I heard they are still running their original monolith.

Microservices should be more of a vertical partitioning of your application and not a horizontal one.  In my opinion it's better to think in terms of business function partitioning rather than "converting" an existing monolith. There's no rule that determines how big a microservice must be, but it should be big enough to do one complete synchronous function without needing to directly depend on outside services (as much as possible) to complete its work. If a microservice performs a complex business function that affects 50 tables, so be it!  It owns those many tables.  Ideally if a service goes down, it should affect only that business functionality it's responsible for, and not directly affect other services.  As you can see, this thinking is the complete opposite from that which produced the distributed mess in my project example.

Not only do you need to ensure that the motivation behind replacing monoliths with microservices is sound, but also you need to step outside the monolith and revisit the actual business and begin partitioning that instead.  Like everything else, baby steps are the way to go.  Start with one small complete business function, and convert that into a single microservice instead of trying to replace a monolith all at once.

Title: Microservices, Dependencies and Events


问:
Error in WooCommerce USPS Shipping Plugin
I am getting following error in WooCommerce USPS Shipping Plugin:"

```<code>USPS REQUEST FAILEDcURL error 5: Could not resolve proxy: http_proxy
</code>```

Can someone please help with on how to resolve this?

I googled it but could not find anything related.

答:
In cURL documentation the code 5 means that a proxy server cannot be resolved (it cannot be reached in a DNS query):

CURLE_COULDNT_RESOLVE_PROXY (5)

Couldn't resolve proxy. The given proxy host could not be resolved.

The WF_Shipping_USPS class in the plugin source uses wp_remote_post() to communicate with the USPS API. I think you have something wrong in configuration for proxy and/or have the "http_proxy" defined as string in some config file or even at the environment vars in Linux.

You can check wp-config.php for the lines (just a sample config, you data may be different):

```<code>/* Configure proxy Server */
define('WP_PROXY_HOST', 'www-cache.leeds.ac.uk');
define('WP_PROXY_PORT', '3128');
define('WP_PROXY_USERNAME', '');
define('WP_PROXY_PASSWORD', '');
define('WP_PROXY_BYPASS_HOSTS', 'localhost');
</code>```

If your server is linux, you can try:

```<code>echo $HTTP_PROXY
</code>```

And see if there are something here that is wrong.

To me somewhere you have the string "http_proxy" configured as a proxy host. If you have a proxy correct this by putting the right config. If you do not have a proxy, remove this string and try to disable proxy usage for Wordpress.

Body:
I am getting following error in WooCommerce USPS Shipping Plugin:"

USPS REQUEST FAILEDcURL error 5: Could not resolve proxy: http_proxy

Can someone please help with on how to resolve this?

I googled it but could not find anything related.

Body:
In cURL documentation the code 5 means that a proxy server cannot be resolved (it cannot be reached in a DNS query):

CURLE_COULDNT_RESOLVE_PROXY (5)

Couldn't resolve proxy. The given proxy host could not be resolved.

The WF_Shipping_USPS class in the plugin source uses wp_remote_post() to communicate with the USPS API. I think you have something wrong in configuration for proxy and/or have the "http_proxy" defined as string in some config file or even at the environment vars in Linux.

You can check wp-config.php for the lines (just a sample config, you data may be different):

/* Configure proxy Server */
define('WP_PROXY_HOST', 'www-cache.leeds.ac.uk');
define('WP_PROXY_PORT', '3128');
define('WP_PROXY_USERNAME', '');
define('WP_PROXY_PASSWORD', '');
define('WP_PROXY_BYPASS_HOSTS', 'localhost');

If your server is linux, you can try:

echo $HTTP_PROXY

And see if there are something here that is wrong.

To me somewhere you have the string "http_proxy" configured as a proxy host. If you have a proxy correct this by putting the right config. If you do not have a proxy, remove this string and try to disable proxy usage for Wordpress.


问:
Using mod operator in JavaScript to wrap around
I am building a Texas Hold'em Poker web application using ReactJS. In order to keep track of the dealer button, I am using the following formula...

```<code>let currentPlayers = [
    {name: "Foo", position: 1},
    {name: "Bar", position: 2},
    {name: "Baz", position: 3}
]
let dealerButtonPos = 1

dealerButtonPos = ((dealerButtonPos + currentPlayers.length ) % currentPlayers.length + 1 )
</code>```

What I am trying to do here is make sure that the dealer button starts at position 1 and is always on the correct position at the start of every round. The dealer button, in this case, should always fall on position 1, then 2, then 3, then 1 again.

The function with the formula will be called at the end of every round. This should rotate the dealer button correctly for up to 8 players.
Will I always be on the correct player position? Am I implementing this correctly? I had a hard time conceptualizing and getting to this point. Can someone explain the mod operator for clarity?

答:
Be nice for iterator pattern

let currentPlayers = [
    {name: "Foo", position: 1},
    {name: "Bar", position: 2},
    {name: "Baz", position: 3}
]

function* currentPlayersIterator(players) {
  let index = 0;
  while(true)
    if (index < players.length) {
      yield players[index++]
    } else {
      index = 0
      yield players[index++]
    }
}

let i = currentPlayersIterator(currentPlayers)

console.log(i.next().value)
console.log(i.next().value)
console.log(i.next().value)
console.log(i.next().value)
console.log(i.next().value)```

Body:
I am building a Texas Hold'em Poker web application using ReactJS. In order to keep track of the dealer button, I am using the following formula...

let currentPlayers = [
    {name: "Foo", position: 1},
    {name: "Bar", position: 2},
    {name: "Baz", position: 3}
]
let dealerButtonPos = 1

dealerButtonPos = ((dealerButtonPos + currentPlayers.length ) % currentPlayers.length + 1 )

What I am trying to do here is make sure that the dealer button starts at position 1 and is always on the correct position at the start of every round. The dealer button, in this case, should always fall on position 1, then 2, then 3, then 1 again.

The function with the formula will be called at the end of every round. This should rotate the dealer button correctly for up to 8 players.
Will I always be on the correct player position? Am I implementing this correctly? I had a hard time conceptualizing and getting to this point. Can someone explain the mod operator for clarity?


答:
Only wrong condition is totalPoints = 100 change it to totalPoints == 100. But the actual reason you are getting this behavior is your check method. In each of your condition, you are calling userAction method again and again. This is why you reach to the conclusion at once.

I have made the adjustment to your fiddle to fix this issue. See updated fiddle UPDATED FIDDLE

Update your check method to

```<code>window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";
    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";
    }
    else if (totalPoints == 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }
</code>```

Note: I have removed calls to your userAction method from this method.

Body:
Only wrong condition is totalPoints = 100 change it to totalPoints == 100. But the actual reason you are getting this behavior is your check method. In each of your condition, you are calling userAction method again and again. This is why you reach to the conclusion at once.

I have made the adjustment to your fiddle to fix this issue. See updated fiddle UPDATED FIDDLE

Update your check method to

window.check = function() {
    if (totalPoints <= 25) {
        txtOutput.value = "You have his attention. Keep going.";
    }
    else if (totalPoints <= 50) {
        txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
    }
    else if (totalPoints <= 75) {
        txtOutput.value = "You almost convinced him. Be careful now!";
    }
    else if (totalPoints == 100) {
        txtOutput.value = "You did it!";
    }
    else if (totalPoints > 100) {
        txtOutput.value = "You pushed it too hard. The merchant runs away!";
    }
    else {
        txtOutput.value = "input not found.";
    }

Note: I have removed calls to your userAction method from this method.


问:
what is the role of ob_start() in here
```<code>session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {
    $hasDB = true;
    mysql_select_db($db);
}
</code>```

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..

答:
Some PHP programmers put ob_start() on the first line of all of their code*, and I'm pretty certain that's what going on here.

It means if they get halfway through outputting the page and decide there's an error, they can clear the buffer and output an error page instead. It also means you never get "couldn't sent headers, output already started" errors when trying to send HTTP headers.

There are a few legitimate reasons to do this, but I'd take it as a sign that they are mediocre programmers who don't want to structure their code in a coherent order - i.e. they should be working out if there are errors or headers to send before they start rendering the page. Don't copy this habit.

(* What makes this an easy habit to fall into is that if output buffering is still turned on when the script end is reached, the buffer is sent to the user, so they don't need to worry about a matching end statement)

Title: what is the role of ob_start() in here

Body:
session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {
    $hasDB = true;
    mysql_select_db($db);
}

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..