问:
Jenkins Shared Library - Accessing Git Changeset related info
I have a Jenkins shared library with bunch of Git repos involved.

Repo 1: Jenkins Shared Library repo which is globally configured in Jenkins.

Repo 2: Application code repo which has the actual application code.

Repo 3: Application config repo which has configuration files for various environments of the application.

The pipeline has various steps like checkout, build, code quality check, unit test, build and deployments.

We use Jenkins provided email template in the shared library to notify the build status. Example code:

```<code>def nTo = globalNotificationSettings.mail.to ?: ""
def nEnabled = globalNotificationSettings.mail.enabled ?: false
def nSubject = "${nBuildStatus}: Job ${env.JOB_NAME} Build #${env.BUILD_NUMBER}"
def nBody = '''${SCRIPT, template="groovy-html.template"}'''

if(nTo && nEnabled) {
    emailext body: nBody, \
        subject: nSubject,\
        to: nTo, \
        mimeType : 'text/html'
}
</code>```

The resulting email ends up showing all the changes consolidated into one single table and doesn't show changes per repo. For a quick reference, the email template is available at Jenkins CI github.

Upon further analysis, its obvious that the email extension uses GitChangeSet object and it doesn't seem to have the information on which repo the changeset is coming from.

Is there a way someone can suggest to get hold of the below info inside Shared Library?

List of changesets being processed by the build at the repo level

I'm not looking for a solution to modify the template. Rather, I need help/guidance on how to access the changeset at a repo level using Jenkins Shared Library. Especially, access the repo info for Jenkins Shared Library which is configured globally in Jenkins.

答:
I misread your Q initially, and answered wrongly.

I actually have different discussion:
so you have app code, app config and shared lib(s).

General approach

Each of the above software components, better have its own, dedicated release cycle.

Even though your managers may request you to send ALL the changelogs in 1 build to everybody, this breaks the patterns of separation of concerns/chain of responsibility and decoupling, overloads with irrelevant information (and if you have devs who regularly edit shared lib, this is a serious symptom), also this creates fake accountability (actually fear to touch anything).

So, in terms of who should see each of the changelogs:

shared libs should probably have their individual release cycle, i.e. its jobs/builds, with own tests, and changelog. Only the maintainers of it should be informed on problems upon failed changes/regressions (you could take a look at this project )

the app code better be managed by the devs, have its own release cycles, i.e. its own jobs/builds

the app configuration is usually extracted into a separate repository b/c it "moves slower" and the changes are not related to app version, usually people avoid changing config often, so it should have its own release cycles as well. TBH, there are cleaner approaches to this, by using a conf service (custom, Vault, etcd, ZK and others), since config changes are rarely done by the developers. They are usually done (in prod envs) by the ops people.

In other words, it seems you are being asked to "solve the wrong problem". But if they insist, this is a very ... strange approach to manage things, and you should be skeptical, and challenge those tasks.

But you still wanna do it...

However, if you still want to "get the job done", (the job being creating coupling of things people usually separate, i.e. shooting in own foot), you can start trying some/all of:

explicit checkout() call returns an object you can query (for app and config)

most projects types have repository env variables you can query (comparing PR/MR current hash vs target branch, using repo URL)

for shared libs, if you have some controls over jenkins configuration, you may need to define global variables. for 1 lib to rule them all, you can "extract" both the lib and the version.

Hope this is kind of discussion and "solutioneering" you hoped for.

Body:
I have a Jenkins shared library with bunch of Git repos involved.

Repo 1: Jenkins Shared Library repo which is globally configured in Jenkins.

Repo 2: Application code repo which has the actual application code.

Repo 3: Application config repo which has configuration files for various environments of the application.

The pipeline has various steps like checkout, build, code quality check, unit test, build and deployments.

We use Jenkins provided email template in the shared library to notify the build status. Example code:

def nTo = globalNotificationSettings.mail.to ?: ""
def nEnabled = globalNotificationSettings.mail.enabled ?: false
def nSubject = "${nBuildStatus}: Job ${env.JOB_NAME} Build #${env.BUILD_NUMBER}"
def nBody = '''${SCRIPT, template="groovy-html.template"}'''

if(nTo && nEnabled) {
    emailext body: nBody, \
        subject: nSubject,\
        to: nTo, \
        mimeType : 'text/html'
}

The resulting email ends up showing all the changes consolidated into one single table and doesn't show changes per repo. For a quick reference, the email template is available at Jenkins CI github.

Upon further analysis, its obvious that the email extension uses GitChangeSet object and it doesn't seem to have the information on which repo the changeset is coming from.

Is there a way someone can suggest to get hold of the below info inside Shared Library?

List of changesets being processed by the build at the repo level

I'm not looking for a solution to modify the template. Rather, I need help/guidance on how to access the changeset at a repo level using Jenkins Shared Library. Especially, access the repo info for Jenkins Shared Library which is configured globally in Jenkins.


来源: stackexchange

问:
Guide Me with good Selenium Tutorial
I am new to automation testing tools i like to learn Selenium tool please guide me with right tutorial whether i need to be well versed with any scripting languages or any platform to pass commands..If it is a video tutorial it will be more useful to me and other beginners of Selenium..</p>

答:
Definitely start with the official documentation, as Zugwalt suggested. Beyond that here are a couple suggestions:

One of the first things you will appreciate with Selenium is that you can specify locators (expressions to select something on your web page) in several different languages: XPath, CSS, DOM, or Selenium-native variants. And you do not have to choose one up front; you can mix and match them (though there are definite performance differences to be aware of). As you learn you may want to understand how to map from one of these syntaxes to another, which is where XPath, CSS, DOM and Selenium: The Rosetta Stone and Cookbook comes in. It is a wallchart that presents a large assortment of recipes across all four syntaxes so it is simple to convert from one to another.

I have also written a getting started guide entitled Web Testing with Selenium Sushi: A Practical Guide and Toolset that, while written in the context of Selenium 1, still has value that applies to Selenium 2 installations as well.

ContentLicense: CC BY-SA 3.0

Title: Guide Me with good Selenium Tutorial


问:
how to pass a file data in an object array to be accepted by a REST endpoint made of php?
so in postman, we have a form-data upload button if we want to attach a file and use POST to call an API endpoint. now my question is,

how to add a file if we are gonna use the body as a raw text payload request
if let's say the body is like this ?

```<code>{
    "id": 1,
    "mydata": [
      {
         "entity_id": 1,
         "upload_file": // WHAT TO PUT HERE ?
      },
      {
         "entity_id": 2,
         "upload_file": //WHAT TO PUT HERE ?
      }
    ]
}
</code>```

In backend, we're suppose to catch an attached or uploaded file using $_FILES global variable.. but if the payload request is an object array... how are we suppose to include an attached file or upload file in the payload ? .. please see example above

答:
If you want to pass it in raw data you can encode to base64 for example and then to put it inline.

```<code>$imagedata = file_get_contents("/path/to/file");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);
</code>```

Take the output of $base64 and put it as a raw data.

In addition, by iterating on $_FILES you will get all uploaded files with their keys. in backend you can link key in $_FILES to your object in array.

ContentLicense: CC BY-SA 4.0

Body:
so in postman, we have a form-data upload button if we want to attach a file and use POST to call an API endpoint. now my question is,

how to add a file if we are gonna use the body as a raw text payload request
if let's say the body is like this ?

{
    "id": 1,
    "mydata": [
      {
         "entity_id": 1,
         "upload_file": // WHAT TO PUT HERE ?
      },
      {
         "entity_id": 2,
         "upload_file": //WHAT TO PUT HERE ?
      }
    ]
}

In backend, we're suppose to catch an attached or uploaded file using $_FILES global variable.. but if the payload request is an object array... how are we suppose to include an attached file or upload file in the payload ? .. please see example above

Body:
If you want to pass it in raw data you can encode to base64 for example and then to put it inline.

$imagedata = file_get_contents("/path/to/file");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

Take the output of $base64 and put it as a raw data.

In addition, by iterating on $_FILES you will get all uploaded files with their keys. in backend you can link key in $_FILES to your object in array.


问:
Memory card game stops working after first two cards flipped
I have a simple memory card concentration game with a function to flipCard and checkForMatch . When the checkForMatch function is invoked it evaluates the two cards to see if a match is found and returns an alert message letting the know if the user has got a match or not. Everything works fine initially but right after the first two cards are selected the alerts no longer pop up and the cards don't flip back, so essentially the user can continue flipping over all the remaining cards on the game board. I'm not sure why it's not working after the first two flips. I've tried moving my createBoard() function and moving the flipCard function above the checkForMatch() but that doesn't solve the issue either.

