问:
css-grids, max-height on Chrome not working?
I want to build a Website Applikation with a fixed Size.

Only a content div should be scrollable.

On FireFox my App worked correctly, but on Chrome i get a strange behaviour and i cannot figure out why?

I extract the problem in a small example as follows.

```<code><!DOCTYPE html>
<html>
<head>
    <title>App</title>
    <style>
        html, body
        {
            left: 0;
            top: 0;
            margin: 0;
            width: 100vw;
            height: 100vh;
        }

        .app
        {
            height : 100vh;
            width : 100vw;
            /*overflow: hidden;*/
            display: grid;
            grid-template-rows: 100px auto;
        }

        .content
        {
            display: grid;
            grid-template-columns: 500px auto;
            height: 100%;
            max-height: 100%;
        }

        .scrollable
        {
            overflow: auto;
            max-height: 100%;
        }

        .red
        {
            background-color: red;
        }

        .yellow
        {
            background-color: yellow;
        }

        .blue
        {
          background-color: blue;
        }
    </style>
</head>

<body>
  <div class="app">
    <div class="yellow"></div>
    <div class="content">
      <div class="red scrollable">
        some content <br />
        some content <br />
        .
        .
        .
        some content <br />
        some content <br />
      </div>

      <div class="blue scrollable"></div>
    </div>
  </div>
</body>

</html>
</code>```

in firefox just the red div got a scrollbar, but in chrome the whole page get one. Why they behave differently and how can i fix this in chrome?

答:
Try this. It works fine in both firefox and chrome.

```<code> <!DOCTYPE html>
<html>
<head>
<title>App</title>
    <style>
   html, body
            {
                left: 0;
                top: 0;
                margin: 0;
                width: 100vw;
                height: 100vh;
            }

            .app
            {
                height : 100vh;
                width : 100vw;
                overflow: hidden;
                display: grid;
                grid-template-rows: 100px auto;
            }

            .content
            {
                display: grid;
                grid-template-columns: 500px auto;
                height: 90vh;
            }

            .scrollable
            {
                overflow: auto;
                max-height: 100%;
            }

            .red
            {
                background-color: red;
            }

            .yellow
            {
                height:10vh;
                background-color: yellow;
            }

            .blue
            {
              background-color: blue;
            }
    </style>
</head>

<body>
  <div class="app">
    <div class="yellow"></div>
    <div class="content">
      <div class="red scrollable">
        some content <br />
        some content <br />
        .
        .
        .
        some content <br />
        some content <br />
      </div>

      <div class="blue scrollable"></div>
    </div>
  </div>
</body>

</html>
</code>```

note : setting height&width dynamically using javascript will be better

Body:
I want to build a Website Applikation with a fixed Size.

Only a content div should be scrollable.

On FireFox my App worked correctly, but on Chrome i get a strange behaviour and i cannot figure out why?

I extract the problem in a small example as follows.

<!DOCTYPE html>

    <title>App</title>

        some content

        some content

        .
        .
        .
        some content

        some content

in firefox just the red div got a scrollbar, but in chrome the whole page get one. Why they behave differently and how can i fix this in chrome?

Body:
Try this. It works fine in both firefox and chrome.

 <!DOCTYPE html>
<html>
<head>
<title>App</title>
    <style>
   html, body
            {
                left: 0;
                top: 0;
                margin: 0;
                width: 100vw;
                height: 100vh;
            }

            .app
            {
                height : 100vh;
                width : 100vw;
                overflow: hidden;
                display: grid;
                grid-template-rows: 100px auto;
            }

            .content
            {
                display: grid;
                grid-template-columns: 500px auto;
                height: 90vh;
            }

            .scrollable
            {
                overflow: auto;
                max-height: 100%;
            }

            .red
            {
                background-color: red;
            }

            .yellow
            {
                height:10vh;
                background-color: yellow;
            }

            .blue
            {
              background-color: blue;
            }
    </style>
</head>

<body>
  <div class="app">
    <div class="yellow"></div>
    <div class="content">
      <div class="red scrollable">
        some content <br />
        some content <br />
        .
        .
        .
        some content <br />
        some content <br />
      </div>

      <div class="blue scrollable"></div>
    </div>
  </div>
</body>

</html>

note : setting height&width dynamically using javascript will be better


来源: stackexchange

问:
Hidden Features of JavaScript?
What "Hidden Features" of JavaScript do you think every programmer should know?

After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.

Hidden Features of HTML

Hidden Features of CSS

Hidden Features of PHP

Hidden Features of ASP.NET

Hidden Features of C#

Hidden Features of Java

Hidden Features of Python

Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.

答:
There is also an almost unknown JavaScript syntax:

```<code>var a;
a=alert(5),7;
alert(a);    // alerts undefined
a=7,alert(5);
alert(a);    // alerts 7

a=(3,6);
alert(a);    // alerts 6
</code>```

More about this here.

OwnerDisplayName: allain

ContentLicense: CC BY-SA 2.5

Title: Hidden Features of JavaScript?

LastEditorDisplayName: marxidad

Body:
There is also an almost unknown JavaScript syntax:

var a;
a=alert(5),7;
alert(a);    // alerts undefined
a=7,alert(5);
alert(a);    // alerts 7

a=(3,6);
alert(a);    // alerts 6

More about this here.


问:
Quick successful exit from C++ with lots of objects allocated
I'm looking for a way to quickly exit a C++ that has allocated a lot of structures in memory using C++ classes.  The program finishes correctly, but after the final "return" in the program, all of the auto-destructors kick in.  The problem is the program has allocated about 15GB of memory through lots of C++ class structures, and this auto-destruct process takes about 1 more hour itself to complete as it walks through all of the structures - even though I don't care about the results.  The program only took 1 hour to complete the task up to this point.  I would like to just return to the OS and let it do its normal wholesale process allocation deletion - which is very quick.  I've been doing this by manually killing the process during the cleanup stage - but am looking for a better programic solution.

I would like to return a success to the OS, but don't care to keep any of the memory content.  The program does perform a lot of dynamic allocation/deallocation during the normal processing, so it's not just simple heap management.

Any opinions?

答:
If you have a C99 compiler, you can use the _Exit function to end immediately without having global object destructors or any functions registered with atexit to be called; whether or not unwritten buffered file data is flushed, open streams are closed, or temporary files are removed is implementation-defined (C99 §7.20.4.4).

If you're on Windows, you can also use ExitProcess to achieve the same effect.

But, as others have said, your destructors should really not be taking an hour to run unless you're doing a fair amount of I/O (writing log files, etc.).  I strongly, strongly recommend you profile your program to see where the time is spent.


问:
How to redirect in redux after registration?
I have created a signup form in react redux and it works as expected. The problem is that I have tried to push / in hash route to redirect user to dashboard, but it gives an error. I even used router in context as below:

```<code>if (this.isValid()) {
      // dispatching request for user sing up
      this.props.userSignupRequest(this.state)
          .then(response => {
              this.setState({isLoading: false});
              this.context.router.replaceWith('/');
          })
          .catch(error => {
              this.setState({errors: error.response.data, isLoading: false});
          });
  }
</code>```

In the Register component file that I have written the above code, I have the below code as well (outside of component class):

```<code>Register.contextTypes = {
    router: PropTypes.object.isRequired
};
</code>```

This does not give any error. How should I implement the redirect? It seems that react-router behaves differently in newer version.

Version: "react-redux": "^5.0.6"

答:
I think, you should use one of the way below:

1) Use react-router-redux - https://github.com/reacttraining/react-router/tree/master/packages/react-router-redux and you can create action and inside action you can use

```<code>import {push} from 'react-router-redux'

const goTo = (dispatch) => {
  dispatch(push('/'));
}
</code>```

2) You can use  component to redirect to some url:

```<code>  load(){
    if (this.isValid()) {
      // dispatching request for user sing up
      this.props.userSignupRequest(this.state)
          .then(response => {
              this.setState({isLoading: false, goTo: '/'});
          })
    }
  }

  render(){
    const {isLoading, goTo} = this.state;

    return goTo? <Redirect to={goTo} /> : (
       <div>Component</div>
    )
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a signup form in react redux and it works as expected. The problem is that I have tried to push / in hash route to redirect user to dashboard, but it gives an error. I even used router in context as below:

if (this.isValid()) {
      // dispatching request for user sing up
      this.props.userSignupRequest(this.state)
          .then(response => {
              this.setState({isLoading: false});
              this.context.router.replaceWith('/');
          })
          .catch(error => {
              this.setState({errors: error.response.data, isLoading: false});
          });
  }

In the Register component file that I have written the above code, I have the below code as well (outside of component class):

Register.contextTypes = {
    router: PropTypes.object.isRequired
};

This does not give any error. How should I implement the redirect? It seems that react-router behaves differently in newer version.

Version: "react-redux": "^5.0.6"

Body:
I think, you should use one of the way below:

1) Use react-router-redux - https://github.com/reacttraining/react-router/tree/master/packages/react-router-redux and you can create action and inside action you can use

import {push} from 'react-router-redux'

const goTo = (dispatch) => {
  dispatch(push('/'));
}

2) You can use  component to redirect to some url:

  load(){
    if (this.isValid()) {
      // dispatching request for user sing up
      this.props.userSignupRequest(this.state)
          .then(response => {
              this.setState({isLoading: false, goTo: '/'});
          })
    }
  }

  render(){
    const {isLoading, goTo} = this.state;

    return goTo? <Redirect to={goTo} /> : (
       <div>Component</div>
    )
  }


问:
How to use Ng2-translate into *NgFor
i need to translate the Data that i get in NgFor but i couldn't find any solution for it.

can any 1 find solution for this

```<code><dl class="row">
    <dd class="col-sm-3" (click)="onSelect(brand)" *ngFor="let brand of searchData">
        <div style="text-align:center">{{brand.name}}</div>
        <br>
    </dd>
</dl>
</code>```

how can i use | translate @pipe inside this NgFor

答:
GOT THE SOLUTION THIS IS WORKING FINE     </p>

```<code>    <dl> <dd>
    <div class="col-md-3" (click)="onSelect(brand)" *ngFor="let brand of searchData">
 <br>{{'HOME.'+brand.name | translate}}
     <br></div>
    </dd> </dl>
</code>```

Title: How to use Ng2-translate into *NgFor

Body:
i need to translate the Data that i get in NgFor but i couldn't find any solution for it.

can any 1 find solution for this

{{brand.name}}

how can i use | translate @pipe inside this NgFor

Body:
GOT THE SOLUTION THIS IS WORKING FINE

    <dl> <dd>
    <div class="col-md-3" (click)="onSelect(brand)" *ngFor="let brand of searchData">
 <br>{{'HOME.'+brand.name | translate}}
     <br></div>
    </dd> </dl>


问:
How can I make variables accessible to all the functions within the class in php
I want my variables to be accessible to all the functions within the class in php.
I am giving a sample code of what Im trying to achieve. Please help me out.

```<code>class ClassName extends AnotherClass {

    function __construct(argument)
    {

    }

    $name = $this->getName();
    $city = $this->getCity();
    $age = 24;

    public function getName() {
        return 'foo';
    }

    public function getCity() {
        return 'kolkata';
    }

    public function fun1() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun2() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun3() {
        echo $name;
        echo $city;
        echo $age;
    }
}
</code>```

Or if there is any other way to have least overhead .Please suggest

答:
You can acheave you goal like this :</p>

```<code>class ClassName extends AnotherClass {

    private $name;
    private $city;
    private $age;

    function __construct(argument)
    {
        $this->name = $this->getName();
        $this->city = $this->getCity();
        $this->age = 24;
    }

    public function getName(){
        return 'foo';
    }
    public function getCity(){
        return 'kolkata';
    }

    public function fun1(){
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
    public function fun2(){
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
    public function fun3(){
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
}
</code>```

Body:
I want my variables to be accessible to all the functions within the class in php.
I am giving a sample code of what Im trying to achieve. Please help me out.

class ClassName extends AnotherClass {

    function __construct(argument)
    {

    }

    $name = $this->getName();
    $city = $this->getCity();
    $age = 24;

    public function getName() {
        return 'foo';
    }

    public function getCity() {
        return 'kolkata';
    }

    public function fun1() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun2() {
        echo $name;
        echo $city;
        echo $age;
    }

    public function fun3() {
        echo $name;
        echo $city;
        echo $age;
    }
}

Or if there is any other way to have least overhead .Please suggest

Body:
You can acheave you goal like this :

class ClassName extends AnotherClass {

    private $name;
    private $city;
    private $age;

    function __construct(argument)
    {
        $this->name = $this->getName();
        $this->city = $this->getCity();
        $this->age = 24;
    }

    public function getName(){
        return 'foo';
    }
    public function getCity(){
        return 'kolkata';
    }

    public function fun1(){
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
    public function fun2(){
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
    public function fun3(){
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
}


问:
How to enable or disable geolocation by selenium test case
I want to allow/block my current location accessible to site by clicking on allow button of that popUp, my chrome version is 62.0, chrome driver version is 3.6.0 and I am using ubuntu 16.04 and my code snippet is,

```<code>ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
options.addArguments("start-maximized");
options.addArguments("--disable-geolocation");
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY,options);
driver = new ChromeDriver(capabilities);
</code>```

But this is not working, could anyone suggest me the perfect solution for this?

答:
```<code>Robot r = new Robot();
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
</code>```

Use java.awt.Robot class for this, first test manually and then you can change the key handlers as needed.

Body:
I want to allow/block my current location accessible to site by clicking on allow button of that popUp, my chrome version is 62.0, chrome driver version is 3.6.0 and I am using ubuntu 16.04 and my code snippet is,

ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
options.addArguments("start-maximized");
options.addArguments("--disable-geolocation");
DesiredCapabilities capabilities=DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY,options);
driver = new ChromeDriver(capabilities);

But this is not working, could anyone suggest me the perfect solution for this?

Body:
Robot r = new Robot();
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyPress(KeyEvent.VK_TAB);
r.keyRelease(KeyEvent.VK_TAB);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

Use java.awt.Robot class for this, first test manually and then you can change the key handlers as needed.


问:
Automatic interactions with web pages
I need to retrive information from a web page which accept only a form as an input.

I usually use HttpClient to retrieve info and parse the html, but this page take a Javascript rather than an explicit url as argument, and print input again as a javascript.

I tried HTMLUnit but is painfully slow, especially on Android. Moreover it seems like I can't make it works correctly, as I'm not able to retrive the html after filling the form, maybe due to the page being a javascrpit (see attached code).

How can I retrive information from this web page in Android?

Cheers :D

```<code>package com.htmlUnitTest;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class HtmlUnitTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {

            submittingForm();

        } catch (Exception e) {

            System.out.println("Something bad happened");

            e.printStackTrace();
        }

    }

    static public void submittingForm() throws Exception {
        final WebClient webClient = new WebClient();

        // Get the first page
        final HtmlPage page1 = webClient.getPage(
                  "http://mobile.viaggiatreno.it/viaggiatreno/mobile/stazione?lang=IT");

        System.out.println(page1.getForms());

        // Get the form that we are dealing with and within that form,
        // find the submit button and the field that we want to change.
        final HtmlForm form = page1.getForms().get(0);

        final HtmlSubmitInput button = form.getInputByValue(" Cerca ");
        final HtmlTextInput textField = form.getInputByName("stazione");

        // Change the value of the text field
        textField.setValueAttribute("Milano Centrale");

        // Now submit the form by clicking the button and get back the second page.
        final HtmlPage page2 = button.click();

        System.out.println(page2.getAnchors());

        webClient.closeAllWindows();
    }

}
</code>```

答: You need to POST to /viaggiatreno/mobile/stazione, parse the answer, then post again if you want to drill down. More info about posting here:  google.com/search?q=webClient+post </p>

Title: Automatic interactions with web pages

Body:
I need to retrive information from a web page which accept only a form as an input.

I usually use HttpClient to retrieve info and parse the html, but this page take a Javascript rather than an explicit url as argument, and print input again as a javascript.

I tried HTMLUnit but is painfully slow, especially on Android. Moreover it seems like I can't make it works correctly, as I'm not able to retrive the html after filling the form, maybe due to the page being a javascrpit (see attached code).

How can I retrive information from this web page in Android?

Cheers :D

package com.htmlUnitTest;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class HtmlUnitTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {

            submittingForm();

        } catch (Exception e) {

            System.out.println("Something bad happened");

            e.printStackTrace();
        }

    }

    static public void submittingForm() throws Exception {
        final WebClient webClient = new WebClient();

        // Get the first page
        final HtmlPage page1 = webClient.getPage(
                  "http://mobile.viaggiatreno.it/viaggiatreno/mobile/stazione?lang=IT");

        System.out.println(page1.getForms());

        // Get the form that we are dealing with and within that form,
        // find the submit button and the field that we want to change.
        final HtmlForm form = page1.getForms().get(0);

        final HtmlSubmitInput button = form.getInputByValue(" Cerca ");
        final HtmlTextInput textField = form.getInputByName("stazione");

        // Change the value of the text field
        textField.setValueAttribute("Milano Centrale");

        // Now submit the form by clicking the button and get back the second page.
        final HtmlPage page2 = button.click();

        System.out.println(page2.getAnchors());

        webClient.closeAllWindows();
    }

}


问:
python 3 code quality testing - improper function usage detection
Is there a way to automatically (script) test if someone implemented a function with something that they were not allowed to use or if they used something stupid...

Example A -- check values of a with range(len()):

Bad: idx in range(len(a)) followed by a[idx]

  Ok: i, v in enumerate(a)

Example B -- use int() when you are not allowed:

Bad: int('1')

  Ok: a = ord('1')-ord('0')

答: You could use the keyword "assert" to avoid a certain behaviour, or even if you expected a different value. Actually your question is not that clear. Another idea would be try/except statment.</p>


问:
Values in multiple columns and rows and mark as "X"
I have a table in worksheet 1 which contains values in 2 columns (E & F). In worksheet 2 I need to indicate on a table with an "X" if my values are found.

The Logic:

IF B7 (Sheet 2) EXISTS in column F:F (Sheet 1) AND

IF C5 (Sheet 2) EXISTS in column E:E (Sheet 1)

Where both (B7 & C5) EXISTS on same ROW (Sheet 1)

Mark the current cell (C7) (Sheet 2) as "X" if not blank " ".

I can't seem to solve this with the current function please help.

```<code>=IF(AND(ISNUMBER(SEARCH($C$5, Sheet1!E:E)), (ISNUMBER(SEARCH($B7, Sheet1!F:F)))), "X", "")
</code>```

I can't seem to solve how I can this to be marked as "X".

In the images i want to be able to mark in Sheet 2 "x" where Value 1 and Value 2 exist on the same row on sheet 2 (row 5 in columns E & F)

Both C7 & C9 should have an “X” in the following example.

Sheet 1

Sheet 2

答:
You need to use COUNTIFS rather than SEARCH. SEARCH is for finding the position of a match for a substring (like "alu") in a string (like "Value"). Although it can be used with a list of strings in an array formula, this is not the easiest way to do it. COUNTIFS finds the number of matches for one or more conditions in the same row in one or more ranges which is what you want to do here. The formula is

```<code>=IF(COUNTIFS(Sheet1!E:E,$C$5,Sheet1!F:F,$B7),"x","")
</code>```

If you wanted to find matches for Value 1.1 and Value 1.2 as well as Value 1, you could use a wildcard

```<code>=IF(COUNTIFS(Sheet1!E:E,$C$5&"*",Sheet1!F:F,$B7),"x","")
</code>```

Body:
I have a table in worksheet 1 which contains values in 2 columns (E & F). In worksheet 2 I need to indicate on a table with an "X" if my values are found.

The Logic:

IF B7 (Sheet 2) EXISTS in column F:F (Sheet 1) AND

IF C5 (Sheet 2) EXISTS in column E:E (Sheet 1)

Where both (B7 & C5) EXISTS on same ROW (Sheet 1)

Mark the current cell (C7) (Sheet 2) as "X" if not blank " ".

I can't seem to solve this with the current function please help.

=IF(AND(ISNUMBER(SEARCH($C$5, Sheet1!E:E)), (ISNUMBER(SEARCH($B7, Sheet1!F:F)))), "X", "")

I can't seem to solve how I can this to be marked as "X".

In the images i want to be able to mark in Sheet 2 "x" where Value 1 and Value 2 exist on the same row on sheet 2 (row 5 in columns E & F)

Both C7 & C9 should have an “X” in the following example.

Sheet 1

Sheet 2

Body:
You need to use COUNTIFS rather than SEARCH. SEARCH is for finding the position of a match for a substring (like "alu") in a string (like "Value"). Although it can be used with a list of strings in an array formula, this is not the easiest way to do it. COUNTIFS finds the number of matches for one or more conditions in the same row in one or more ranges which is what you want to do here. The formula is

=IF(COUNTIFS(Sheet1!E:E,$C$5,Sheet1!F:F,$B7),"x","")

If you wanted to find matches for Value 1.1 and Value 1.2 as well as Value 1, you could use a wildcard

=IF(COUNTIFS(Sheet1!E:E,$C$5&"*",Sheet1!F:F,$B7),"x","")


问:
How to add a class that does controls on an entire table?
in our project we have an SQL Database with a table representing all users

```<code>CREATE TABLE `user_table` (
`firstname` varchar(20) NOT NULL,
  `lastName` varchar(20) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(24) NOT NULL,
  `accessToken` varchar(64) NOT NULL,
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
)
</code>```

and we have a class UserDAO. We need to add methods such as

```<code>public boolean areUserCredentialsValid(String email, String password) {...}
public boolean isAccessTokenValid(String accessToken) {...}
public boolean isEmailInUse(String email) {...}
</code>```

I think the names are pretty self-explicative: we want to perform operations on the entire table in order to return boolean values, so we thought it may not be correct to add these methods in UserDAO, as they do not perform CRUD operations on a single User, instead they perform R-only operations on the entire User Table, so we were thinking about a new class AllUsersDAO but it does not seem convincing. What is the best solution here and why?

I don't know if we are overthinking this, but this is a project for an University course and we are evaluated especially for our software engineering abilities, so we want to be sure to adopt the best solution.

Thank you all in advance!

答:
Based on the method signature that you have given i can see that you are passing one email id or email/password or token at a time hence you can define these methods in your service class and you can use this service method for each user.say a UserService class which accepts these credentials then you can use the dao method to query for an object with these credentials if it returns an object you can return true if it returns null you can return false.</p>

```<code>public class UserServiceImpl
{
    public boolean isEmailInUse(String email) {
    User user=....;// jdbc code to find a user with this email
    if(user!=null)
      return true;
    else
      return false;
    }
}
</code>```

Body:
in our project we have an SQL Database with a table representing all users

CREATE TABLE `user_table` (
`firstname` varchar(20) NOT NULL,
  `lastName` varchar(20) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(24) NOT NULL,
  `accessToken` varchar(64) NOT NULL,
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
)

and we have a class UserDAO. We need to add methods such as

public boolean areUserCredentialsValid(String email, String password) {...}
public boolean isAccessTokenValid(String accessToken) {...}
public boolean isEmailInUse(String email) {...}

I think the names are pretty self-explicative: we want to perform operations on the entire table in order to return boolean values, so we thought it may not be correct to add these methods in UserDAO, as they do not perform CRUD operations on a single User, instead they perform R-only operations on the entire User Table, so we were thinking about a new class AllUsersDAO but it does not seem convincing. What is the best solution here and why?

I don't know if we are overthinking this, but this is a project for an University course and we are evaluated especially for our software engineering abilities, so we want to be sure to adopt the best solution.

Thank you all in advance!

Body:
Based on the method signature that you have given i can see that you are passing one email id or email/password or token at a time hence you can define these methods in your service class and you can use this service method for each user.say a UserService class which accepts these credentials then you can use the dao method to query for an object with these credentials if it returns an object you can return true if it returns null you can return false.

public class UserServiceImpl
{
    public boolean isEmailInUse(String email) {
    User user=....;// jdbc code to find a user with this email
    if(user!=null)
      return true;
    else
      return false;
    }
}


问:
Insert Mutiple Record into Database Using Php Mysql
I am running a forecast.This forecast has been successfully implemented and i want to run summary report based on the forecast. To achieve this, i had to allow the user to click a button "Summary Report". Upon clicking the button, it will insert the record into the Database and immediately fetch and analyze the data into summary as required. Question now is that the record are much like 1200 records. This records are not inserted into the DB,perhaps because it is too much. But when i reduce the period of the forecast such that the record is like 100, it will insert the data  and analyze it as required. What should i do for the record of says 5000 to be inserted into the Database. Or is there a better way to achieve multiple insertion to the database?
See below the insertion code:</p>

```<code>if(isset($_POST['exportBtn'])){
        foreach($_POST['sj'] as $key => $value) {
         $eflt = $_POST['sflt'][$key];
         $emodel = $_POST['smodel'][$key];
         $eengine =$_POST['sengine'][$key];
         $eloc = $_POST['sloc'][$key];
         $estye = $_POST['sstye'][$key];
         $ensvr = $_POST['snsvr'][$key];
         $eehd = $_POST['sehd'][$key];
              $inExp = mysqli_query($link,"INSERT INTO table_name(fltno,model,engine,loc,serviceType,nextSvr,usageHr)VALUES('$eflt','$emodel','$eengine','$eloc','$estye','$ensvr','$eehd')");
        }//End for-each loop
</code>```

答:
```<code>  $data = [];
    $allData = [];
    if(isset($_POST['exportBtn'])){
        foreach($_POST['sj'] as $key => $value) {
            $data[] = isset($_POST['sflt'][$key])?$_POST['sflt'][$key]:'';
            $data[] = isset($_POST['smodel'][$key])?$_POST['smodel'][$key]:'';
            $data[] = isset($_POST['sengine'][$key])?$_POST['sengine'][$key]:'';
            $data[] = isset($_POST['sloc'][$key])?$_POST['sloc'][$key]:'';
            $data[] = isset($_POST['sstye'][$key])?$_POST['sstye'][$key]:'';
            $data[] = isset($_POST['snsvr'][$key])?$_POST['snsvr'][$key]:'';
            $data[] = isset($_POST['sehd'][$key])?$_POST['sehd'][$key]:'';
            $allData []= '('.implode(',', $data).')';
       }
        mysql_query('INSERT INTO table_name (fltno,model,engine,loc,serviceType,nextSvr,usageHr) VALUES '.implode(',', $allData));
}
</code>```

Body:
I am running a forecast.This forecast has been successfully implemented and i want to run summary report based on the forecast. To achieve this, i had to allow the user to click a button "Summary Report". Upon clicking the button, it will insert the record into the Database and immediately fetch and analyze the data into summary as required. Question now is that the record are much like 1200 records. This records are not inserted into the DB,perhaps because it is too much. But when i reduce the period of the forecast such that the record is like 100, it will insert the data  and analyze it as required. What should i do for the record of says 5000 to be inserted into the Database. Or is there a better way to achieve multiple insertion to the database?
See below the insertion code:

if(isset($_POST['exportBtn'])){
        foreach($_POST['sj'] as $key => $value) {
         $eflt = $_POST['sflt'][$key];
         $emodel = $_POST['smodel'][$key];
         $eengine =$_POST['sengine'][$key];
         $eloc = $_POST['sloc'][$key];
         $estye = $_POST['sstye'][$key];
         $ensvr = $_POST['snsvr'][$key];
         $eehd = $_POST['sehd'][$key];
              $inExp = mysqli_query($link,"INSERT INTO table_name(fltno,model,engine,loc,serviceType,nextSvr,usageHr)VALUES('$eflt','$emodel','$eengine','$eloc','$estye','$ensvr','$eehd')");
        }//End for-each loop


问:
Movement of data in a horizontal oriented listbox
I have a wpf listbox and two buttons(up and down).

If the user selects the any item in the list and clicks on down button,all the following items(including the selected item) must shift downwards. And similarly, on click of up button, it should move up.

Example has been explained below :-

```<code>                   Student 1     Student 2     Student 3
       Sem            1             1             1
       Physics       68            87            70
       Chemistry     78            89            78
       Math          62            77            80
       Sem           2             2             2
       Physics       78            69            78
       Chemistry     58            79            88
       Math          72            67            90
</code>```

In the above table, if the user selects first semester item for student 2 and clicks on down button, the data for student 2 should move down as shown below :-

```<code>                   Student 1     Student 2     Student 3
       Sem           1                           1
       Physics       68                          70
       Chemistry     78                          78
       Math          62                          80
       Sem           2             1             2
       Physics       78            87            78
       Chemistry     58            89            88
       Math          72            77            90
</code>```

The data which got shifted should be retrievable.
I am using observable collection to bind the itemsource of listbox.
Below is my sample code:-

```<code><Window.Resources>
        <DataTemplate x:Key="myTemplate">
            <StackPanel>
                <Label Background="Purple" Foreground="White" BorderBrush="Red" BorderThickness="4">
                    <Label.Content>
                        <WrapPanel HorizontalAlignment="Stretch">
                            <TextBlock>Student Name:</TextBlock>
                            <TextBlock Text="{Binding Name}" />
                        </WrapPanel>
                    </Label.Content>
                </Label>
                <WrapPanel>
                    <ListBox ItemsSource="{Binding LstSubjects}" BorderThickness="0" >
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition></RowDefinition>
                                        <RowDefinition></RowDefinition>
                                        <RowDefinition></RowDefinition>
                                        <RowDefinition></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <WrapPanel Grid.Row="0">
                                        <TextBlock> Sem:</TextBlock>
                                        <TextBlock Text="{Binding Semester}"></TextBlock>
                                    </WrapPanel>
                                    <WrapPanel Grid.Row="1">
                                        <TextBlock> Physics:</TextBlock>
                                        <TextBlock Text="{Binding Physics}"></TextBlock>
                                    </WrapPanel>
                                    <WrapPanel  Grid.Row="2">
                                        <TextBlock> Chemistry:</TextBlock>
                                        <TextBlock Text="{Binding Chemistry}"></TextBlock>
                                    </WrapPanel>
                                    <WrapPanel  Grid.Row="3">
                                        <TextBlock> Maths:</TextBlock>
                                        <TextBlock Text="{Binding Maths}"></TextBlock>
                                    </WrapPanel>
                                </Grid>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </WrapPanel>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>

              <Grid>
                    <ListBox ItemsSource="{Binding StudentModel}" ItemTemplate="{StaticResource myTemplate}" Margin="0,0,0,0" VerticalAlignment="Top">
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal"/>
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>
                    </ListBox>
                </Grid>
</code>```

Please note that the listbox contains student name and list of all subject marks(Sem,Physics,Chemistry,Maths).

Thanks in advance.

答:
Here's a sample giving you 2 approaches, showing common ways of handling your data in wpf. This is not an answer to your original question.
From your comment, it seems you want to go another direction, so I post this as an answer. Feeld free to redefine your intention and I will edit this post.

```<code><Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">

<Window.DataContext>
    <local:MyViewmodel/>
</Window.DataContext>

<StackPanel>
    <!-- let Datagrid create the columns -->
    <DataGrid Name="MyDataGrid" ItemsSource="{Binding Students}">
    </DataGrid>

    <!-- A listview with itemtemplate grouping the proprties -->
    <ListView ItemsSource="{Binding Students}">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Name}"></TextBlock>
                    <TextBlock Text="{Binding Semester}"></TextBlock>
                    <TextBlock Text="{Binding Physics}"></TextBlock>
                    <TextBlock Text="{Binding Chemistry}"></TextBlock>
                    <TextBlock Text="{Binding Math}"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>