document.addEventListener('DOMContentLoaded', () =>{

const cardArray = [
    {
        name: 'monster1',
        img: 'image1.png'
    },
    {
        name: 'monster1',
        img: 'image1.png'
    },
    {
        name: 'monster2',
        img: 'image2.png'
    },
    {
        name: 'monster2',
        img: 'image2.png'
    },
    {
        name: 'monster3',
        img: 'image3.png'
    },
    {
        name: 'monster3',
        img: 'image3.png'
    },
    {
        name: 'monster4',
        img: 'image4.jpg'
    },
    {
        name: 'monster4',
        img: 'image4.jpg'
    },
    {
        name: 'monster5',
        img: 'image5.png'
    },
    {
        name: 'monster5',
        img: 'image5.png'
    },
    {
        name: 'monster6',
        img: 'image6.png'
    },
    {
        name: 'monster6',
        img: 'image6.png'
    }
]

cardArray.sort(() => 0.5 - Math.random())

const grid = document.querySelector('.grid');
const resultDisplay = document.querySelector('#result')
const cardsChosen = []
const cardsChosenId = []
const cardsWon = []

function createBoard(){
    for (let i = 0; i < cardArray.length; i++) {
        const card = document.createElement('img')
        card.setAttribute('src','logo.png')
        card.setAttribute('data-id', i)
        card.addEventListener('click', flipCard)
        grid.appendChild(card)
    }
}

// Flip Your card
function flipCard() {
    const cardId = this.getAttribute('data-id')
    cardsChosen.push(cardArray[cardId].name)
    cardsChosenId.push(cardId)
    this.setAttribute('src', cardArray[cardId].img)
    if(cardsChosen.length === 2) {
        setTimeout(checkForMatch, 500)      }
}

// Check for matches
function checkForMatch() {
    const cards = document.querySelectorAll('img')
    const optionOneId = cardsChosenId[0]
    const optionTwoId = cardsChosenId[1]

    if (cardsChosen[0] === cardsChosen[1]) {
        alert('You found a match!')
        cards[optionOneId].setAttribute('src', 'white.png')
        cards[optionTwoId].setAttribute('src', 'white.png')
        cardsWon.push(cardsChosen)
    } else {
        alert('Sorry, try again!')
        cards[optionOneId].setAttribute('src', 'logo.png')
        cards[optionTwoId].setAttribute('src', 'logo.png')
    }
    cardsChosen = []
    cardsChosenId = []
    resultDisplay.textContent = cardsWon.length
    if (cardsWon.length === cardArray.length/2) {
        resultDisplay.textContent = 'Congratulations! You found all the cards!'
    }
}

createBoard()

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grid{
    display: flex;
    flex-wrap: wrap;
    height: 300px;
    width: 400px;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    <title>Memory Game - Ania Kubow Tutorial</title>

Score:

```

答:
Problem : You can not re-instantiate const variables which you were doing inside checkForMatch, which is throwing error and your code is not working.

There are two solutions for this.

Solution 1 - You can update declaration of cardsChosen & cardsChosenId with let instead of const.

Solution 2 - To clear array, do not re-instantiate it with cardsChosen = [] but use cardsChosen.splice(0, cardsChosen.length);.

P.S. - You can check browser console and you would have idea about what error you were getting. This way it could have been easy for you to fix problem.

document.addEventListener('DOMContentLoaded', () => {

  const cardArray = [{
      name: 'monster1',
      img: 'image1.png'
    },
    {
      name: 'monster1',
      img: 'image1.png'
    },
    {
      name: 'monster2',
      img: 'image2.png'
    },
    {
      name: 'monster2',
      img: 'image2.png'
    },
    {
      name: 'monster3',
      img: 'image3.png'
    },
    {
      name: 'monster3',
      img: 'image3.png'
    },
    {
      name: 'monster4',
      img: 'image4.jpg'
    },
    {
      name: 'monster4',
      img: 'image4.jpg'
    },
    {
      name: 'monster5',
      img: 'image5.png'
    },
    {
      name: 'monster5',
      img: 'image5.png'
    },
    {
      name: 'monster6',
      img: 'image6.png'
    },
    {
      name: 'monster6',
      img: 'image6.png'
    }
  ]

  cardArray.sort(() => 0.5 - Math.random())

  const grid = document.querySelector('.grid');
  const resultDisplay = document.querySelector('#result')
  let cardsChosen = []
  let cardsChosenId = []
  let cardsWon = []

  function createBoard() {
    for (let i = 0; i < cardArray.length; i++) {
      const card = document.createElement('img')
      card.setAttribute('src', 'logo.png')
      // Added alt for test only
      card.setAttribute('alt', cardArray[i].name)
      card.setAttribute('data-id', i)
      card.addEventListener('click', flipCard)
      grid.appendChild(card)
    }
  }

  // Flip Your card
  function flipCard() {
    const cardId = this.getAttribute('data-id')
    cardsChosen.push(cardArray[cardId].name)
    cardsChosenId.push(cardId)
    this.setAttribute('src', cardArray[cardId].img)
    if (cardsChosen.length === 2) {
      setTimeout(checkForMatch, 500)
    }
  }

  // Check for matches
  function checkForMatch() {
    const cards = document.querySelectorAll('img')
    const optionOneId = cardsChosenId[0]
    const optionTwoId = cardsChosenId[1]

    if (cardsChosen[0] === cardsChosen[1]) {
      alert('You found a match!')
      cards[optionOneId].setAttribute('src', 'white.png')
      cards[optionTwoId].setAttribute('src', 'white.png')
      cardsWon.push(cardsChosen)
    } else {
      alert('Sorry, try again!')
      cards[optionOneId].setAttribute('src', 'logo.png')
      cards[optionTwoId].setAttribute('src', 'logo.png')
    }
    cardsChosen = []
    cardsChosenId = []
    resultDisplay.textContent = cardsWon.length
    if (cardsWon.length === cardArray.length / 2) {
      resultDisplay.textContent = 'Congratulations! You found all the cards!'
    }
  }

  createBoard()

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grid {
  display: flex;
  flex-wrap: wrap;
  height: 300px;
  width: 400px;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="index.css">
  <title>Memory Game - Ania Kubow Tutorial</title>

Score:

```

Body:
I have a simple memory card concentration game with a function to flipCard and checkForMatch . When the checkForMatch function is invoked it evaluates the two cards to see if a match is found and returns an alert message letting the know if the user has got a match or not. Everything works fine initially but right after the first two cards are selected the alerts no longer pop up and the cards don't flip back, so essentially the user can continue flipping over all the remaining cards on the game board. I'm not sure why it's not working after the first two flips. I've tried moving my createBoard() function and moving the flipCard function above the checkForMatch() but that doesn't solve the issue either.

document.addEventListener('DOMContentLoaded', () =>{

const cardArray = [
    {
        name: 'monster1',
        img: 'image1.png'
    },
    {
        name: 'monster1',
        img: 'image1.png'
    },
    {
        name: 'monster2',
        img: 'image2.png'
    },
    {
        name: 'monster2',
        img: 'image2.png'
    },
    {
        name: 'monster3',
        img: 'image3.png'
    },
    {
        name: 'monster3',
        img: 'image3.png'
    },
    {
        name: 'monster4',
        img: 'image4.jpg'
    },
    {
        name: 'monster4',
        img: 'image4.jpg'
    },
    {
        name: 'monster5',
        img: 'image5.png'
    },
    {
        name: 'monster5',
        img: 'image5.png'
    },
    {
        name: 'monster6',
        img: 'image6.png'
    },
    {
        name: 'monster6',
        img: 'image6.png'
    }
]

cardArray.sort(() => 0.5 - Math.random())

const grid = document.querySelector('.grid');
const resultDisplay = document.querySelector('#result')
const cardsChosen = []
const cardsChosenId = []
const cardsWon = []

function createBoard(){
    for (let i = 0; i < cardArray.length; i++) {
        const card = document.createElement('img')
        card.setAttribute('src','logo.png')
        card.setAttribute('data-id', i)
        card.addEventListener('click', flipCard)
        grid.appendChild(card)
    }
}

// Flip Your card
function flipCard() {
    const cardId = this.getAttribute('data-id')
    cardsChosen.push(cardArray[cardId].name)
    cardsChosenId.push(cardId)
    this.setAttribute('src', cardArray[cardId].img)
    if(cardsChosen.length === 2) {
        setTimeout(checkForMatch, 500)      }
}

// Check for matches
function checkForMatch() {
    const cards = document.querySelectorAll('img')
    const optionOneId = cardsChosenId[0]
    const optionTwoId = cardsChosenId[1]

    if (cardsChosen[0] === cardsChosen[1]) {
        alert('You found a match!')
        cards[optionOneId].setAttribute('src', 'white.png')
        cards[optionTwoId].setAttribute('src', 'white.png')
        cardsWon.push(cardsChosen)
    } else {
        alert('Sorry, try again!')
        cards[optionOneId].setAttribute('src', 'logo.png')
        cards[optionTwoId].setAttribute('src', 'logo.png')
    }
    cardsChosen = []
    cardsChosenId = []
    resultDisplay.textContent = cardsWon.length
    if (cardsWon.length === cardArray.length/2) {
        resultDisplay.textContent = 'Congratulations! You found all the cards!'
    }
}

createBoard()

})

.grid{
    display: flex;
    flex-wrap: wrap;
    height: 300px;
    width: 400px;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="index.css">
    <title>Memory Game - Ania Kubow Tutorial</title>

Score:

Body:
Problem : You can not re-instantiate const variables which you were doing inside checkForMatch, which is throwing error and your code is not working.

There are two solutions for this.

Solution 1 - You can update declaration of cardsChosen & cardsChosenId with let instead of const.

Solution 2 - To clear array, do not re-instantiate it with cardsChosen = [] but use cardsChosen.splice(0, cardsChosen.length);.

P.S. - You can check browser console and you would have idea about what error you were getting. This way it could have been easy for you to fix problem.

document.addEventListener('DOMContentLoaded', () => {

  const cardArray = [{
      name: 'monster1',
      img: 'image1.png'
    },
    {
      name: 'monster1',
      img: 'image1.png'
    },
    {
      name: 'monster2',
      img: 'image2.png'
    },
    {
      name: 'monster2',
      img: 'image2.png'
    },
    {
      name: 'monster3',
      img: 'image3.png'
    },
    {
      name: 'monster3',
      img: 'image3.png'
    },
    {
      name: 'monster4',
      img: 'image4.jpg'
    },
    {
      name: 'monster4',
      img: 'image4.jpg'
    },
    {
      name: 'monster5',
      img: 'image5.png'
    },
    {
      name: 'monster5',
      img: 'image5.png'
    },
    {
      name: 'monster6',
      img: 'image6.png'
    },
    {
      name: 'monster6',
      img: 'image6.png'
    }
  ]

  cardArray.sort(() => 0.5 - Math.random())

  const grid = document.querySelector('.grid');
  const resultDisplay = document.querySelector('#result')
  let cardsChosen = []
  let cardsChosenId = []
  let cardsWon = []

  function createBoard() {
    for (let i = 0; i < cardArray.length; i++) {
      const card = document.createElement('img')
      card.setAttribute('src', 'logo.png')
      // Added alt for test only
      card.setAttribute('alt', cardArray[i].name)
      card.setAttribute('data-id', i)
      card.addEventListener('click', flipCard)
      grid.appendChild(card)
    }
  }

  // Flip Your card
  function flipCard() {
    const cardId = this.getAttribute('data-id')
    cardsChosen.push(cardArray[cardId].name)
    cardsChosenId.push(cardId)
    this.setAttribute('src', cardArray[cardId].img)
    if (cardsChosen.length === 2) {
      setTimeout(checkForMatch, 500)
    }
  }

  // Check for matches
  function checkForMatch() {
    const cards = document.querySelectorAll('img')
    const optionOneId = cardsChosenId[0]
    const optionTwoId = cardsChosenId[1]

    if (cardsChosen[0] === cardsChosen[1]) {
      alert('You found a match!')
      cards[optionOneId].setAttribute('src', 'white.png')
      cards[optionTwoId].setAttribute('src', 'white.png')
      cardsWon.push(cardsChosen)
    } else {
      alert('Sorry, try again!')
      cards[optionOneId].setAttribute('src', 'logo.png')
      cards[optionTwoId].setAttribute('src', 'logo.png')
    }
    cardsChosen = []
    cardsChosenId = []
    resultDisplay.textContent = cardsWon.length
    if (cardsWon.length === cardArray.length / 2) {
      resultDisplay.textContent = 'Congratulations! You found all the cards!'
    }
  }

  createBoard()

})

.grid {
  display: flex;
  flex-wrap: wrap;
  height: 300px;
  width: 400px;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="index.css">
  <title>Memory Game - Ania Kubow Tutorial</title>
</head>

<body>
  <h3>Score:<span id="result"></span></h3>

  <div class="grid"></div>

  <script src="index.js"></script>
</body>

</html>


问:
A simple way to sum a result from UNION in MySQL
I have a union of three tables (t1, t2, t3).

Each rerun exactly the same number of records, first column is id, second amount:

```<code>1  10
2  20
3  20

1  30
2  30
3  10

1  20
2  40
3  50
</code>```

Is there a simple way in SQL to sum it up, i.e. to only get:

```<code>1   60
2   80
3   80
</code>```

答:
```<code>SELECT      BANKEMPNAME,  workStation, SUM (CALCULATEDAMOUNT) FROM(
SELECT      BANKEMPNAME, workStation, SUM(CALCULATEDAMOUNT) AS CALCULATEDAMOUNT,SALARYMONTH
FROM        dbo.vw_salaryStatement
WHERE       (ITEMCODE  LIKE 'A%')
GROUP BY    BANKEMPNAME,workStation, SALARYMONTH
union all
SELECT      BANKEMPNAME, workStation,  SUM(CALCULATEDAMOUNT) AS CALCULATEDAMOUNT,SALARYMONTH
FROM        dbo.vw_salaryStatement
WHERE       (ITEMCODE  NOT LIKE 'A%')
GROUP BY    BANKEMPNAME, workStation, SALARYMONTH) as t1
WHERE       SALARYMONTH BETWEEN '20220101' AND '20220131'
group by    BANKEMPNAME,  workStation
order by    BANKEMPNAME asc
</code>```

IN MSSQL You can write this way, But Doing UNION ALL THE Column should be the same for both ways.

I have given this example So that you can understand the process...

Body:
I have a union of three tables (t1, t2, t3).

Each rerun exactly the same number of records, first column is id, second amount:

1  10
2  20
3  20

1  30
2  30
3  10

1  20
2  40
3  50

Is there a simple way in SQL to sum it up, i.e. to only get:

1   60
2   80
3   80

Body:
SELECT      BANKEMPNAME,  workStation, SUM (CALCULATEDAMOUNT) FROM(
SELECT      BANKEMPNAME, workStation, SUM(CALCULATEDAMOUNT) AS CALCULATEDAMOUNT,SALARYMONTH
FROM        dbo.vw_salaryStatement
WHERE       (ITEMCODE  LIKE 'A%')
GROUP BY    BANKEMPNAME,workStation, SALARYMONTH
union all
SELECT      BANKEMPNAME, workStation,  SUM(CALCULATEDAMOUNT) AS CALCULATEDAMOUNT,SALARYMONTH
FROM        dbo.vw_salaryStatement
WHERE       (ITEMCODE  NOT LIKE 'A%')
GROUP BY    BANKEMPNAME, workStation, SALARYMONTH) as t1
WHERE       SALARYMONTH BETWEEN '20220101' AND '20220131'
group by    BANKEMPNAME,  workStation
order by    BANKEMPNAME asc

IN MSSQL You can write this way, But Doing UNION ALL THE Column should be the same for both ways.

I have given this example So that you can understand the process...


问:
Foursquare, how to display checkins feed from all users of my website?
So, I understand that each user of my website will have an Auth_key after they allow my website to access their foursquare account (after the authentication process). What I understand is, to display the latest checkins of a user, I need to use that user's auth_key and use the users/self/checkins end point to get the particular user latest checkpoint. So, in order to get all users latest checkins, I need to loop through each of my users, get each auth_key and get the feeds.

I'm making a feeds of the latest checkins of my users. So, it will be displaying the latest 20 checkins. Which end point can I use to achieve this?

答:
Apparently, foursquare API developers are working on a 'Push API'. So, instead of we sending request to foursquare, foursquare will send us the data every time a user who is authorized in our website do a check in.

https://github.com/foursquare/hackathon/wiki/Foursquare-Push-API


问:
Function to validate an input type button max value 9 and min value 1, not working
I have a challenge that make a table depending on what's on the inputs.

function createTable(){
    let table = document.getElementById('table')
    let row = document.getElementById('input-row').value
    let column = document.getElementById('input-column').value

     for(let rowIndex = 0; rowIndex < row; rowIndex++){
        let tr = document.createElement('tr')

        for(let colIndex = 0; colIndex < column; colIndex++){
            let td = document.createElement('td')
            tr.appendChild(td)
        }

        table.appendChild(tr)

        document.getElementById('input-row').value = " "
        document.getElementById('input-column').value = " "

        if(row == " ") {
            alert('Number of rows cannot be empty')
            return false
        }

        if(row > 9) {
            alert('Number of rows cannot be greater than 9')
            return false
        }

        if(row <= 0) {
            alert('Number of rows cannot be less than 1')
            return false
        }

    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="inputs-container">
            <div class="inputs-container_rows">
                <input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">
                <h3>Rows</h3>
            </div>
            <div class="inputs-container_columns">
                <input type="number" class="inputs" max=9 min=0 id="input-column">
                <h3>Columns</h3>
            </div>
 </div>
 <div class="btn-container">
            <button id="btn" onclick="createTable()">Create Table</button>
        </div>
        <div class="table-container">
            <table border="1" id="table">

            </table>
 </div></code>```

for the validation only the if(row > 9) is working the other ones not.

Also, I want to erase the table when again I press the button, I don't know how to do it.

答:
I noticed some issues:

Since you get the row value as a string, you should use the String.length property to check if it is empty. Or you can evaluate that no value is entered by comparing with "".

You need to convert row to integer before comparing; parseInt() method can be used for this purpose.

You should evaluate conditions before looping.

let table = document.getElementById('table');
let rowElement = document.getElementById('input-row');
let columnElement = document.getElementById('input-column');

function isValid() {
    let row = rowElement.value;

    if(row.length == 0){
        alert('Number of rows cannot be empty');
        return false;
    }

    if(parseInt(row) > 9) {
        alert('Number of rows cannot be greater than 9');
        return false;
    }

    if(parseInt(row) <= 0) {
        alert('Number of rows cannot be less than 1');
        return false;
    }
    return true;
}

function createTable(){
    let row = rowElement.value;
    let column = columnElement.value;

    if(isValid(row))
    {
      for(let rowIndex = 0; rowIndex < row; rowIndex++)
      {
          let tr = document.createElement('tr')

          for(let colIndex = 0; colIndex < column; colIndex++){
              let td = document.createElement('td')
              tr.appendChild(td)
          }

          table.appendChild(tr);
          document.getElementById('input-row').value = "";
          document.getElementById('input-column').value = "";
      }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="inputs-container">
  <div class="inputs-container_rows">
      <input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">
      <h3>Rows</h3>
  </div>
  <div class="inputs-container_columns">
      <input type="number" class="inputs" max=9 min=0 id="input-column">
      <h3>Columns</h3>
  </div>
</div>

<div class="btn-container">
  <button id="btn" onclick="createTable()">Create Table</button>
</div>

<div class="table-container">
  <table border="1" id="table"></table>
</div></code>```

Body:
I have a challenge that make a table depending on what's on the inputs.

function createTable(){
    let table = document.getElementById('table')
    let row = document.getElementById('input-row').value
    let column = document.getElementById('input-column').value

     for(let rowIndex = 0; rowIndex < row; rowIndex++){
        let tr = document.createElement('tr')

        for(let colIndex = 0; colIndex < column; colIndex++){
            let td = document.createElement('td')
            tr.appendChild(td)
        }

        table.appendChild(tr)

        document.getElementById('input-row').value = " "
        document.getElementById('input-column').value = " "

        if(row == " ") {
            alert('Number of rows cannot be empty')
            return false
        }

        if(row > 9) {
            alert('Number of rows cannot be greater than 9')
            return false
        }

        if(row <= 0) {
            alert('Number of rows cannot be less than 1')
            return false
        }

    }
}

                <input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">

Rows

                <input type="number" class="inputs" max=9 min=0 id="input-column">

Columns

            <button id="btn" onclick="createTable()">Create Table</button>

for the validation only the if(row > 9) is working the other ones not.

Also, I want to erase the table when again I press the button, I don't know how to do it.

Body:
I noticed some issues:

Since you get the row value as a string, you should use the String.length property to check if it is empty. Or you can evaluate that no value is entered by comparing with "".

You need to convert row to integer before comparing; parseInt() method can be used for this purpose.

You should evaluate conditions before looping.

let table = document.getElementById('table');
let rowElement = document.getElementById('input-row');
let columnElement = document.getElementById('input-column');

function isValid() {
    let row = rowElement.value;

    if(row.length == 0){
        alert('Number of rows cannot be empty');
        return false;
    }

    if(parseInt(row) > 9) {
        alert('Number of rows cannot be greater than 9');
        return false;
    }

    if(parseInt(row) <= 0) {
        alert('Number of rows cannot be less than 1');
        return false;
    }
    return true;
}

function createTable(){
    let row = rowElement.value;
    let column = columnElement.value;

    if(isValid(row))
    {
      for(let rowIndex = 0; rowIndex < row; rowIndex++)
      {
          let tr = document.createElement('tr')

          for(let colIndex = 0; colIndex < column; colIndex++){
              let td = document.createElement('td')
              tr.appendChild(td)
          }

          table.appendChild(tr);
          document.getElementById('input-row').value = "";
          document.getElementById('input-column').value = "";
      }
    }
}

<div class="inputs-container">
  <div class="inputs-container_rows">
      <input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">
      <h3>Rows</h3>
  </div>
  <div class="inputs-container_columns">
      <input type="number" class="inputs" max=9 min=0 id="input-column">
      <h3>Columns</h3>
  </div>
</div>

<div class="btn-container">
  <button id="btn" onclick="createTable()">Create Table</button>
</div>

<div class="table-container">
  <table border="1" id="table"></table>
</div>


问:
Extract specific list elements from a nested list in R?
I have a nested list that looks like this:

```<code>x <- list(list(a = c(1,10), b=c(2,10)), list(c=c(3,10), d=c(6,10)), list(e= c(3,10)))
> x
[[1]]
[[1]]$a
[1]  1 10

[[1]]$b
[1]  2 10

[[2]]
[[2]]$c
[1]  3 10

[[2]]$d
[1]  6 10

[[3]]
[[3]]$e
[1]  3 10
</code>```

I'm trying to extract just the first value from each list element. However, if the length of a list is greater than 1, then I want to add the extracted values together.

For example, in my list x above, we can see that the first list (i.e., x[[1]]) contains a and b... so I want to extract the 1st values from this list (in this case, 1 and 2) and since they belong to the same list, they get added together.

At the end, Im just trying to return a vector of the extracted (and where necessary, added) values. So in my example, I would expect a vector like: [1] 3 9 3.

答:
Here's another option using a nested map_dbl from purrr:

```<code>library(purrr)

map_dbl(x, ~sum(map_dbl(.x, 1)))
# [1] 3 9 3
</code>```

Body:
I have a nested list that looks like this:

x <- list(list(a = c(1,10), b=c(2,10)), list(c=c(3,10), d=c(6,10)), list(e= c(3,10)))
> x
[[1]]
[[1]]$a
[1]  1 10

[[1]]$b
[1]  2 10

[[2]]
[[2]]$c
[1]  3 10

[[2]]$d
[1]  6 10

[[3]]
[[3]]$e
[1]  3 10

I'm trying to extract just the first value from each list element. However, if the length of a list is greater than 1, then I want to add the extracted values together.

For example, in my list x above, we can see that the first list (i.e., x[[1]]) contains a and b... so I want to extract the 1st values from this list (in this case, 1 and 2) and since they belong to the same list, they get added together.

At the end, Im just trying to return a vector of the extracted (and where necessary, added) values. So in my example, I would expect a vector like: [1] 3 9 3.

Body:
Here's another option using a nested map_dbl from purrr:

library(purrr)

map_dbl(x, ~sum(map_dbl(.x, 1)))
# [1] 3 9 3


问:
The listener for function 'Function1' was unable to start when running a timer function
I am getting this below error when I am running my timer function app in Azure Cloud. It is just a basic code and I wanted the log to be shown in Insight.

```<code>public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}
</code>```

答:
Here is the workaround I did to identify this issue cause:

Created the Azure Function (Stack: .NET 3.1) of type Timer Trigger with your given timer "0 * * * * *" and the connection string given from the storage account created in Azure portal, which is running successfully (in local):

2. Deleted the Storage account from the Azure Portal and tried to run the function locally which gave me the error: The listener for function Function1 was unable to start.

Recovered the Storage Account and then deployed to the Azure Portal Function App and running successfully in cloud also:

In the Azure Cloud, Yes, as @Skin Said that it would be a Storage Account configuration issue.

Few of the steps to resolve this issue were:

Check the AzureWebJobsStorage value contains correct the correct storage account connection string.

Check the Storage account is not deleted.

Check the Networking Option in the Function App that might be the firewall is blocking/restricting the access to the associated storage account.

Body:
I am getting this below error when I am running my timer function app in Azure Cloud. It is just a basic code and I wanted the log to be shown in Insight.

public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}


问:
Default and Parameterized constructors and object declaration
I've written this code:

```<code>#include<iostream>

using namespace std;

class Student {
   public:
      string name;
      int age;
      Student() {
         cout<<"Default constructor"<<endl;
      }
      Student(string name, int age) {
         this->name=name;
         this->age=age;
         cout<<"Parameterized constructor"<<endl;
      }
};

int main() {
   system("clear");
   Student s1={"abc", 20};                                                                                return 0;                                                                                }
</code>```

Result:

```<code>Parameterized constructor
</code>```

Conclusion: Defining object s1 like this Student s1={"abc", 20} calls parameterized constructor of class

Testing out conclusion:

```<code>#include<iostream>

using namespace std;

class Student {
   public:
      string name;
      int age;
};

int main() {
   system("clear");
   Student s1={"abc", 20};

   return 0;
}
</code>```

But compiling the code above doesn't give any errors.

Questions:

Why there is no errors even if we don't define any parameterized constructor inside class ?

When we define class data members as private, we get some error:

```<code>5.cpp:12:12: error: no matching constructor for initialization of 'Student'
   Student s1={"abc", 20};
           ^  ~~~~~~~~~~~
5.cpp:5:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
class Student {
      ^
5.cpp:5:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
5.cpp:5:7: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 2 were provided
1 error generated.
</code>```

Why we are getting this error now and not when data members were public ?
:)

答:
For the 1st case, Student has user-declared constructors, Student s1={"abc", 20}; performs list-initialization, as the effect, the appropriate constructor Student::Student(string, int) is selected to construct s1.

If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, ...

For the 2nd case, Student has no user-declared constructors, it's an aggregate and Student s1={"abc", 20}; performs aggregate-initialization, as the effect the data member name and age are initialized from "abc" and 20 directly.

An aggregate is one of the following types:

...

... class type (typically, struct or union), that has

...

no user-declared or inherited constructors

...

Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list.

If you make data members private, Student is not aggregate again. Student s1={"abc", 20}; still performs list-initialization and causes the error since no appropriate constructor exists.

An aggregate is one of the following types:

...

... class type (typically, struct or union), that has

no private or protected direct (since C++17)non-static data members

...

Body:
I've written this code:

#include<iostream>

using namespace std;

class Student {
   public:
      string name;
      int age;
      Student() {
         cout<<"Default constructor"<<endl;
      }
      Student(string name, int age) {
         this->name=name;
         this->age=age;
         cout<<"Parameterized constructor"<<endl;
      }
};

int main() {
   system("clear");
   Student s1={"abc", 20};                                                                                return 0;                                                                                }

Result:

Parameterized constructor

Conclusion: Defining object s1 like this Student s1={"abc", 20} calls parameterized constructor of class

Testing out conclusion:

#include<iostream>

using namespace std;

class Student {
   public:
      string name;
      int age;
};

int main() {
   system("clear");
   Student s1={"abc", 20};

   return 0;
}

But compiling the code above doesn't give any errors.

Questions:

Why there is no errors even if we don't define any parameterized constructor inside class ?

When we define class data members as private, we get some error:

5.cpp:12:12: error: no matching constructor for initialization of 'Student'
   Student s1={"abc", 20};
           ^  ~~~~~~~~~~~
5.cpp:5:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
class Student {
      ^
5.cpp:5:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
5.cpp:5:7: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 2 were provided
1 error generated.

Why we are getting this error now and not when data members were public ?
:)


问:
Set a html form with javascript
I've been playing with the PayPal code:

```<code>                <form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="paypal">
                <input type="hidden" name="cmd" value="_cart">
                <input type="hidden" name="upload" value="1">
                <input type="hidden" name="currency_code" value="GBP">
                <input type="hidden" name="business" value="test@test.org">
                <input type="hidden" name="item_name_1" value="Item1">
                <input type="hidden" name="amount_1" value="1.00">
                <input type="hidden" name="item_name_2" value="Item2">
                <input type="hidden" name="amount_2" value="2.00">
                <input type="submit" value="PayPal">
                </form>
</code>```

And I want to set the value of item_name_1 and amount_1 via javascript when a button is pressed elsewhere so when that form is submitted the values are all set:

So I have this function run when the add to cart is clicked:

```<code><script type='text/javascript'>
function addtocart(){
paypal.item_name_2.value="Hello!";
}
 </script>
</code>```

I feel I'm on the right tracks but no joy. Help please! TIA

答:
try this </p>

```<code>document.forms['paypay']['item_name_2'].value = "hello";
</code>```

Title: Set a html form with javascript

Body:
I've been playing with the PayPal code:

                <form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="paypal">
                <input type="hidden" name="cmd" value="_cart">
                <input type="hidden" name="upload" value="1">
                <input type="hidden" name="currency_code" value="GBP">
                <input type="hidden" name="business" value="test@test.org">
                <input type="hidden" name="item_name_1" value="Item1">
                <input type="hidden" name="amount_1" value="1.00">
                <input type="hidden" name="item_name_2" value="Item2">
                <input type="hidden" name="amount_2" value="2.00">
                <input type="submit" value="PayPal">
                </form>

And I want to set the value of item_name_1 and amount_1 via javascript when a button is pressed elsewhere so when that form is submitted the values are all set:

So I have this function run when the add to cart is clicked:

I feel I'm on the right tracks but no joy. Help please! TIA

Body:
try this

document.forms['paypay']['item_name_2'].value = "hello";


问:
Compiling a haskell script with external dependencies without cabal
I'm relatively new to Haskell and I realize I might be swimming against the stream here, but nonetheless, I'll ask:

Say I have a short Haskell script:

```<code>import Data.List.Split (splitOn)

main :: IO ()
main = do
  let orders = splitOn "x" "axbxc"
  putStrLn $ head orders
</code>```

If I used only standard functions I could compile this with ghc

答:
I think this is the quintessential entry point to the package management battle in Haskell. It's not there's not enough advice, but there's so much, each with its own caveats and assumptions. Climbing that mountain for the sake of splitOn feels to the newbie like they're Doing It Wrong.

After spending far too much time trying each permutation, I've collated the fine answers here, and many, many others from elsewhere, put them to the test, and summarised the results. The full write up is here.

The pertinent summary of solutions is:

Install globally

You can still do global installs with cabal install --lib the-package.

Use Stack as a run command

You can use stack directly, eg: stack exec --package containers --package optparse-generic [...and so on] -- runghc hello.hs

Create a Stack project

The real deal. Run stack new my-project hraftery/minimal, put your code in Main.hs and your dependencies in my-project.cabal (and maybe stack.yaml - check the article), and then run stack build to automagically pull and build all dependencies.

Use a Stack script

Make your Haskell file itself an executable Stack script. Add -- stack --resolver lts-6.25 script --package the-package to the top of your .hs file and set its executable bit.

For my Edit/Test/Run workflow (eg. using VS Code, GHCi and GHC respectively), I found it pretty clear what works in practice. In summary:

Amongst a chorus of discouragement, Global Installs suit what I know of your use case just fine.

Where Global Installs don't make sense (eg. for managing dependency versions or being portable) a Stack project starting from my minimal template is a smooth transition to a more sophisticated and popular method.

Body:
I'm relatively new to Haskell and I realize I might be swimming against the stream here, but nonetheless, I'll ask:

Say I have a short Haskell script:

import Data.List.Split (splitOn)

main :: IO ()
main = do
  let orders = splitOn "x" "axbxc"
  putStrLn $ head orders

If I used only standard functions I could compile this with ghc


问:
RockMongo Collections View - Error Description make encrpytion
I have installed and implemented the rockmongo tool and auth things are going cool. but while viewing the collections description the popup shows to view the data which are simple text, i need to show it as encrypted.</p>

答:
finally myself cracked it...changed some javascript code in Js Folder and i got the popup with decrypt.....

File name called collection.js where you can customize the popup


问:
Flutter merge array if they are duplicated
I need to merge arrays that are duplicate

I have data like this

```<code>var filterData = [{'date': '25, feb', 'data': ['asd','dsa']}, {'date': '25, feb', 'data': ['asd','dsa']}, {'date': '26, feb', 'data': ['asd','dsa']}]
</code>```

I want to filter it like [{'date': '25, feb', 'data': ['asd','dsa','asd','dsa']}, {'date': '26, feb', 'data': ['asd','dsa']}]

答:
You could create a model class mainly for getting type safety and equality checks ==. The latter is needed so a Set cand know when two objects are equals.

```<code>// Feel free to change the class name
class Datum {
  final String date;
  final List<String> data;

  Datum(this.date, this.data);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Datum && runtimeType == other.runtimeType && date == other.date && data == other.data;

  @override
  int get hashCode => date.hashCode ^ data.hashCode;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        json["date"] as String,
        List<String>.from((json["data"] as List).map((x) => '$x')),
      );

  Map<String, dynamic> toJson() => {
        "date": date,
        "data": List<dynamic>.from(data.map((x) => x)),
      };
}

</code>```

And then you could use a Set so it does not hold duplicate objects. And by overriding the == and hashCode the Set checks if an two objects are the same.

```<code>var filterData = {
Datum.fromJson({'date': '25, feb', 'data': ['asd','dsa']}),
Datum.fromJson({'date': '25, feb', 'data': ['asd','dsa']}),
 Datum.fromJson({'date': '26, feb', 'data': ['asd','dsa']})
}
</code>```

Note that filterData now is a Set and not a List.

Body:
I need to merge arrays that are duplicate

I have data like this

var filterData = [{'date': '25, feb', 'data': ['asd','dsa']}, {'date': '25, feb', 'data': ['asd','dsa']}, {'date': '26, feb', 'data': ['asd','dsa']}]

I want to filter it like [{'date': '25, feb', 'data': ['asd','dsa','asd','dsa']}, {'date': '26, feb', 'data': ['asd','dsa']}]

Body:
You could create a model class mainly for getting type safety and equality checks ==. The latter is needed so a Set cand know when two objects are equals.

// Feel free to change the class name
class Datum {
  final String date;
  final List<String> data;

  Datum(this.date, this.data);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Datum && runtimeType == other.runtimeType && date == other.date && data == other.data;

  @override
  int get hashCode => date.hashCode ^ data.hashCode;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        json["date"] as String,
        List<String>.from((json["data"] as List).map((x) => '$x')),
      );

  Map<String, dynamic> toJson() => {
        "date": date,
        "data": List<dynamic>.from(data.map((x) => x)),
      };
}

And then you could use a Set so it does not hold duplicate objects. And by overriding the == and hashCode the Set checks if an two objects are the same.

var filterData = {
Datum.fromJson({'date': '25, feb', 'data': ['asd','dsa']}),
Datum.fromJson({'date': '25, feb', 'data': ['asd','dsa']}),
 Datum.fromJson({'date': '26, feb', 'data': ['asd','dsa']})
}

Note that filterData now is a Set and not a List.


问:
Laravel cannot find public dir
I worked on a team and then clone the laravel/php codes from our repository. When I serve the laravel on localhost, it cannot find all the file inside the public directory and throw an error on the terminal:

[404]: GET /public/css/style.css - No such file or directory
```
<p>Many answers to similar issues advise me to change the codes in the <code>blade.php</code> file. The problem is that I can't edit the <code>blade.php</code> because it works fine on other team members even though we have the same ubuntu, PHP, and laravel version and <code>.env</code> file.</p>
<p>What I have tried:</p>
<ul>
<li>Run <code>composer install</code> and <code>composer update</code></li>
<li>Try different browsers such as firefox and chromium-based browsers</li>
<li>Run <code>php artisan storage:link</code></li>
<li>Restart apache2</li>
<li>Run <code>npm install</code> and <code>npm run dev</code></li>
</ul>
<p>I think there is some package or something missing.</p>
<p>List of paths I get from <code>dd($__data)</code>:</p>
```"path" => "/project-directory/project-name/app"
"path.base" => "/project-directory/project-name"
"path.lang" => "/project-directory/project-name/resources/lang"
"path.config" => "/project-directory/project-name/config"
"path.public" => "/project-directory/project-name/public"
"path.storage" => "/project-directory/project-name/storage"
"path.database" => "/project-directory/project-name/database"
"path.resources" => "/project-directory/project-name/resources"
"path.bootstrap" => "/project-directory/project-name/bootstrap"
```

答:
You need first run

```<code>php artisan storage:link
</code>```

For more details check https://laravel.com/docs/8.x/filesystem

Then you must be check your .env values.
Is correctly APP_URL=

Also in your exception is strange

```<code>/public/.../...
</code>```

Reason is wrong configuration.
First check your .env values like

```<code>APP_URL=...
FILESYSTEM_DRIVER=public
</code>```

then check config/filesystems.php

Title: Laravel cannot find public dir

Body:
I worked on a team and then clone the laravel/php codes from our repository. When I serve the laravel on localhost, it cannot find all the file inside the public directory and throw an error on the terminal:

[404]: GET /public/css/style.css - No such file or directory

Many answers to similar issues advise me to change the codes in the blade.php file. The problem is that I can't edit the blade.php because it works fine on other team members even though we have the same ubuntu, PHP, and laravel version and .env file.

What I have tried:

Run composer install and composer update

Try different browsers such as firefox and chromium-based browsers

Run php artisan storage:link

Restart apache2

Run npm install and npm run dev

I think there is some package or something missing.

List of paths I get from dd($__data):

"path" => "/project-directory/project-name/app"
"path.base" => "/project-directory/project-name"
"path.lang" => "/project-directory/project-name/resources/lang"
"path.config" => "/project-directory/project-name/config"
"path.public" => "/project-directory/project-name/public"
"path.storage" => "/project-directory/project-name/storage"
"path.database" => "/project-directory/project-name/database"
"path.resources" => "/project-directory/project-name/resources"
"path.bootstrap" => "/project-directory/project-name/bootstrap"

Body:
You need first run

php artisan storage:link

For more details check https://laravel.com/docs/8.x/filesystem

Then you must be check your .env values.
Is correctly APP_URL=

Also in your exception is strange

/public/.../...

Reason is wrong configuration.
First check your .env values like

APP_URL=...
FILESYSTEM_DRIVER=public

then check config/filesystems.php


问:
Resolving RVA's for Import and Export tables within a PE file
I am currently writing a PE parser/loader.
I have successfully loaded the PE file into memory using standard c file io, retrieved valid DOS and PE headers (the optional header) as well as gaining access to the PE's sections.
My next target is to gain access to the Export table to retrieve exported symbols.
To do this i have used the RVA stored in the optional headers data-dictionary array at index 0 (which i believe points to the export table) and added this address to the address of the PE file loaded into program memory, then casted this into a valid export table header. I am turning up NULL addresses and data when i do this. here is a small code snippet;

```<code>// RVA from optional headers data dictionaries array cast to Export directory type
  IMAGE_EXPORT_DIRECTORY* ied(
  (IMAGE_EXPORT_DIRECTORY*)((void*)
  ((unsigned char*)buffer + ioh->DataDirectory[0].VirtualAddress)));
</code>```

Do i have to use memory mapped IO to do this properly? Am i calculating the address wrong? Information on PE RVA's seems sparse.
thanks in advance.

答: I have written the python code to print all import and export functions of pe file. You will get the nice idea of how to do that in C. In data directory we have to check if the export directory rva and size is '0' or not. if not '0' we can proceed. You can use tool 'CFF explorer' from Nt core website. this is very good tool which will show how the data maps into export directory and then you can parse it easily. Here is the blog.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am currently writing a PE parser/loader.
I have successfully loaded the PE file into memory using standard c file io, retrieved valid DOS and PE headers (the optional header) as well as gaining access to the PE's sections.
My next target is to gain access to the Export table to retrieve exported symbols.
To do this i have used the RVA stored in the optional headers data-dictionary array at index 0 (which i believe points to the export table) and added this address to the address of the PE file loaded into program memory, then casted this into a valid export table header. I am turning up NULL addresses and data when i do this. here is a small code snippet;

// RVA from optional headers data dictionaries array cast to Export directory type
  IMAGE_EXPORT_DIRECTORY* ied(
  (IMAGE_EXPORT_DIRECTORY*)((void*)
  ((unsigned char*)buffer + ioh->DataDirectory[0].VirtualAddress)));

Do i have to use memory mapped IO to do this properly? Am i calculating the address wrong? Information on PE RVA's seems sparse.
thanks in advance.


问:
What is the best approach for this CRUD search page in ASP.NET
I'm building a heavily CRUD based ASP.NET website and I've got to the phase of the project where I'm trying to build a search webpage that shows the user different subsets of a certain important table based on parameters they enter such as dates and different text fields.

I can't use a fixed SQL statement, because depending on whether they search by date or by something else, the SQL would be different, so instead I have been generating a results list using a table web control that starts out invisible and then is filled and set to visible once the user identifies a search they want to make. I used a table control because its easy to create and modify in the code behind, and I was able to make the needed calls to the database and populate that table as required.

However, the second thing I need with this search page, is the ability to allow the user to select a record from the results and then go edit it using the rest of the CRUD based pages on the site. To do that, I created asp:buttons in the table and gave them all different ids and the same event handler. But since I created the buttons dynamically, it seems the event disappears on callback and my scheme fails, so I'm taking a second look at how to do this.

My current code for the events looks like:

```<code> tempcell = new TableCell();
 Button tempbutton = new Button();
 tempbutton.Text = "Go";
 tempbutton.ID = "gobutton" + rowN;
 tempbutton.Visible = true;
 tempbutton.Click += new EventHandler(tempbutton_Click);
 tempcell.Controls.Add(tempbutton);
 temprow.Cells.Add(tempcell);
</code>```

My results table is declared like this:

```<code><asp:Table ID="ResultTable" visible="false" runat="server"
GridLines="Both" CellSpacing="8">
</asp:Table>
</code>```

I'd like to be able to identify which record the user selected, so I can send that info on to another page. And of course, I still need to be able to generate results for several different search criteria. Currently I have date, template and code based searches that lead to different stored procedures and different parameters based on what the user has entered.

Any suggestions on this? It seems like the data grids and repeaters require SQL statements in advance to work properly, so I'm not sure how to use them, but if I could then the item command approach would work with the buttons.

答:
Your event will hook up successfully if the button is recreated in the page load event.

Otherwise, use a GridView.  It is the perfect solution for simple CRUD, and you can control it as much as you need.

OwnerDisplayName: Tony Peterson

Body:
I'm building a heavily CRUD based ASP.NET website and I've got to the phase of the project where I'm trying to build a search webpage that shows the user different subsets of a certain important table based on parameters they enter such as dates and different text fields.

I can't use a fixed SQL statement, because depending on whether they search by date or by something else, the SQL would be different, so instead I have been generating a results list using a table web control that starts out invisible and then is filled and set to visible once the user identifies a search they want to make. I used a table control because its easy to create and modify in the code behind, and I was able to make the needed calls to the database and populate that table as required.

However, the second thing I need with this search page, is the ability to allow the user to select a record from the results and then go edit it using the rest of the CRUD based pages on the site. To do that, I created asp:buttons in the table and gave them all different ids and the same event handler. But since I created the buttons dynamically, it seems the event disappears on callback and my scheme fails, so I'm taking a second look at how to do this.

My current code for the events looks like:

 tempcell = new TableCell();
 Button tempbutton = new Button();
 tempbutton.Text = "Go";
 tempbutton.ID = "gobutton" + rowN;
 tempbutton.Visible = true;
 tempbutton.Click += new EventHandler(tempbutton_Click);
 tempcell.Controls.Add(tempbutton);
 temprow.Cells.Add(tempcell);

My results table is declared like this:

<asp:Table ID="ResultTable" visible="false" runat="server"
GridLines="Both" CellSpacing="8">
</asp:Table>

I'd like to be able to identify which record the user selected, so I can send that info on to another page. And of course, I still need to be able to generate results for several different search criteria. Currently I have date, template and code based searches that lead to different stored procedures and different parameters based on what the user has entered.

Any suggestions on this? It seems like the data grids and repeaters require SQL statements in advance to work properly, so I'm not sure how to use them, but if I could then the item command approach would work with the buttons.

OwnerDisplayName: ck


问:
View and Set HTTP headers for Safari/Chrome
I'm testing an API and I would like to hit it with safari and see the raw json that's returned. The API requires a certain HTTP header be sent with every request. Is there a way in Safari or Chrome to set my http headers when visiting a URL?</p>

答:
The (currently experimental) WebRequest API lets you do view and modify headers: http://code.google.com/chrome/extensions/trunk/webRequest.html

It's pretty easy to view headers using onSendHeaders.

To edit headers, you'll need to block the request. This sample (from the docs linked to above) removes the User-Agent header from all requests:

```<code>chrome.experimental.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    delete details.requestHeaders['User-Agent'];
    return {requestHeaders: details.requestHeaders};
  },
  {},
["blocking"]);
</code>```

Body:
The (currently experimental) WebRequest API lets you do view and modify headers: http://code.google.com/chrome/extensions/trunk/webRequest.html

It's pretty easy to view headers using onSendHeaders.

To edit headers, you'll need to block the request. This sample (from the docs linked to above) removes the User-Agent header from all requests:

chrome.experimental.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    delete details.requestHeaders['User-Agent'];
    return {requestHeaders: details.requestHeaders};
  },
  {},
["blocking"]);


问:
How to update json value with dropdown list
Can anyone teach me how can I update json value using the the dropdown list.
In JavaScript

HTML:

<select id="currency" onchange="getSelectValue();">
    <option value="Singapore Dollar">Singapore Dollar</option>
    <option value="USD">USD</option>
    <option value="Malaysia Riggit">Malaysia Riggit</option>
</select>
```
<p>JSON :</p>
<pre class="lang-js prettyprint-override"><code>{
"products": [
    {
       "name": "Apple",
        "price": "2.50",
        "code": "SGD"
    },
    {
       "name": "Orange",
        "price": "2.50",
        "code": "SGD"
    }
]
}
</code>```

答:
You can create a select in javascript like this, focus on the

```
<p>EDIT:</p>
<p>Add the "value" as a param of the function</p>
```<select id="currency" onchange="getSelectValue(value)">
    <option value="SGD">Singapore Dollar</option>
    <option value="USD">USD</option>
    <option value="MR">Malaysia Riggit</option>
</select>
```
<p>and the function definition should look like this:</p>
```const getSelectValue = (selectedValue) => {
    console.log(selectedValue);
    // Your code...
};
```

Body:
Can anyone teach me how can I update json value using the the dropdown list.
In JavaScript

HTML:

<select id="currency" onchange="getSelectValue();">
    <option value="Singapore Dollar">Singapore Dollar</option>
    <option value="USD">USD</option>
    <option value="Malaysia Riggit">Malaysia Riggit</option>
</select>

JSON :

{
"products": [
    {
       "name": "Apple",
        "price": "2.50",
        "code": "SGD"
    },
    {
       "name": "Orange",
        "price": "2.50",
        "code": "SGD"
    }
]
}

Body:
You can create a select in javascript like this, focus on the <script />

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Javascript - Select</title>
</head>
<body>
    <div id="main"></div>
</body>
<script>
    const {products} = JSON.parse('{ "products": [ { "name": "Apple", "price": "2.50", "code": "SGD" }, { "name": "Orange", "price": "2.50", "code": "SGD" } ] }');

    const select = document.createElement("select");
    select.id = 'currency';
    select.onchange = ({target: {value}}) => console.log(value);

    products.forEach(({code, name}) => {
        const option = document.createElement("option");
        option.label = name;
        option.value = code;
        select.appendChild(option);
    });

    const main = document.getElementById('main');
    main.appendChild(select);
</script>
</html>

EDIT:

Add the "value" as a param of the function

<select id="currency" onchange="getSelectValue(value)">
    <option value="SGD">Singapore Dollar</option>
    <option value="USD">USD</option>
    <option value="MR">Malaysia Riggit</option>
</select>

and the function definition should look like this:

const getSelectValue = (selectedValue) => {
    console.log(selectedValue);
    // Your code...
};


问:
Flutter - Warning (CocoaPods not installed Skipping pod install) Even While Installed
I am trying to build a Flutter app with Geolocator plugin on Android Studio.
When I am running the app I have the following warning - that prevents the app from running:

Warning: CocoaPods not installed. Skipping pod install.
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.

I tried every solution i found in the internet (Stackoverflow & GitHub) but nothing seems to work.

Important: When I tried to run the app from Xcode instead of from Android Studio, I had this error:

The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

So what I did was - Change directory to ios (on the Flutter project) and running:

```<code>pod init
pod install
</code>```

Tried to run again from Xcode and it worked perfectly.
After it works on Xcode I tried to run it from Android Studio and the same error happens to me, preventing the app to launch.

Flutter Doctor:

```<code>[✓] Flutter (Channel stable, 2.2.2, on macOS 11.4 20F71 darwin-x64, locale en-IL)
    • Flutter version 2.2.2 at /Users/idanrefaeli/Developer/flutter
    • Framework revision d79295af24 (5 weeks ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/idanrefaeli/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.57.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.23.0

[✓] Connected device (2 available)
    • Idan’s (mobile) • 00008020-0011092101A2002E • ios            • iOS 14.6
    • Chrome (web)    • chrome                    • web-javascript • Google Chrome 91.0.4472.114

! Doctor found issues in 1 category.
</code>```

Extra logs:
'Run' log in Android Studio: pastebin.com/7iYtdcTQ
Also this terminal log after running 'pod install': pastebin.com/1cCNuFYM

-- UPDATE --

I finally was able to run the app, all I did was to copy all the project files to a new project from scratch and it worked.
Maybe it happened because of a certain conflict, since I imported someone else's project (from Angela Yu's Flutter Udemy course).
Anyway, I still didn't find a fix for this fraustrating problem so if anyone recognizes something it would be great!

答: As @islomkhuja-akhrarov mentioned it's an Android Studio Bumblebee problem, installing patch 1 helped</p>

Body:
I am trying to build a Flutter app with Geolocator plugin on Android Studio.
When I am running the app I have the following warning - that prevents the app from running:

Warning: CocoaPods not installed. Skipping pod install.
CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To install see https://guides.cocoapods.org/using/getting-started.html#installation for instructions.

Exception: CocoaPods not installed or not in valid state.

I tried every solution i found in the internet (Stackoverflow & GitHub) but nothing seems to work.

Important: When I tried to run the app from Xcode instead of from Android Studio, I had this error:

The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

So what I did was - Change directory to ios (on the Flutter project) and running:

pod init
pod install

Tried to run again from Xcode and it worked perfectly.
After it works on Xcode I tried to run it from Android Studio and the same error happens to me, preventing the app to launch.

Flutter Doctor:

[✓] Flutter (Channel stable, 2.2.2, on macOS 11.4 20F71 darwin-x64, locale en-IL)
    • Flutter version 2.2.2 at /Users/idanrefaeli/Developer/flutter
    • Framework revision d79295af24 (5 weeks ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/idanrefaeli/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5.1, Build version 12E507
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.57.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.23.0

[✓] Connected device (2 available)
    • Idan’s (mobile) • 00008020-0011092101A2002E • ios            • iOS 14.6
    • Chrome (web)    • chrome                    • web-javascript • Google Chrome 91.0.4472.114

! Doctor found issues in 1 category.

Extra logs:
'Run' log in Android Studio: pastebin.com/7iYtdcTQ
Also this terminal log after running 'pod install': pastebin.com/1cCNuFYM

-- UPDATE --

I finally was able to run the app, all I did was to copy all the project files to a new project from scratch and it worked.
Maybe it happened because of a certain conflict, since I imported someone else's project (from Angela Yu's Flutter Udemy course).
Anyway, I still didn't find a fix for this fraustrating problem so if anyone recognizes something it would be great!


问:
Unity WaitForSeconds Delay not Functioning
I'm making a rhythm game and and working on a script that spawns an object on every beat of a song. Thus, it spawns a single object, waits for the length of the beat, and then spawns the next one. It's supposed to do this until the song finishes. The issue is that the script seems to be spawning everyone of the objects at once, rather than waiting for the specified amount of time. The script compiles fine and I can't figure out what the issue is. Here's my script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spawnState : MonoBehaviour
{

    public float waitTime = 0.483870968f;
    public bool running = true;
    public int beats = 504;
    private int count = 0;

    public GameObject spawn;

    // Update is called once per frame
    void Update()
    {
        //Generate object

        while (running == true)
        {

            //Wait
            StartCoroutine(Wait());

            //Count & Stop
            count += 1;
            if (count >= beats)
            {
                running = false;
            }

        }
    }

    //Wait function
    IEnumerator Wait()
    {
        //Wait
        yield return new WaitForSeconds(waitTime);

        //Spawn
        Instantiate(spawn, transform.position, spawn.transform.rotation);

    }
}
</code>```

Thank you!

答:
For starters you don't want any possibly blocking while loop within Update!

Update is called once every frame.

Do you really want to instantiate 504 objects within one frame?

And then StartCoroutine does not delay the method which calls it. It rather registers a Coroutine to be running and continues immediately with the rest of the code. So you are starting 504 "parallel" running Coroutines and after 0.48.. seconds you suddenly get all 504 objects instantiated at the same time.

What you rather want to do would e.g. be either directly using a timer field without a Coroutine

```<code>private float timer;

void Update()
{
    if(!running) return;

    timer += Time.deltaTime;

    if(timer >= waitTime)
    {
        timer = 0;

        Instantiate(spawn, transform.position, spawn.transform.rotation);

        count += 1;
        if (count >= beats)
        {
            running = false;
        }
    }
}
</code>```

Or if you want to use a Coroutine you could e.g. simply do

```<code>private void Start ()
{
    StartCorouine (SpawnRoutine());
}

private IEnumerator SpawnRoutine ()
{
    for(var count = 0; count < beats; count++)
    {
        yield return new WaitForSeconds (waitTime);

        Instantiate(spawn, transform.position, spawn.transform.rotation);
    }
}
</code>```

or if Start is anyway the only place where you trigger this it can be that routine itself

```<code>private IEnumerator Start ()
{
    for(var count = 0; count < beats; count++)
    {
        yield return new WaitForSeconds (waitTime);

        Instantiate(spawn, transform.position, spawn.transform.rotation);
    }
}
</code>```

Body:
I'm making a rhythm game and and working on a script that spawns an object on every beat of a song. Thus, it spawns a single object, waits for the length of the beat, and then spawns the next one. It's supposed to do this until the song finishes. The issue is that the script seems to be spawning everyone of the objects at once, rather than waiting for the specified amount of time. The script compiles fine and I can't figure out what the issue is. Here's my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spawnState : MonoBehaviour
{

    public float waitTime = 0.483870968f;
    public bool running = true;
    public int beats = 504;
    private int count = 0;

    public GameObject spawn;

    // Update is called once per frame
    void Update()
    {
        //Generate object

        while (running == true)
        {

            //Wait
            StartCoroutine(Wait());

            //Count & Stop
            count += 1;
            if (count >= beats)
            {
                running = false;
            }

        }
    }

    //Wait function
    IEnumerator Wait()
    {
        //Wait
        yield return new WaitForSeconds(waitTime);

        //Spawn
        Instantiate(spawn, transform.position, spawn.transform.rotation);

    }
}

Thank you!

Body:
For starters you don't want any possibly blocking while loop within Update!

Update is called once every frame.

Do you really want to instantiate 504 objects within one frame?

And then StartCoroutine does not delay the method which calls it. It rather registers a Coroutine to be running and continues immediately with the rest of the code. So you are starting 504 "parallel" running Coroutines and after 0.48.. seconds you suddenly get all 504 objects instantiated at the same time.

What you rather want to do would e.g. be either directly using a timer field without a Coroutine

private float timer;

void Update()
{
    if(!running) return;

    timer += Time.deltaTime;

    if(timer >= waitTime)
    {
        timer = 0;

        Instantiate(spawn, transform.position, spawn.transform.rotation);

        count += 1;
        if (count >= beats)
        {
            running = false;
        }
    }
}

Or if you want to use a Coroutine you could e.g. simply do

private void Start ()
{
    StartCorouine (SpawnRoutine());
}

private IEnumerator SpawnRoutine ()
{
    for(var count = 0; count < beats; count++)
    {
        yield return new WaitForSeconds (waitTime);

        Instantiate(spawn, transform.position, spawn.transform.rotation);
    }
}

or if Start is anyway the only place where you trigger this it can be that routine itself

private IEnumerator Start ()
{
    for(var count = 0; count < beats; count++)
    {
        yield return new WaitForSeconds (waitTime);

        Instantiate(spawn, transform.position, spawn.transform.rotation);
    }
}


问:
Separate "for" loop iterations
How would I go about making each iteration of my four loop be random. The outcome as of now makes all 20 sentences put the same output, although it is choosing random words each time from the four arrays created in static class OuterWord. I have omitted the parts of the code that I don't think are necessary including the getMethods created for each array and sentence, hopefully that will not negatively effect my question.

`public class SentenceMaker {

```<code>static class OuterWord {
    //arrays
    String [] article = {"the", "a", "one", "some", "any"}; //array for articles
    String [] noun = {"boy", "girl", "dog", "town", "car"}; //array for nouns
    String [] verb = {"drove", "jumped", "ran", "walked", "skipped"}; //array for verbs
    String [] preposition = {"to", "from", "over", "under", "on"}; //array for prepositions

}
static class OuterSentence {
   int random = (int) (Math.random()*5);
    OuterWord word = new OuterWord();

    //sentence structure article-noun-verb-preposition-article-noun
    //StringBuilder with append, attempts to concatenate with .append
    //This code works as well
    StringBuilder sentence = new StringBuilder()
                    .append(word.article[random].substring(0, 1).toUpperCase())
                    .append(word.article[random].substring(1))
                    .append(" ")
                    .append(word.noun[random])
                    .append(" ")
                    .append(word.verb[random])
                    .append(" ")
                    .append(word.preposition[random])
                    .append(" ")
                    .append(word.article[random])
                    .append(" ")
                    .append(word.noun[random])
                    .append(".");
}

public static void main(String args[]) {
    //random element from arrays
    //int random = (int) (Math.random()*5);

    //instantiation of the Word and Sentence classes
    OuterWord word = new OuterWord();
    OuterSentence s = new OuterSentence();

    //loop initializer
    int counter = 0;

    //for loop for 20 iterations
    for(int i = 0; i < 20; i++){
        //counter to keep track of iterations
        counter = counter + 1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence " + counter + ": " + s.sentence.);
    }
}
</code>```

}`

答:
Just move the OuterSentence object to for loop.

```<code>for(int i = 0; i < 20; i++){
        OuterSentence s = new OuterSentence();
        //counter to keep track of iterations
        counter = counter + 1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence " + counter + ": " + s.sentence);
    }
</code>```

The above one is much readable or the other way is to just create the new object in the System.out.println statement like as follows:

```<code>System.out.println("Sentence " + counter + ": " + new OuterSentence().sentence);
</code>```

In both the ways we are creating a new object for every statement so that new random will get generated so that new sentence will be formed.

Title: Separate "for" loop iterations

Body:
How would I go about making each iteration of my four loop be random. The outcome as of now makes all 20 sentences put the same output, although it is choosing random words each time from the four arrays created in static class OuterWord. I have omitted the parts of the code that I don't think are necessary including the getMethods created for each array and sentence, hopefully that will not negatively effect my question.

`public class SentenceMaker {

static class OuterWord {
    //arrays
    String [] article = {"the", "a", "one", "some", "any"}; //array for articles
    String [] noun = {"boy", "girl", "dog", "town", "car"}; //array for nouns
    String [] verb = {"drove", "jumped", "ran", "walked", "skipped"}; //array for verbs
    String [] preposition = {"to", "from", "over", "under", "on"}; //array for prepositions

}
static class OuterSentence {
   int random = (int) (Math.random()*5);
    OuterWord word = new OuterWord();

    //sentence structure article-noun-verb-preposition-article-noun
    //StringBuilder with append, attempts to concatenate with .append
    //This code works as well
    StringBuilder sentence = new StringBuilder()
                    .append(word.article[random].substring(0, 1).toUpperCase())
                    .append(word.article[random].substring(1))
                    .append(" ")
                    .append(word.noun[random])
                    .append(" ")
                    .append(word.verb[random])
                    .append(" ")
                    .append(word.preposition[random])
                    .append(" ")
                    .append(word.article[random])
                    .append(" ")
                    .append(word.noun[random])
                    .append(".");
}

public static void main(String args[]) {
    //random element from arrays
    //int random = (int) (Math.random()*5);

    //instantiation of the Word and Sentence classes
    OuterWord word = new OuterWord();
    OuterSentence s = new OuterSentence();

    //loop initializer
    int counter = 0;

    //for loop for 20 iterations
    for(int i = 0; i < 20; i++){
        //counter to keep track of iterations
        counter = counter + 1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence " + counter + ": " + s.sentence.);
    }
}

}`

Body:
Just move the OuterSentence object to for loop.

for(int i = 0; i < 20; i++){
        OuterSentence s = new OuterSentence();
        //counter to keep track of iterations
        counter = counter + 1;
        //sentence article-noun-verb-preposition-article-noun
        System.out.println("Sentence " + counter + ": " + s.sentence);
    }

The above one is much readable or the other way is to just create the new object in the System.out.println statement like as follows:

System.out.println("Sentence " + counter + ": " + new OuterSentence().sentence);

In both the ways we are creating a new object for every statement so that new random will get generated so that new sentence will be formed.


问:
How to deactivate or override the Android "BACK" button, in Flutter?
Is there a way to deactivate the Android back button when on a specific page?

```<code>class WakeUpApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "Time To Wake Up ?",
      home: new WakeUpHome(),
      routes: <String, WidgetBuilder>{
        '/pageOne': (BuildContext context) => new pageOne(),
        '/pageTwo': (BuildContext context) => new pageTwo(),
      },
    );
  }
}
</code>```

On pageOne I have a button to go to pageTwo:

```<code>new FloatingActionButton(
  onPressed: () {
    Navigator.of(context).pushNamed('/pageTwo');
  },
)
</code>```

My problem is that if I press the Back arrow at the bottom of the android screen, I go back to pageOne. I would like this button to not show up at all.
Ideally, I would like to have no possible way out of this screen unless the user for example keeps his finger pressed on the screen for 5 seconds. (I am trying to write an App for toddlers, and would like only the parents to be able to navigate out of the particular screen).

答:
Using generated route you can return to destination page by doing this-</p>
```<code>AppBar(
        leading: new IconButton(
        icon: new Icon(Icons.arrow_back),
         onPressed: () {
         Navigator.of(context) .pushNamedAndRemoveUntil(AppRouter.dashboard, (route) => false);
         }),
       )