</code>```

.. and the cs code:

```<code>namespace WpfApplication1
{
public class Student
{
    public string Name { get; set; }
    public int Semester { get; set; }
    public int Physics { get; set; }
    public int Chemistry { get; set; }
    public int Math { get; set; }
};

public class MyViewmodel
{
    public MyViewmodel()
    {
        Students = new ObservableCollection<Student>
        {
            new Student { Name="John", Semester = 1, Physics = 50, Chemistry = 60, Math = 70 },
            new Student { Name="Tim", Semester = 2, Physics = 80, Chemistry = 50, Math = 70 },
            new Student { Name="Aaron", Semester = 3, Physics = 40, Chemistry = 90, Math = 70 }
        };
    }

    public ObservableCollection<Student> Students { get; set; }
};

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}
}
</code>```

Body:
I have a wpf listbox and two buttons(up and down).

If the user selects the any item in the list and clicks on down button,all the following items(including the selected item) must shift downwards. And similarly, on click of up button, it should move up.

Example has been explained below :-

                   Student 1     Student 2     Student 3
       Sem            1             1             1
       Physics       68            87            70
       Chemistry     78            89            78
       Math          62            77            80
       Sem           2             2             2
       Physics       78            69            78
       Chemistry     58            79            88
       Math          72            67            90

In the above table, if the user selects first semester item for student 2 and clicks on down button, the data for student 2 should move down as shown below :-

                   Student 1     Student 2     Student 3
       Sem           1                           1
       Physics       68                          70
       Chemistry     78                          78
       Math          62                          80
       Sem           2             1             2
       Physics       78            87            78
       Chemistry     58            89            88
       Math          72            77            90

The data which got shifted should be retrievable.
I am using observable collection to bind the itemsource of listbox.
Below is my sample code:-

<Window.Resources>
        <DataTemplate x:Key="myTemplate">
            <StackPanel>

                        <WrapPanel HorizontalAlignment="Stretch">
                            <TextBlock>Student Name:</TextBlock>
                            <TextBlock Text="{Binding Name}" />
                        </WrapPanel>

                <WrapPanel>
                    <ListBox ItemsSource="{Binding LstSubjects}" BorderThickness="0" >
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition></RowDefinition>
                                        <RowDefinition></RowDefinition>
                                        <RowDefinition></RowDefinition>
                                        <RowDefinition></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <WrapPanel Grid.Row="0">
                                        <TextBlock> Sem:</TextBlock>
                                        <TextBlock Text="{Binding Semester}"></TextBlock>
                                    </WrapPanel>
                                    <WrapPanel Grid.Row="1">
                                        <TextBlock> Physics:</TextBlock>
                                        <TextBlock Text="{Binding Physics}"></TextBlock>
                                    </WrapPanel>
                                    <WrapPanel  Grid.Row="2">
                                        <TextBlock> Chemistry:</TextBlock>
                                        <TextBlock Text="{Binding Chemistry}"></TextBlock>
                                    </WrapPanel>
                                    <WrapPanel  Grid.Row="3">
                                        <TextBlock> Maths:</TextBlock>
                                        <TextBlock Text="{Binding Maths}"></TextBlock>
                                    </WrapPanel>
                                </Grid>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </WrapPanel>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>

              <Grid>
                    <ListBox ItemsSource="{Binding StudentModel}" ItemTemplate="{StaticResource myTemplate}" Margin="0,0,0,0" VerticalAlignment="Top">
                        <ListBox.ItemsPanel>
                            <ItemsPanelTemplate>
                                <StackPanel Orientation="Horizontal"/>
                            </ItemsPanelTemplate>
                        </ListBox.ItemsPanel>
                    </ListBox>
                </Grid>

Please note that the listbox contains student name and list of all subject marks(Sem,Physics,Chemistry,Maths).

Thanks in advance.

Body:
Here's a sample giving you 2 approaches, showing common ways of handling your data in wpf. This is not an answer to your original question.
From your comment, it seems you want to go another direction, so I post this as an answer. Feeld free to redefine your intention and I will edit this post.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">

<Window.DataContext>
    <local:MyViewmodel/>
</Window.DataContext>

<StackPanel>
    <!-- let Datagrid create the columns -->
    <DataGrid Name="MyDataGrid" ItemsSource="{Binding Students}">
    </DataGrid>

    <!-- A listview with itemtemplate grouping the proprties -->
    <ListView ItemsSource="{Binding Students}">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Name}"></TextBlock>
                    <TextBlock Text="{Binding Semester}"></TextBlock>
                    <TextBlock Text="{Binding Physics}"></TextBlock>
                    <TextBlock Text="{Binding Chemistry}"></TextBlock>
                    <TextBlock Text="{Binding Math}"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>

.. and the cs code:

namespace WpfApplication1
{
public class Student
{
    public string Name { get; set; }
    public int Semester { get; set; }
    public int Physics { get; set; }
    public int Chemistry { get; set; }
    public int Math { get; set; }
};

public class MyViewmodel
{
    public MyViewmodel()
    {
        Students = new ObservableCollection<Student>
        {
            new Student { Name="John", Semester = 1, Physics = 50, Chemistry = 60, Math = 70 },
            new Student { Name="Tim", Semester = 2, Physics = 80, Chemistry = 50, Math = 70 },
            new Student { Name="Aaron", Semester = 3, Physics = 40, Chemistry = 90, Math = 70 }
        };
    }

    public ObservableCollection<Student> Students { get; set; }
};

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}
}


答:
```<code>class ClassName extends AnotherClass
{
    protected $name;
    protected $city;
    protected $age = 24;

    public function __construct()
    {
        $this->name = $this->getName();
        $this->city = $this->getCity();
    }

    ...

    public function fun1()
    {
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
    ...
}
</code>```

That would get you going a bit.

Title: How can I make variables accessible to all the functions within the class in php

Body:
class ClassName extends AnotherClass
{
    protected $name;
    protected $city;
    protected $age = 24;

    public function __construct()
    {
        $this->name = $this->getName();
        $this->city = $this->getCity();
    }

    ...

    public function fun1()
    {
        echo $this->name;
        echo $this->city;
        echo $this->age;
    }
    ...
}

That would get you going a bit.


问:
how to insert tab delimited file into mysql with relation
What i want is to insert data in mysql table but i unable to find the way to make relationship from one row

suppose i have a file file.tab it contains data in like

```<code>parent_1    parent_details_1    child_1.1   child_details_1.1   child_1.2   child_details_1.2
parent_2    parent_details_2    child_2.1   child_details_2.1
parent_3    parent_details_3    child_3.1   child_details_3.1   child_3.2   child_details_3.2   child_3.3   child_details_3.3
</code>```

what i want to achive is to insert data in two table like

```<code>            parent_table
+---+-----------+-------------------+
|id |   name    |      details      |
+---+-----------+-------------------+
| 1 |  parent_1 |  parent_details_1 |
| 2 |  parent_2 |  parent_details_2 |
| 3 |  parent_3 |  parent_details_3 |
+---+-----------+-------------------+

              child_table
+---+-----+-----------+-------------------+
|id | pid |   name    |      details      |
+---+-----+-----------+-------------------+
| 1 |  1  | child_1.1 | child_details_1.1 |
| 2 |  1  | child_1.2 | child_details_1.2 |
| 3 |  2  | child_2.1 | child_details_2.1 |
| 4 |  3  | child_3.1 | child_details_3.1 |
| 5 |  3  | child_3.2 | child_details_3.2 |
| 6 |  3  | child_3.3 | child_details_3.3 |
+---+-----+-----------+-------------------+
</code>```

first two columns is for parent and after that two-two columns belongs to child but i don't know how many child a parent has.

i have tried to load file that way.

```<code>LOAD DATA INFILE '/tmp/file.tab INTO TABLE ...
</code>```

but what do i do next i have no idea.

so kindly help me out in this question.

答:
If the solution doesn't need to be all in SQL I find that preprocessing is often simpler.  In this case split data into two files that can be trivially loaded with LOAD DATA INFILE (one for the parent table and one for the child table).

Here is one way to do the preprocessing using perl

```<code>my ( $parent_id, $child_id ) = ( 0, 0 );
my ( @parent_table, @child_table );
while (<>) {                    # for each line of input
  chomp;
  # split on tabs
  my ( $parent_name, $parent_detail, @child_id_detail_pairs ) = split /\t/;
  # create a row and parent_id for the parent table
  push @parent_table, [ ++$parent_id, $parent_name, $parent_detail ];

  while (@child_id_detail_pairs) { # while we have child names & details
    # remove a name and details
    my $child_name    = shift @child_id_detail_pairs;
    my $child_details = shift @child_id_detail_pairs;

    # create a row and child_id for the child table
    push @child_table, [ ++$child_id, $parent_id, $child_name, $child_details ];
  }
}

# write this to one file to load into the parent table
print "parent_table\n";
for my $row (@parent_table) {
  print join( "\t", @$row ), "\n";
}

# write this to one file to load into the child table
print "child_table\n";
for my $row (@child_table) {
  print join( "\t", @$row ), "\n";
}
</code>```

Body:
What i want is to insert data in mysql table but i unable to find the way to make relationship from one row

suppose i have a file file.tab it contains data in like

parent_1    parent_details_1    child_1.1   child_details_1.1   child_1.2   child_details_1.2
parent_2    parent_details_2    child_2.1   child_details_2.1
parent_3    parent_details_3    child_3.1   child_details_3.1   child_3.2   child_details_3.2   child_3.3   child_details_3.3

what i want to achive is to insert data in two table like

            parent_table
+---+-----------+-------------------+
|id |   name    |      details      |
+---+-----------+-------------------+
| 1 |  parent_1 |  parent_details_1 |
| 2 |  parent_2 |  parent_details_2 |
| 3 |  parent_3 |  parent_details_3 |
+---+-----------+-------------------+

              child_table
+---+-----+-----------+-------------------+
|id | pid |   name    |      details      |
+---+-----+-----------+-------------------+
| 1 |  1  | child_1.1 | child_details_1.1 |
| 2 |  1  | child_1.2 | child_details_1.2 |
| 3 |  2  | child_2.1 | child_details_2.1 |
| 4 |  3  | child_3.1 | child_details_3.1 |
| 5 |  3  | child_3.2 | child_details_3.2 |
| 6 |  3  | child_3.3 | child_details_3.3 |
+---+-----+-----------+-------------------+

first two columns is for parent and after that two-two columns belongs to child but i don't know how many child a parent has.

i have tried to load file that way.

LOAD DATA INFILE '/tmp/file.tab INTO TABLE ...

but what do i do next i have no idea.

so kindly help me out in this question.

Body:
If the solution doesn't need to be all in SQL I find that preprocessing is often simpler.  In this case split data into two files that can be trivially loaded with LOAD DATA INFILE (one for the parent table and one for the child table).

Here is one way to do the preprocessing using perl

my ( $parent_id, $child_id ) = ( 0, 0 );
my ( @parent_table, @child_table );
while (<>) {                    # for each line of input
  chomp;
  # split on tabs
  my ( $parent_name, $parent_detail, @child_id_detail_pairs ) = split /\t/;
  # create a row and parent_id for the parent table
  push @parent_table, [ ++$parent_id, $parent_name, $parent_detail ];

  while (@child_id_detail_pairs) { # while we have child names & details
    # remove a name and details
    my $child_name    = shift @child_id_detail_pairs;
    my $child_details = shift @child_id_detail_pairs;

    # create a row and child_id for the child table
    push @child_table, [ ++$child_id, $parent_id, $child_name, $child_details ];
  }
}

# write this to one file to load into the parent table
print "parent_table\n";
for my $row (@parent_table) {
  print join( "\t", @$row ), "\n";
}

# write this to one file to load into the child table
print "child_table\n";
for my $row (@child_table) {
  print join( "\t", @$row ), "\n";
}


问:
Conditional Left Join SQL
```<code>table A
    ----------------------------
    NAME   | CODE  | BRANCH
    ----------------------------
    bob    | PL    | B
    david  | AA    | B
    susan  | PL    | C
    joe    | AB    | C
    alfred | PL    | B

table B
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    PL   | code 1
    PB   | code 2
    PC   | code 3

table C
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    AA   | code 4
    AB   | code 5
    AC   | code 6
</code>```

Is there any way to join table A, B and C. without join all the table?

```<code>select A.*, COALESCE(B.DESCRIPTION, C.DESCRIPTION) AS DESCRIPTION  from A
left join B on A.CODE = B.CODE
left join C on A.CODE = C.CODE
</code>```

In my real case there will be more than 10 to join with the same column.
So I need conditional left join, something like this

```<code>SELECT A* , DESCRIPTION
FROM A  LEFT JOIN (
     CASE
        WHEN A.CODE = 'B' THEN SELECT * FROM B
        WHEN A.CODE = 'C' THEN SELECT * FROM C
      END
    ) BC ON A.CODE = BC.CODE
</code>```

答:
You could use this to generate queries. Then you write a PL/SQL block to loop through all these queries and execute dynamically to give you separate results.

```<code>SELECT    'SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN '
       || CASE WHEN A.BRANCH = 'B' THEN 'TABLEB B' END
       || CASE WHEN A.BRANCH = 'C' THEN 'TABLEC C' END
       || ' ON '
       || 'A.CODE = '
       || CASE WHEN A.BRANCH = 'B' THEN 'B.CODE' END
       || CASE WHEN A.BRANCH = 'C' THEN 'C.CODE' END
          v_query
  FROM TableA A;
</code>```

Output

```<code>V_QUERY
--------------------------------------------------------------------------------
SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE

SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE

SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEC C ON A.CODE = C.CODE

SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEC C ON A.CODE = C.CODE

SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE
</code>```

Title: Conditional Left Join SQL

Body:
table A
    ----------------------------
    NAME   | CODE  | BRANCH
    ----------------------------
    bob    | PL    | B
    david  | AA    | B
    susan  | PL    | C
    joe    | AB    | C
    alfred | PL    | B

table B
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    PL   | code 1
    PB   | code 2
    PC   | code 3

table C
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    AA   | code 4
    AB   | code 5
    AC   | code 6

Is there any way to join table A, B and C. without join all the table?

select A.*, COALESCE(B.DESCRIPTION, C.DESCRIPTION) AS DESCRIPTION  from A
left join B on A.CODE = B.CODE
left join C on A.CODE = C.CODE

In my real case there will be more than 10 to join with the same column.
So I need conditional left join, something like this

SELECT A* , DESCRIPTION
FROM A  LEFT JOIN (
     CASE
        WHEN A.CODE = 'B' THEN SELECT * FROM B
        WHEN A.CODE = 'C' THEN SELECT * FROM C
      END
    ) BC ON A.CODE = BC.CODE

Body:
You could use this to generate queries. Then you write a PL/SQL block to loop through all these queries and execute dynamically to give you separate results.

SELECT    'SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN '
       || CASE WHEN A.BRANCH = 'B' THEN 'TABLEB B' END
       || CASE WHEN A.BRANCH = 'C' THEN 'TABLEC C' END
       || ' ON '
       || 'A.CODE = '
       || CASE WHEN A.BRANCH = 'B' THEN 'B.CODE' END
       || CASE WHEN A.BRANCH = 'C' THEN 'C.CODE' END
          v_query
  FROM TableA A;

Output

V_QUERY
--------------------------------------------------------------------------------
SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE

SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE

SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEC C ON A.CODE = C.CODE

SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEC C ON A.CODE = C.CODE

SELECT A.* , DESCRIPTION
FROM TABLEA A  LEFT JOIN TABLEB B ON A.CODE = B.CODE


问:
Android sharing intent with google maps location and URL Shortener API
I am trying to share a location with latitude and longitude as;

```<code>String uri = "http://maps.google.com/maps?daddr=" + latLngMaps.latitude + "," + latLngMaps.longitude;
</code>```

Using these lines of code:

```<code>Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                String ShareSub = pharmacyName + "\n" + pharmacyAddress;
                sharingIntent.putExtra(Intent.EXTRA_TEXT, ShareSub + "\n" + shortURL);
                startActivity(Intent.createChooser(sharingIntent, "Share With?"));
</code>```

What I want to do is:

I am using URL shortener api and converting the "http://maps.google.com/maps?daddr=" + latLngMaps.latitude + "," + latLngMaps.longitude; to goo.gl/xxxxx

It becomes like this

Is it possible to get that first Image's view when I share my map on Whatsapp?

If it is not, How can I shorten my link as goo.gl/maps/xxxx not goo.gl/xxxx ?

答:
You need to use Google static Maps API which returns a map as an Image which you can share through intent.You can also customize static maps API like you can set marker location, set zoom level.

```<code>Url
https://maps.googleapis.com/maps/api/staticmap?center=Australia&size=640x400&style=element:labels|visibility:off&style=element:geometry.stroke|visibility:off&style=feature:landscape|element:geometry|saturation:-100&style=feature:water|saturation:-100|invert_lightness:true&key=YOUR_API_KEY
</code>```

You can also use the lighter version of google map using google map options. it is also displayed as an Image. which can be clicked and also has google map customization.

visit my website for learnning Kotlin and Android - Developine

Body:
I am trying to share a location with latitude and longitude as;

String uri = "http://maps.google.com/maps?daddr=" + latLngMaps.latitude + "," + latLngMaps.longitude;

Using these lines of code:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                String ShareSub = pharmacyName + "\n" + pharmacyAddress;
                sharingIntent.putExtra(Intent.EXTRA_TEXT, ShareSub + "\n" + shortURL);
                startActivity(Intent.createChooser(sharingIntent, "Share With?"));

What I want to do is:

I am using URL shortener api and converting the "http://maps.google.com/maps?daddr=" + latLngMaps.latitude + "," + latLngMaps.longitude; to goo.gl/xxxxx

It becomes like this

Is it possible to get that first Image's view when I share my map on Whatsapp?

If it is not, How can I shorten my link as goo.gl/maps/xxxx not goo.gl/xxxx ?

Body:
You need to use Google static Maps API which returns a map as an Image which you can share through intent.You can also customize static maps API like you can set marker location, set zoom level.

Url
https://maps.googleapis.com/maps/api/staticmap?center=Australia&size=640x400&style=element:labels|visibility:off&style=element:geometry.stroke|visibility:off&style=feature:landscape|element:geometry|saturation:-100&style=feature:water|saturation:-100|invert_lightness:true&key=YOUR_API_KEY

You can also use the lighter version of google map using google map options. it is also displayed as an Image. which can be clicked and also has google map customization.

visit my website for learnning Kotlin and Android - Developine


问:
Give the classes a specific id
I have a question about the class, and give the class a specific id.

For example I've got a html code like this:

```<code><div class="test">text1</div>
<div class="test">text2</div>
<div class="test">text3</div>
<div class="test">text4</div>
<div class="test">text5</div>
</code>```

My question is how can I add an id by each .test class.

I thought something like this in Jquery:

```<code>var i = 1;
$('.test').each(function(){
   $('.test').attr('id','id_'+i+'');
   i++
});
</code>```

This doesn't work I think it's something with .closest() or .next()
to solve this problem.

Regards,

Frank

EDIT:

I solved the problem by myself the answer is:

```<code>    $('.test').each(function(){
        $(this).attr('class','test').attr('id','id_'+i+'');
        i++;
    });
</code>```

答:
No reason to make a counter, .each() comes with one built in.</p>

```<code>$('.test').each(function(i){
   $(this).attr('id','id_'+i+'');
});
</code>```

Title: Give the classes a specific id

Body:
I have a question about the class, and give the class a specific id.

For example I've got a html code like this:

text1

text2

text3

text4

text5

My question is how can I add an id by each .test class.

I thought something like this in Jquery:

var i = 1;
$('.test').each(function(){
   $('.test').attr('id','id_'+i+'');
   i++
});

This doesn't work I think it's something with .closest() or .next()
to solve this problem.

Regards,

Frank

EDIT:

I solved the problem by myself the answer is:

    $('.test').each(function(){
        $(this).attr('class','test').attr('id','id_'+i+'');
        i++;
    });

Body:
No reason to make a counter, .each() comes with one built in.

$('.test').each(function(i){
   $(this).attr('id','id_'+i+'');
});


问:
LinkedIn API Key and Secret - Permissions
What permission level do I need to have to get access to the API Key and Secret. Do one have be at least be a campaign manager or does being a viewer suffice? </p>

答: To be able to see the LinkedIn data integration API Keys of an adAccount one have to have at least the “Creative Manager” access permission for the account in question. Out of the 4 available permissions, “Creative Manager” is the second one, right above “Viewer”.


问:
Finding the value and index of the first occurence of the largest element in an array
I'm looking for a way to find the value and index of the first occurrence of the largest element in an array (in ruby). I have not been able to find a way to achieve this with fewer than 2 lines of code and without traversing the array more than I would like.

First I tried:

```<code>example = [1, 100, 2, 100, 3]
value, index = example.each_with_index.max
</code>```

But this gives me the index of the last occurrence of the largest element.

My current approach is:

```<code>example = [1, 100, 2, 100, 3]
value = example.max
index = example.find_index(value)
</code>```

Which works, but if the first and last occurrences of the largest element are the last two elements of the array, my current code has to traverse pretty much the entire array twice.

I'm more interested in performance than code size, but if there is a non-wasteful one-line solution that would be great!

答:
I'm more interested in performance

You really should measure then. Your own solution is about 75 times faster than Cary's solution (who also really should've measured).

```<code>              user     system      total        real
Yours     0.484000   0.000000   0.484000 (  0.485868)
Cary's   36.094000   0.000000  36.094000 ( 36.412679)
</code>```

Yes, your solution traverses the array twice. But it's two fast traversals. Cary only has one traversal, but it's a slow one. He's doing much much more per element, an enumerator gets involved, and he's partially doing it in Ruby code.

My benchmark code:

```<code>require 'benchmark'

example = (1..10**8).to_a
Benchmark.bm(7) do |x|
  x.report("Yours") {
    value = example.max
    index = example.index(value)
  }
  x.report("Cary's") {
    value, index = example.each_with_index.max_by { |n,i| [n,-i] }
  }
end
</code>```

I btw changed your example.find_index to example.index. Same thing. Just shorter name.

The fastest single-pass solution (if you for some reason insist on one) I came up with is this:

```<code>value, index = example[0], 0
i = 0
example.each do |v|
  if v > value
    value = v
    index = i
  end
  i += 1
end
</code>```

That took about 4.8 seconds, so about 7.5 times faster than Cary's but still about 10 times slower than yours.

Bottom line: Use your own solution. You can even make it a short one-liner (but I wouldn't):

```<code>index = example.index(value = example.max)
</code>```

Body:
I'm looking for a way to find the value and index of the first occurrence of the largest element in an array (in ruby). I have not been able to find a way to achieve this with fewer than 2 lines of code and without traversing the array more than I would like.

First I tried:

example = [1, 100, 2, 100, 3]
value, index = example.each_with_index.max

But this gives me the index of the last occurrence of the largest element.

My current approach is:

example = [1, 100, 2, 100, 3]
value = example.max
index = example.find_index(value)

Which works, but if the first and last occurrences of the largest element are the last two elements of the array, my current code has to traverse pretty much the entire array twice.

I'm more interested in performance than code size, but if there is a non-wasteful one-line solution that would be great!

Body:
I'm more interested in performance

You really should measure then. Your own solution is about 75 times faster than Cary's solution (who also really should've measured).

              user     system      total        real
Yours     0.484000   0.000000   0.484000 (  0.485868)
Cary's   36.094000   0.000000  36.094000 ( 36.412679)

Yes, your solution traverses the array twice. But it's two fast traversals. Cary only has one traversal, but it's a slow one. He's doing much much more per element, an enumerator gets involved, and he's partially doing it in Ruby code.

My benchmark code:

require 'benchmark'

example = (1..10**8).to_a
Benchmark.bm(7) do |x|
  x.report("Yours") {
    value = example.max
    index = example.index(value)
  }
  x.report("Cary's") {
    value, index = example.each_with_index.max_by { |n,i| [n,-i] }
  }
end

I btw changed your example.find_index to example.index. Same thing. Just shorter name.

The fastest single-pass solution (if you for some reason insist on one) I came up with is this:

value, index = example[0], 0
i = 0
example.each do |v|
  if v > value
    value = v
    index = i
  end
  i += 1
end

That took about 4.8 seconds, so about 7.5 times faster than Cary's but still about 10 times slower than yours.

Bottom line: Use your own solution. You can even make it a short one-liner (but I wouldn't):

index = example.index(value = example.max)


问:
Can I run a Laravel Route on Linux Cron Job/ Crontab?
I have an API route that updates my Database,

this is the structure of the route that I want to execute via cronjob,

```<code> @extends ('layout')

    @section ('content')

        <script>
                /*--------------------------------------*/
                /* Start Get Employees Data and Update */
                /*------------------------------------*/
                getDataFs();

              function getDataFs()
              {
                    var _token = $("input[name='_token']").val();
                    $.ajax({
                        url: 'https:/api/', /* API Url of JSON Data from Hosts */
                        type: 'GET',
                        dataType: 'json',
                        xhrFields: {
                            withCredentials: true
                        },
                        success: function(response){
                            console.log(response);
                            for(i=0; i < response.length; i++)
                            {
                                $.ajax({
                                    url: '/api/update_list',
                                    headers: {
                                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                    },
                                    type: 'POST',
                                    dataType: 'json',
                                    data: { 'employee_data': response[i], '_token': _token },
                                    success: function(response){
                                        console.log(response);
                                    }
                                })
                            }
                        }
                    });
                }
                /*--------------------------------------*/
                /* End Get Employees Data and Update   */
                /*------------------------------------*/
        </script>
    @endsection
</code>```

Inside my API route I have an ajax request that gets data from another api,

I know it is possible to run php using sh script or a perl script and adding that .sh or .pl script on the created cronjob,

What I want to know is that is it possible to run a laravel route inside a shell script/perl script on linux?

/usr/bin/php myscript.php to /usr/bin/php laravel/route

If So, can you give me a working sample script with path to my laravel route,

答:
After an hour of research, I was able to solve my problem by researching bit by bit,

here's what i did,

For Laravel 5.4 - to be executed in terminal

php artisan make:command CustomCommand --command=command:name

go to app/Console/Kernel.php

locate schedule function
and add this inside $schedule->command('command:name')->daily();

go to app/Console/Commands/CustomCommand.php

add 'User DB;' and set $signature

protected $signature = 'command:name';

set $description = 'This will update employees';

set handle

public function handle()

{

DB::table('users')->where('id','25')->update(['email'=>'sample@gmail.com']);

$this->info('Successfully Updated Data!');

}

go to terminal

go to projectdir

run 'php artisan command:name'

crontab -e

set min, hour, day, year, month php /path/to/project/artisan update:employee

e.g. * * * * * php /var/html/laravelproject/artisan command:name

Body:
I have an API route that updates my Database,

this is the structure of the route that I want to execute via cronjob,

 @extends ('layout')

    @section ('content')

    @endsection

Inside my API route I have an ajax request that gets data from another api,

I know it is possible to run php using sh script or a perl script and adding that .sh or .pl script on the created cronjob,

What I want to know is that is it possible to run a laravel route inside a shell script/perl script on linux?

/usr/bin/php myscript.php to /usr/bin/php laravel/route

If So, can you give me a working sample script with path to my laravel route,


问:
Group array some values
Hi
I'm trying to display Array that has the same type but different value.
How can I show this array in a grouped way according to the value "CAT"?

My array:

```<code>$options  = array(
    array("cat" => "Impresoras","nameProd" => "Impresora 4"),
    array("cat" => "Destructoras","nameProd" => "Destructora 3"),
    array("cat" => "Impresoras","nameProd" => "Impresora 8"),
    array("cat" => "Destructoras","nameProd" => "Destructora 5")
);
</code>```

I need print:

Impresoras: Impresora 4, Impresora 8

Destructoras: Destructora 3, Destructora 5

答:
Create a new array with the cat as key. Someting like this;

```<code>$grouped_categories = array();
foreach ( $options as $option ) {
    $grouped_categories[$option['cat']][] = $option['nameProd'];
}
</code>```

This will output something like;

```<code>[
    'Impresoras' => ['Impresora 4', 'Impresora 8']
    'Destructoras' => [...]
]
</code>```

How you want to output that array is up to you.

Title: Group array some values

Body:
Hi
I'm trying to display Array that has the same type but different value.
How can I show this array in a grouped way according to the value "CAT"?

My array:

$options  = array(
    array("cat" => "Impresoras","nameProd" => "Impresora 4"),
    array("cat" => "Destructoras","nameProd" => "Destructora 3"),
    array("cat" => "Impresoras","nameProd" => "Impresora 8"),
    array("cat" => "Destructoras","nameProd" => "Destructora 5")
);

I need print:

Impresoras: Impresora 4, Impresora 8

Destructoras: Destructora 3, Destructora 5

Body:
Create a new array with the cat as key. Someting like this;

$grouped_categories = array();
foreach ( $options as $option ) {
    $grouped_categories[$option['cat']][] = $option['nameProd'];
}

This will output something like;

[
    'Impresoras' => ['Impresora 4', 'Impresora 8']
    'Destructoras' => [...]
]

How you want to output that array is up to you.


问:
Is std::any_of required to follow short circuit logic?
Given the following code,

```<code>std::vector<int> numbers = {1, 2, 3, 4, 5};
std::any_of(std::begin(numbers), std::end(numbers),
            [](int number) { return number > 3; } );
</code>```

is std::any_of required (by the standard) to return as soon as it reaches 4?

答:
The standard itself doesn't place any such hard requirement. But one may infer it is indirectly encouraged ([alg.any_of]):

```<code>template <class InputIterator, class Predicate>
  bool any_of(InputIterator first, InputIterator last, Predicate pred);
template <class ExecutionPolicy, class ForwardIterator, class Predicate>
  bool any_of(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last,
              Predicate pred);
</code>```

Returns: false if [first, last) is empty or if there is no iterator i in the range [first, last) such that pred(*i) is true, and true
  otherwise.

Complexity: At most last - first applications of the predicate.

While a perfectly conforming implementation may apply the predicate exactly last-first times, the wording to me sounds like it would be encouraged to exit as soon as possible.

Note that it's virtually impossible to ask the same of the overload that accepts an ExecutionPolicy. Since then the order of evaluation is not known.

On a less formal note, any implementation of the sequential version that does not exit the moment the predicate is true, puts the credentials of its author into question.

Body:
Given the following code,

std::vector<int> numbers = {1, 2, 3, 4, 5};
std::any_of(std::begin(numbers), std::end(numbers),
            [](int number) { return number > 3; } );

is std::any_of required (by the standard) to return as soon as it reaches 4?

Body:
The standard itself doesn't place any such hard requirement. But one may infer it is indirectly encouraged ([alg.any_of]):

template <class InputIterator, class Predicate>
  bool any_of(InputIterator first, InputIterator last, Predicate pred);
template <class ExecutionPolicy, class ForwardIterator, class Predicate>
  bool any_of(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last,
              Predicate pred);

Returns: false if [first, last) is empty or if there is no iterator i in the range [first, last) such that pred(*i) is true, and true
  otherwise.

Complexity: At most last - first applications of the predicate.

While a perfectly conforming implementation may apply the predicate exactly last-first times, the wording to me sounds like it would be encouraged to exit as soon as possible.

Note that it's virtually impossible to ask the same of the overload that accepts an ExecutionPolicy. Since then the order of evaluation is not known.

On a less formal note, any implementation of the sequential version that does not exit the moment the predicate is true, puts the credentials of its author into question.


问:
fatal error C1083: Cannot open include file: 'magic.h': No such file or directory
trying to run a django server on my windows 10 computer.

When I execute python manage.py runserver, I get the following error:

fatal error C1083: Cannot open include file: 'magic.h': No such file or directory

I'm running 64 bit python 3.5, on Windows 10.

Here is the picture of the error:

答:
This issue was discussed in GitHub: https://github.com/ahupp/python-magic/issues/154

It seems that solution is to reinstall libmagic "pip install libmagic" and/or "pip install python-magic" (the environment I work with uses both) and download Windows-specific file from https://pypi.python.org/pypi/python-magic-bin/0.4.14 and install that with "pip install " to your Python-environment.


问:
PHP redirect without header() or meta
I'm trying to design a page which does some database actions, then redirects to user back to the page they came from. The problem is that I use a require() function to get the connection to the database, so the headers are already sent. A meta tag is out of the question since I want it to look like all the processes are done from the page they came from. Any tips? Is there a way I can use the require() and the header() or do I have to drop one? Is there an alternative to header()?

答: As Artefacto noted, connecting to the database should not require any output.  Fix whatever you're including (e.g. database_connect.php) not to output.  See this search on the "headers already sent" issue, which may help you find "hidden" output.</p>

Title: PHP redirect without header() or meta


问:
aws call a step function from lambda
SO I have setup a step function to call a lamba which will send an email.

I have manually tested this and it works...Now I want to initially call this step function with a new lambda....I've found some code online and I've played about with it....passes the test and doesn't fire any errors....does anyone know what I am missing as it isn't working?

I've found the code from the tutorial on https://www.youtube.com/watch?v=9MKL5Jr2zZ4&t=306s and I think it should be ok to directly copy it as her only use for it is to call a step function.

Thanks

```<code>'use strict';

const AWS = require('aws-sdk');
const stepFunctions = new AWS.StepFunctions();

//module.exports.hello = (event, context, callback) => {
exports.handler = function(event, context) {
    const response = {
        statusCode:200,
        body: JSON.stringify({
            message: 'Hello World!',
            input: event,
        }),
    };

//  callback(null, response);
};

module.exports.init = (event, context, callback) => {

    const params = {
        stateMachineArn: 'STATE-MACHINE-ARN',
        input: '',
        name: 'Execution lambda'
    }

    stepFunctions.startExecution(params, (err, data) => {
        if(err) {
            console.log(err);

            const response = {
                statusCode: 500,
                body:JSON.stringify({
                    message: 'There was an error'
                }),
            };
            callback(null, response);
        } else {
            console.log(data);

            const response = {
                statusCode: 200,
                body: JSON.stringify({
                    message: 'Step function worked'
                })
            };
            callback(null, response);
        }
    });
};
</code>```

all I want this lambda to do is call the step function executeSendEmailLambda

any help would be greatfull thanky

UPDATE
Thanks to the help of I think I am one bit closer but we are back to square one of test passing but the lambda is not calling the step F

```<code>console.log('Loading function');

const AWS = require('aws-sdk');

exports.handler = function(event, context) {

    console.log('Loading step functions');
    const stepFunctions = new AWS.StepFunctions({
    region: 'US West (Oregon)'
});

console.log('Loading init');
module.exports.init = (event, context, callback) => {

    console.log('Loading params');

    const params = {
        stateMachineArn: 'STATE-MACHINE-ARN',
        // input: JSON.stringify({}), Optional if your statemachine requires an application/json input, make sure its stringified
        name: 'TestExecution' // name can be anything you want, but it should change for every execution
    };

    console.log('start step functions');

    stepFunctions.startExecution(params, (err, data) => {
        if (err) {
            console.log(err);
            const response = {
                statusCode: 500,
                body: JSON.stringify({
                    message: 'There was an error'
                })
            };
            callback(null, response);
        } else {
            console.log(data);
            const response = {
                statusCode: 200,
                body: JSON.stringify({
                    message: 'Step function worked'
                })
            };
            callback(null, response);
            console.log(response);
        }
    });
    };

};
</code>```

the logs for this show the following

```<code>    
23:54:47
2017-12-07T23:54:47.448Z    016133fa-dbaa-11e7-8473-7147adf52922    Loading function

23:54:47
START RequestId: 016133fa-dbaa-11e7-8473-7147adf52922 Version: $LATEST

23:54:47
2017-12-07T23:54:47.767Z    016133fa-dbaa-11e7-8473-7147adf52922    Loading step functions

23:54:47
2017-12-07T23:54:47.905Z    016133fa-dbaa-11e7-8473-7147adf52922    Loading init

23:54:47
END RequestId: 016133fa-dbaa-11e7-8473-7147adf52922

23:54:47
REPORT RequestId: 016133fa-dbaa-11e7-8473-7147adf52922  Duration: 178.97 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 31 MB
No newer events found at the moment. Retry.
</code>```

答:
I modified your code a little bit and tested it with one of my Step Functions and this code seems to work for me :)</p>

```<code>const AWS = require('aws-sdk');

const stepFunctions = new AWS.StepFunctions({
region: 'YOUR_REGION_NAME'
});

module.exports.init = (event, context, callback) => {
const params = {
    stateMachineArn: 'YOUR_STATE_MACHINE_ARN',
    // input: JSON.stringify({}), Optional if your statemachine requires an application/json input, make sure its stringified
    name: 'TestExecution' // name can be anything you want, but it should change for every execution
};

stepFunctions.startExecution(params, (err, data) => {
    if (err) {
    console.log(err);
    const response = {
        statusCode: 500,
        body: JSON.stringify({
        message: 'There was an error'
        })
    };
    callback(null, response);
    } else {
    console.log(data);
    const response = {
        statusCode: 200,
        body: JSON.stringify({
        message: 'Step function worked'
        })
    };
    callback(null, response);
    }
});
};
</code>```

ContentLicense: CC BY-SA 4.0

Title: aws call a step function from lambda

Body:
SO I have setup a step function to call a lamba which will send an email.

I have manually tested this and it works...Now I want to initially call this step function with a new lambda....I've found some code online and I've played about with it....passes the test and doesn't fire any errors....does anyone know what I am missing as it isn't working?

I've found the code from the tutorial on https://www.youtube.com/watch?v=9MKL5Jr2zZ4&t=306s and I think it should be ok to directly copy it as her only use for it is to call a step function.

Thanks

'use strict';

const AWS = require('aws-sdk');
const stepFunctions = new AWS.StepFunctions();

//module.exports.hello = (event, context, callback) => {
exports.handler = function(event, context) {
    const response = {
        statusCode:200,
        body: JSON.stringify({
            message: 'Hello World!',
            input: event,
        }),
    };

//  callback(null, response);
};

module.exports.init = (event, context, callback) => {

    const params = {
        stateMachineArn: 'STATE-MACHINE-ARN',
        input: '',
        name: 'Execution lambda'
    }

    stepFunctions.startExecution(params, (err, data) => {
        if(err) {
            console.log(err);

            const response = {
                statusCode: 500,
                body:JSON.stringify({
                    message: 'There was an error'
                }),
            };
            callback(null, response);
        } else {
            console.log(data);

            const response = {
                statusCode: 200,
                body: JSON.stringify({
                    message: 'Step function worked'
                })
            };
            callback(null, response);
        }
    });
};

all I want this lambda to do is call the step function executeSendEmailLambda

any help would be greatfull thanky

UPDATE
Thanks to the help of I think I am one bit closer but we are back to square one of test passing but the lambda is not calling the step F

console.log('Loading function');

const AWS = require('aws-sdk');

exports.handler = function(event, context) {

    console.log('Loading step functions');
    const stepFunctions = new AWS.StepFunctions({
    region: 'US West (Oregon)'
});

console.log('Loading init');
module.exports.init = (event, context, callback) => {

    console.log('Loading params');

    const params = {
        stateMachineArn: 'STATE-MACHINE-ARN',
        // input: JSON.stringify({}), Optional if your statemachine requires an application/json input, make sure its stringified
        name: 'TestExecution' // name can be anything you want, but it should change for every execution
    };

    console.log('start step functions');

    stepFunctions.startExecution(params, (err, data) => {
        if (err) {
            console.log(err);
            const response = {
                statusCode: 500,
                body: JSON.stringify({
                    message: 'There was an error'
                })
            };
            callback(null, response);
        } else {
            console.log(data);
            const response = {
                statusCode: 200,
                body: JSON.stringify({
                    message: 'Step function worked'
                })
            };
            callback(null, response);
            console.log(response);
        }
    });
    };

};

the logs for this show the following

    
23:54:47
2017-12-07T23:54:47.448Z    016133fa-dbaa-11e7-8473-7147adf52922    Loading function

23:54:47
START RequestId: 016133fa-dbaa-11e7-8473-7147adf52922 Version: $LATEST

23:54:47
2017-12-07T23:54:47.767Z    016133fa-dbaa-11e7-8473-7147adf52922    Loading step functions

23:54:47
2017-12-07T23:54:47.905Z    016133fa-dbaa-11e7-8473-7147adf52922    Loading init

23:54:47
END RequestId: 016133fa-dbaa-11e7-8473-7147adf52922

23:54:47
REPORT RequestId: 016133fa-dbaa-11e7-8473-7147adf52922  Duration: 178.97 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 31 MB
No newer events found at the moment. Retry.

Body:
I modified your code a little bit and tested it with one of my Step Functions and this code seems to work for me :)

const AWS = require('aws-sdk');

const stepFunctions = new AWS.StepFunctions({
region: 'YOUR_REGION_NAME'
});

module.exports.init = (event, context, callback) => {
const params = {
    stateMachineArn: 'YOUR_STATE_MACHINE_ARN',
    // input: JSON.stringify({}), Optional if your statemachine requires an application/json input, make sure its stringified
    name: 'TestExecution' // name can be anything you want, but it should change for every execution
};

stepFunctions.startExecution(params, (err, data) => {
    if (err) {
    console.log(err);
    const response = {
        statusCode: 500,
        body: JSON.stringify({
        message: 'There was an error'
        })
    };
    callback(null, response);
    } else {
    console.log(data);
    const response = {
        statusCode: 200,
        body: JSON.stringify({
        message: 'Step function worked'
        })
    };
    callback(null, response);
    }
});
};


问:
How to prevent users from going back to the previous page?
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

```<code>[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}
</code>```

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

```<code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
</code>```

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

答:
This little piece of code might help you in solving your issue.</p>

```<code><script type="text/javascript">
                /*To retain on the same view on Back Click*/
                history.pushState(null, null, window.location.href);
                window.addEventListener('popstate', function (event) {
                    history.pushState(null, null, window.location.href);
                    event.preventDefault();
                    });
</script>
</code>```

Body:
I am using ASP.NET MVC (latest version).

Imagine having 2 pages:

Page-1: "Enter data" >> Page-2: "Thank you"

After submitting Page-1 you are being redirected to Page-2.

My goal: I want to make sure that you can't go back to Page-1 when you hit the browser's back button once you made it to Page-2. Instead I want you rather to stay on Page-2 (or being pushed forward to Page-2 every time you hit the back button).

I have tried all different kind of things. The following is just some simplified pseudo code ...

[NoBrowserCache]
public ActionResult Page1(int userId)
{
   var user = GetUserFromDb(userId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
      // forward to page 2
      return RedirectToAction("Page2", routeValues: new { userId = userId });
   }

   var model = new Page1Model();

   return View("Page1", model);
}

[NoBrowserCache]
[HttpPost]
public ActionResult Page1(Page1Model model)
{
   var user = GetUserFromDb(model.UserId);
   if (user.HasAlreadySubmittedPage1InThePast)
   {
       // forward to page 2
       return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
   }

   // Save posted data to the db
   // ...

   return RedirectToAction("Page2", routeValues: new { userId = model.UserId });
}

public class NoBrowserCache : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Haha ... tried everything I found on the web here:
        // Make sure the requested page is not put in the browser cache.
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();
        filterContext.HttpContext.Response.Cache.AppendCacheExtension("no-cache");
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now);
        filterContext.HttpContext.Response.Expires = 0;
    }
}

If only I could make sure that a request is being sent to the server every time I hit the back button. But right now, clicking the back button just pulls Page-1 from my browser's cache without sending a request to the server. So currently, I have no chance to redirect you forward to Page-2 by server means.

Any ideas or suggestions?

Thanks, guys!

Btw: There is no login/authentication involved. So, I can't use Session.Abandon() or stuff like this. And I would rather use some server based code than javascript if possible.

EDIT 2017-5-12
Following @grek40, I made sure that the anti-chaching statements end up in the browser. I therefor completely removed the [NoBrowserCache]-ActionFilterAttribute from my C# code above. Instead I added the following statements in the  section of my _Layout.cshtml:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

I confirm that these three lines are being rendered to my browser (used my browser's developer tools to inspect). However, caching still works. I can still move backward without any server requests. Tested this with Google Chrome v62, Firefox Quantum v57 and Microsoft Edge v41 (all on Win10). #

EDIT 2017-6-12
Again following @grek40's suggestions: tried Expires: 0 as well as Expires: -1. No difference. I still didn't manage, to turn off my browser's cache.

Body:
This little piece of code might help you in solving your issue.

<script type="text/javascript">
                /*To retain on the same view on Back Click*/
                history.pushState(null, null, window.location.href);
                window.addEventListener('popstate', function (event) {
                    history.pushState(null, null, window.location.href);
                    event.preventDefault();
                    });
</script>