</code>```

Body:
Is there a way to deactivate the Android back button when on a specific page?

class WakeUpApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: "Time To Wake Up ?",
      home: new WakeUpHome(),
      routes: <String, WidgetBuilder>{
        '/pageOne': (BuildContext context) => new pageOne(),
        '/pageTwo': (BuildContext context) => new pageTwo(),
      },
    );
  }
}

On pageOne I have a button to go to pageTwo:

new FloatingActionButton(
  onPressed: () {
    Navigator.of(context).pushNamed('/pageTwo');
  },
)

My problem is that if I press the Back arrow at the bottom of the android screen, I go back to pageOne. I would like this button to not show up at all.
Ideally, I would like to have no possible way out of this screen unless the user for example keeps his finger pressed on the screen for 5 seconds. (I am trying to write an App for toddlers, and would like only the parents to be able to navigate out of the particular screen).

Body:
Using generated route you can return to destination page by doing this-

AppBar(
        leading: new IconButton(
        icon: new Icon(Icons.arrow_back),
         onPressed: () {
         Navigator.of(context) .pushNamedAndRemoveUntil(AppRouter.dashboard, (route) => false);
         }),
       )


问:
Trying to run a calculation inside an if-else statement and it's stalling - C
I'm in an introductory code class for C and I'm trying to run this square and cube calculation if a number greater than 1 is entered, but it stalls if I run it. I'm not getting any errors and I've tried different ways to make this work through tips here, but nothing is happening and I don't know enough to get what's wrong.</p>
```<code>#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", &square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}
</code>```

答:
Add & in scanf, remove & while printing. The & operator evaluates to the memory location of the variable. In scanf we are supposed to use &, so that the input is stored in the memory address obtained by writing &var.

Exit the program after printing the square and cube, or place the next printf in an else block.

#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", &num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
        return 0;
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}
```

Body:
I'm in an introductory code class for C and I'm trying to run this square and cube calculation if a number greater than 1 is entered, but it stalls if I run it. I'm not getting any errors and I've tried different ways to make this work through tips here, but nothing is happening and I don't know enough to get what's wrong.

#include <stdio.h>

int main ()
{
    int num, square, cube;

    printf("What is your number? ");
    scanf("%d", num);

    if (num > 1)
    {
        square = num * num;
        cube = num * num * num;

        printf("\nThe square of your number is ");
        printf("%d", &square);
        printf(" and the cube of your number is ");
        printf("%d", cube);
        printf(".");
    }

    printf("\nPlease enter a number greater than 1.");

    return 0;
}