问:
Dynamic tag name in React JSX
I am trying to write a React component for HTML heading tags (h1, h2, h3, etc.), where the heading level is specified via a prop.

I tried to do it like this:

```<code><h{this.props.level}>Hello</h{this.props.level}>
</code>```

And I expected output like:

```<code><h1>Hello</h1>
</code>```

But this is not working.

Is there any way to do this?

答:
All the other answers are working fine but I would add some extra, because by doing this:

It is a bit safer. Even if your type-checking is failing you still
return a proper component.

It is more declarative. Anybody by looking at this component can see what it could return.

Its is more flexible for example instead of 'h1', 'h2', ... for type of your Heading you can have some other abstract concepts 'sm', 'lg' or 'primary', 'secondary'

The Heading component:

```<code>import React from 'react';

const elements = {
  h1: 'h1',
  h2: 'h2',
  h3: 'h3',
  h4: 'h4',
  h5: 'h5',
  h6: 'h6',
};

function Heading({ type, children, ...props }) {
  return React.createElement(
    elements[type] || elements.h1,
    props,
    children
  );
}

Heading.defaultProps = {
  type: 'h1',
};

export default Heading;
</code>```

Which you can use it like

```<code><Heading type="h1">Some Heading</Heading>
</code>```

or you can have a different abstract concept, for example you can define a size props like:

```<code>import React from 'react';

const elements = {
  xl: 'h1',
  lg: 'h2',
  rg: 'h3',
  sm: 'h4',
  xs: 'h5',
  xxs: 'h6',
};

function Heading({ size, children }) {
  return React.createElement(
    elements[size] || elements.rg,
    props,
    children
  );
}

Heading.defaultProps = {
  size: 'rg',
};

export default Heading;
</code>```

Which you can use it like

```<code><Heading size="sm">Some Heading</Heading>
</code>```

Title: Dynamic tag name in React JSX

Body:
I am trying to write a React component for HTML heading tags (h1, h2, h3, etc.), where the heading level is specified via a prop.

I tried to do it like this:

<h{this.props.level}>Hello</h{this.props.level}>

And I expected output like:

Hello

But this is not working.

Is there any way to do this?

Body:
All the other answers are working fine but I would add some extra, because by doing this:

It is a bit safer. Even if your type-checking is failing you still
return a proper component.

It is more declarative. Anybody by looking at this component can see what it could return.

Its is more flexible for example instead of 'h1', 'h2', ... for type of your Heading you can have some other abstract concepts 'sm', 'lg' or 'primary', 'secondary'

The Heading component:

import React from 'react';

const elements = {
  h1: 'h1',
  h2: 'h2',
  h3: 'h3',
  h4: 'h4',
  h5: 'h5',
  h6: 'h6',
};

function Heading({ type, children, ...props }) {
  return React.createElement(
    elements[type] || elements.h1,
    props,
    children
  );
}

Heading.defaultProps = {
  type: 'h1',
};

export default Heading;

Which you can use it like

<Heading type="h1">Some Heading</Heading>

or you can have a different abstract concept, for example you can define a size props like:

import React from 'react';

const elements = {
  xl: 'h1',
  lg: 'h2',
  rg: 'h3',
  sm: 'h4',
  xs: 'h5',
  xxs: 'h6',
};

function Heading({ size, children }) {
  return React.createElement(
    elements[size] || elements.rg,
    props,
    children
  );
}

Heading.defaultProps = {
  size: 'rg',
};

export default Heading;

Which you can use it like

<Heading size="sm">Some Heading</Heading>


来源: stackexchange

问:
How to add ggproto objects together and save for later without call to ggplot()?
I would like to save some specifications of a ggplot command for later, given that I need to run several different graphs that all share some scale aesthetics.

Let's say I would like save this for later:

```<code>my.scale_aes <- scale_x_continuous(...) + scale_color_manual(...)
</code>```

This would of course prompt an error message, indicating that you cannot add ggproto objects together without a direct ggplot() call. But is that really the case? And is there another way by which I could still add these components together?

I read somewhere else that it has to do with the different methods of adding elements together: methods("+") and that what I need has something to do with +.gg* but I have no idea how to implement this and how to make it work.

答:
You can do this by defining a list of the ggplot terms you want and adding them in.

```<code>library(ggplot2)

my.scales <- list(
  scale_x_continuous(breaks = c(56, 60, 61)),
  scale_color_manual(values = c("black", "red"))
)

ggplot(data = diamonds[1:100,],
       aes(depth, price, color = cut == "Ideal")) +
  geom_point() +
  my.scales

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to save some specifications of a ggplot command for later, given that I need to run several different graphs that all share some scale aesthetics.

Let's say I would like save this for later:

my.scale_aes <- scale_x_continuous(...) + scale_color_manual(...)

This would of course prompt an error message, indicating that you cannot add ggproto objects together without a direct ggplot() call. But is that really the case? And is there another way by which I could still add these components together?

I read somewhere else that it has to do with the different methods of adding elements together: methods("+") and that what I need has something to do with +.gg* but I have no idea how to implement this and how to make it work.

Body:
You can do this by defining a list of the ggplot terms you want and adding them in.

library(ggplot2)

my.scales <- list(
  scale_x_continuous(breaks = c(56, 60, 61)),
  scale_color_manual(values = c("black", "red"))
)

ggplot(data = diamonds[1:100,],
       aes(depth, price, color = cut == "Ideal")) +
  geom_point() +
  my.scales


问:
Resize image before sending
I want to have a route with gin that will send an image (jpeg) as the response but instead of sending the original image that's saved to disk I would like to resize it first (to thumbnail size).

So far I can send images using c.File(filepath string) but that doesn't allow me to resize the image. Is there any way to do that without having to create a new file on the disk?

答:
Yes, you can just resize it using built in package "image", i just built it for you, with different resize options and bytes / pure image output, pick what you want. I didnt use this particular package in the past, so any correction / recommendation for this pice of code is welcome. code:</p>

```<code>package main

import (
    "bytes"
    "image"
    "image/color"
    "image/draw"
    "image/jpeg"
    "io/ioutil"
    "log"
    "math"
    "os"
)

func main() {
    f, err := os.Open("resources/image.jpg")
    if err != nil {
        log.Fatal(err)
    }

    //encoding message is discarded, because OP wanted only jpg, else use encoding in resize function
    img, _, err := image.Decode(f)
    if err != nil {
        log.Fatal(err)
    }

    //this is the resized image
    resImg := resize(img, 20, 20)

    //this is the resized image []bytes
    imgBytes := imgToBytes(resImg)

    //optional written to file
    err = ioutil.WriteFile("resources/test.jpg", imgBytes, 0777)
    if err != nil {
        log.Fatal(err)
    }
}

func resize(img image.Image, length int, width int) image.Image {
    //truncate pixel size
    minX := img.Bounds().Min.X
    minY := img.Bounds().Min.Y
    maxX := img.Bounds().Max.X
    maxY := img.Bounds().Max.Y
    for (maxX-minX)%length != 0 {
        maxX--
    }
    for (maxY-minY)%width!= 0 {
        maxY--
    }
    scaleX := (maxX - minX) / length
    scaleY := (maxY - minY) / width

    imgRect := image.Rect(0, 0, length, width)
    resImg := image.NewRGBA(imgRect)
    draw.Draw(resImg, resImg.Bounds(), &image.Uniform{C: color.White}, image.ZP, draw.Src)
    for y := 0; y < width; y += 1 {
        for x := 0; x < length; x += 1 {
            averageColor := getAverageColor(img, minX+x*scaleX, minX+(x+1)*scaleX, minY+y*scaleY, minY+(y+1)*scaleY)
            resImg.Set(x, y, averageColor)
        }
    }
    return resImg
}

func getAverageColor(img image.Image, minX int, maxX int, minY int, maxY int) color.Color {
    var averageRed float64
    var averageGreen float64
    var averageBlue float64
    var averageAlpha float64
    scale := 1.0 / float64((maxX-minX)*(maxY-minY))

    for i := minX; i < maxX; i++ {
        for k := minY; k < maxY; k++ {
            r, g, b, a := img.At(i, k).RGBA()
            averageRed += float64(r) * scale
            averageGreen += float64(g) * scale
            averageBlue += float64(b) * scale
            averageAlpha += float64(a) * scale
        }
    }

    averageRed = math.Sqrt(averageRed)
    averageGreen = math.Sqrt(averageGreen)
    averageBlue = math.Sqrt(averageBlue)
    averageAlpha = math.Sqrt(averageAlpha)

    averageColor := color.RGBA{
        R: uint8(averageRed),
        G: uint8(averageGreen),
        B: uint8(averageBlue),
        A: uint8(averageAlpha)}

    return averageColor
}

func imgToBytes(img image.Image) []byte {
    var opt jpeg.Options
    opt.Quality = 80

    buff := bytes.NewBuffer(nil)
    err := jpeg.Encode(buff, img, &opt)
    if err != nil {
        log.Fatal(err)
    }

    return buff.Bytes()
}

</code>```

Title: Resize image before sending

Body:
Yes, you can just resize it using built in package "image", i just built it for you, with different resize options and bytes / pure image output, pick what you want. I didnt use this particular package in the past, so any correction / recommendation for this pice of code is welcome. code:

package main

import (
    "bytes"
    "image"
    "image/color"
    "image/draw"
    "image/jpeg"
    "io/ioutil"
    "log"
    "math"
    "os"
)

func main() {
    f, err := os.Open("resources/image.jpg")
    if err != nil {
        log.Fatal(err)
    }

    //encoding message is discarded, because OP wanted only jpg, else use encoding in resize function
    img, _, err := image.Decode(f)
    if err != nil {
        log.Fatal(err)
    }

    //this is the resized image
    resImg := resize(img, 20, 20)

    //this is the resized image []bytes
    imgBytes := imgToBytes(resImg)

    //optional written to file
    err = ioutil.WriteFile("resources/test.jpg", imgBytes, 0777)
    if err != nil {
        log.Fatal(err)
    }
}

func resize(img image.Image, length int, width int) image.Image {
    //truncate pixel size
    minX := img.Bounds().Min.X
    minY := img.Bounds().Min.Y
    maxX := img.Bounds().Max.X
    maxY := img.Bounds().Max.Y
    for (maxX-minX)%length != 0 {
        maxX--
    }
    for (maxY-minY)%width!= 0 {
        maxY--
    }
    scaleX := (maxX - minX) / length
    scaleY := (maxY - minY) / width

    imgRect := image.Rect(0, 0, length, width)
    resImg := image.NewRGBA(imgRect)
    draw.Draw(resImg, resImg.Bounds(), &image.Uniform{C: color.White}, image.ZP, draw.Src)
    for y := 0; y < width; y += 1 {
        for x := 0; x < length; x += 1 {
            averageColor := getAverageColor(img, minX+x*scaleX, minX+(x+1)*scaleX, minY+y*scaleY, minY+(y+1)*scaleY)
            resImg.Set(x, y, averageColor)
        }
    }
    return resImg
}

func getAverageColor(img image.Image, minX int, maxX int, minY int, maxY int) color.Color {
    var averageRed float64
    var averageGreen float64
    var averageBlue float64
    var averageAlpha float64
    scale := 1.0 / float64((maxX-minX)*(maxY-minY))

    for i := minX; i < maxX; i++ {
        for k := minY; k < maxY; k++ {
            r, g, b, a := img.At(i, k).RGBA()
            averageRed += float64(r) * scale
            averageGreen += float64(g) * scale
            averageBlue += float64(b) * scale
            averageAlpha += float64(a) * scale
        }
    }

    averageRed = math.Sqrt(averageRed)
    averageGreen = math.Sqrt(averageGreen)
    averageBlue = math.Sqrt(averageBlue)
    averageAlpha = math.Sqrt(averageAlpha)

    averageColor := color.RGBA{
        R: uint8(averageRed),
        G: uint8(averageGreen),
        B: uint8(averageBlue),
        A: uint8(averageAlpha)}

    return averageColor
}

func imgToBytes(img image.Image) []byte {
    var opt jpeg.Options
    opt.Quality = 80

    buff := bytes.NewBuffer(nil)
    err := jpeg.Encode(buff, img, &opt)
    if err != nil {
        log.Fatal(err)
    }

    return buff.Bytes()
}


问:
"unexpected console statement no-console"
I'm getting this error in Brackets.

I want to stress the fact that it's literally the second time I opened a JS file.
As I stressed It I want also to emphasize the fact that I have no clue what Eslint and node.js are.

All the fixes on the StackOverflow and other sites assume knowing how abovementioned entities work.

Please help to a complete newb to fix the problem and learn something new.

Thank you in advance!

Here's the piece of code, but I don't think it will help with anything.

Html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript</title>

</head>
<body>
<h1>Javascript starter</h1>

    <script src=Script.js> </script>
</body>
</html>
</code>```

Javascript:

```<code>var now = 2018;
var yearJohn = 1989;
var fullAge = 18;

//Multiple operators
var isFullAge = now - yearJohn >= fullAge; //true
сonsole.log(isFullAge);

//Grouping

    var ageJohn = now - yearJohn;
    var ageMark = 35;
    var average = (ageJohn + ageMark)/2;
    console.log(average);

    // Multiple assigments
    var x, y;
    x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26

    console.log(x, y);

    // More operators
    x *= 2;
    console.log(x);
    x += 10;
    // eslint-disable-next-line no-console
    console.log(x);
</code>```

答:
Please try to change  console.log  to  document.write

and then open your html file in browser

```<code>var now = 2018;
var yearJohn = 1989;
var fullAge = 18;

//Multiple operators
var isFullAge = now - yearJohn >= fullAge; //true
document.write(isFullAge);

//Grouping

var ageJohn = now - yearJohn;
var ageMark = 35;
var average = (ageJohn + ageMark)/2;
document.write(average);

// Multiple assigments
var x, y;
x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26

document.write(x, y);

// More operators
x *= 2;
document.write(x);
x += 10;
// eslint-disable-next-line no-console
document.write(x);
</code>```

Body:
I'm getting this error in Brackets.

I want to stress the fact that it's literally the second time I opened a JS file.
As I stressed It I want also to emphasize the fact that I have no clue what Eslint and node.js are.

All the fixes on the StackOverflow and other sites assume knowing how abovementioned entities work.

Please help to a complete newb to fix the problem and learn something new.

Thank you in advance!

Here's the piece of code, but I don't think it will help with anything.

Html:

<!DOCTYPE html>

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

Javascript starter

Javascript:

var now = 2018;
var yearJohn = 1989;
var fullAge = 18;

//Multiple operators
var isFullAge = now - yearJohn >= fullAge; //true
сonsole.log(isFullAge);

//Grouping

    var ageJohn = now - yearJohn;
    var ageMark = 35;
    var average = (ageJohn + ageMark)/2;
    console.log(average);

    // Multiple assigments
    var x, y;
    x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26

    console.log(x, y);

    // More operators
    x *= 2;
    console.log(x);
    x += 10;
    // eslint-disable-next-line no-console
    console.log(x);

Body:
Please try to change  console.log  to  document.write

and then open your html file in browser

var now = 2018;
var yearJohn = 1989;
var fullAge = 18;

//Multiple operators
var isFullAge = now - yearJohn >= fullAge; //true
document.write(isFullAge);

//Grouping

var ageJohn = now - yearJohn;
var ageMark = 35;
var average = (ageJohn + ageMark)/2;
document.write(average);

// Multiple assigments
var x, y;
x = y = (3 + 5) * 4 - 6; // 8 * 4 - 6 // 32 - 6 // 26

document.write(x, y);

// More operators
x *= 2;
document.write(x);
x += 10;
// eslint-disable-next-line no-console
document.write(x);


问:
How can I get an image inside another div element to react on hover on the outermost div element?
I have a page where I have a Wordpress plugin WPDATATABLES using HTML to display some information that I'm pulling from various sites (importXML). The idea is for the page to look something like this https://www.labelradar.com/labels/chillyourmind/profile, that when you over over a particular element, the entire element reacts and changes into a white logo with the main color of the social media icon. Currently, I am able to get all the CSS working except for one small detail, and that's the white icon. It only changes when you are within range of the image outline of the icon.

Here's the page: https://trapparty.net/theparty/

I know there must be someway to force the div to react at the same time when I hover on the outermost div element controlling the entire thing. Here's a pastbin of the entire CSS code I'm using:

https://www.pastiebin.com/5cf313feb2753

And below is one HTML element with the nested DIV elements.

I've tried combining some CSS like this to try and call the div on the outside:

```<code>.soundcloud.soundcloudicon .soundcloudwhite {
    display: none;
    position: absolute;
    top: 0px;
    left: 0;
    z-index: 99;
}

<center><a href="https://www.instagram.com/thetrapparty/" target="_blank"><div class="instagram"><div class="instagramicon">

<center><img src="https://www.trapparty.net/wp-content/followicons/instagram.png" height="263" width="178" alt="instagram">
        </center>
<center><img src="https://www.trapparty.net/wp-content/followicons/instagramwhite.png" height="263" width="178"  class="instagramwhite" alt="instagramwhite"></center>
    </div>
<div class="igcount"><h2><center><font color="white">47.4k</font></center></h2></div>
<div class="followerstextig">Followers</div></div></a></center>
</code>```

The actual result I'd like can be seen in the Label Radar link above, but essentially, I want the white icon to show up whenever I hover over the entire  outer div element.

答:
Reading the title it would be something like:</p>

```<code>div img {
  border: 1px solid black;
}

div:hover img {
  border: 1px solid red;
}
</code>```

Body:
I have a page where I have a Wordpress plugin WPDATATABLES using HTML to display some information that I'm pulling from various sites (importXML). The idea is for the page to look something like this https://www.labelradar.com/labels/chillyourmind/profile, that when you over over a particular element, the entire element reacts and changes into a white logo with the main color of the social media icon. Currently, I am able to get all the CSS working except for one small detail, and that's the white icon. It only changes when you are within range of the image outline of the icon.

Here's the page: https://trapparty.net/theparty/

I know there must be someway to force the div to react at the same time when I hover on the outermost div element controlling the entire thing. Here's a pastbin of the entire CSS code I'm using:

https://www.pastiebin.com/5cf313feb2753

And below is one HTML element with the nested DIV elements.

I've tried combining some CSS like this to try and call the div on the outside:

.soundcloud.soundcloudicon .soundcloudwhite {
    display: none;
    position: absolute;
    top: 0px;
    left: 0;
    z-index: 99;
}

47.4k

Followers

The actual result I'd like can be seen in the Label Radar link above, but essentially, I want the white icon to show up whenever I hover over the entire  outer div element.

Body:
Reading the title it would be something like:

div img {
  border: 1px solid black;
}

div:hover img {
  border: 1px solid red;
}


问:
Input prompt is being displayed under program output on zyBooks. Is this my mistake?
Have I made a mistake here, or is this an error within zyBooks? It will not allow me to get full marks, as the input prompt is being displayed with the print statement in the program output, and it is specifically asking only for the print statement.

```<code>user_name = (input('What is your first name?'))
print('Hello', user_name, 'and welcome to CS Online!')
</code>```

Here is the result, and then the result that it is expecting.

https://i.imgur.com/rddXBUR.png (The result)

https://i.imgur.com/Zuysq1r.png (The expected result)

答:
input's prompt parameter is printed to stdout. So simply remove it.

```<code>user_name = input()
</code>```

Body:
Have I made a mistake here, or is this an error within zyBooks? It will not allow me to get full marks, as the input prompt is being displayed with the print statement in the program output, and it is specifically asking only for the print statement.

user_name = (input('What is your first name?'))
print('Hello', user_name, 'and welcome to CS Online!')

Here is the result, and then the result that it is expecting.

https://i.imgur.com/rddXBUR.png (The result)

https://i.imgur.com/Zuysq1r.png (The expected result)

Body:
input's prompt parameter is printed to stdout. So simply remove it.

user_name = input()


问:
How can I get two different events with "querySelectorAll" for each element?
I have a probleme with my code. Now if I click the first element, all elements will become red, if I click second time they will become green. I would like have two independent events for each element with class fa-heart. I will explain better: If I click the first time the first element DOM, only this element will become red, and if I click it second time, it will become green, and so for all the others. I apologize if my request is not clear. Thank you so much for your help.</p>

```<code><script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a onclick="change()"><i class="fas fa-heart"></i></a>
<a onclick="change()"><i class="fas fa-heart"></i></a>
<a onclick="change()"><i class="fas fa-heart"></i></a>

<script>
 function change(){
      var a = document.querySelectorAll('.fa-heart');
      var qty = a.length;
      var i = 0;

      for(i; i<qty; i++){
         if(a[i].style.color !== 'red'){
             a[i].style.color = 'red';
         }else{
             a[i].style.color='green';
           }
     }
}
</script>
</code>```

答:
Add an individual listener to each  instead, and in the listener, check the current .style of the clicked element to figure out what to assign next:

document.querySelectorAll('.fa-heart').forEach((i) => {
  i.addEventListener('click', () => {
    i.style.color = i.style.color !== 'red'
      ? 'red'
      : 'green';
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a></code>```

Or, with event delegation:

document.addEventListener('click', (e) => {
  if (!e.target.matches('.fa-heart')) {
    return;
  }
  e.target.style.color = e.target.style.color !== 'red'
    ? 'red'
    : 'green';
});

console.log('start');
setTimeout(() => {
  console.log('adding dynamic elements');
  document.body.innerHTML += `

`;
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://kit.fontawesome.com/a1d70a0cda.js"></script></code>```

If you must use inline handlers (which you shouldn't), pass the this (the clicked element) to the listener:

function change(i) {
  i.style.color = i.style.color !== 'red'
    ? 'red'
    : 'green';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<i class="fas fa-heart"></i>
<i class="fas fa-heart"></i>
<i class="fas fa-heart"></i></code>```

Body:
Add an individual listener to each <i> instead, and in the listener, check the current .style of the clicked element to figure out what to assign next:

document.querySelectorAll('.fa-heart').forEach((i) => {
  i.addEventListener('click', () => {
    i.style.color = i.style.color !== 'red'
      ? 'red'
      : 'green';
  });
});

<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>

Or, with event delegation:

document.addEventListener('click', (e) => {
  if (!e.target.matches('.fa-heart')) {
    return;
  }
  e.target.style.color = e.target.style.color !== 'red'
    ? 'red'
    : 'green';
});

console.log('start');
setTimeout(() => {
  console.log('adding dynamic elements');
  document.body.innerHTML += `<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>
<a><i class="fas fa-heart"></i></a>`;
}, 1000);

<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>

If you must use inline handlers (which you shouldn't), pass the this (the clicked element) to the listener:

function change(i) {
  i.style.color = i.style.color !== 'red'
    ? 'red'
    : 'green';
}

<script src="https://kit.fontawesome.com/a1d70a0cda.js"></script>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>
<a onclick="change(this)"><i class="fas fa-heart"></i></a>


问:
Average finder always prints “0”
I am trying to create a program which finds the average of a set of data which someone enters. I have tried using this code:

```<code>var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
  var newdata = prompt("Enter a piece of data (must be a number)");
  data.push(newdata);
  var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
  while (i < data.length) {
    total + data[i];
    i++;
  }
  var average = total / data.length;
  document.write(average);
}
</code>```

However, when I run it, no matter what I put in, it always prints “0”. Thank you in advance for your help.

答:
The problem is in the line

```<code>total + data[i];
</code>```

This code will be executed at some result will be generated. But then nothing happens to that value. In javascript Numbers are primitive types. Except objects all data types object. You can't mutate them with =(assigning them to a value).

You need to use assignment expression.

```<code>total = total + data[i];
</code>```

Or the short for that will be

```<code>total += data[i];
</code>```

Another problem is that you are not converting the result of prompt() to a Number. Use Unary Plus + to convert string to number.

Below is corrected version of your code.

var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
  var newdata = +prompt("Enter a piece of data (must be a number)");
  data.push(newdata);
  var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
  while (i < data.length) {
    total += data[i];
    i++;
  }
  var average = total / data.length;
  document.write(average);
}```
</div>
</div>
</p>

<p>A cleaner and better version can be achieved using <code>do-while</code> and <code>reduce()</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [];
var yesno;
do{
  var newdata = +prompt("Enter a piece of data (must be a number)");
  yesno = confirm("Would you like to add more data?");
  data.push(newdata);
}
while (yesno);
var total = data.reduce((ac,a) => ac + a,0);
var average = total / data.length;
document.write(average);</code>```

Title: Average finder always prints “0”

Body:
I am trying to create a program which finds the average of a set of data which someone enters. I have tried using this code:

var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
  var newdata = prompt("Enter a piece of data (must be a number)");
  data.push(newdata);
  var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
  while (i < data.length) {
    total + data[i];
    i++;
  }
  var average = total / data.length;
  document.write(average);
}

However, when I run it, no matter what I put in, it always prints “0”. Thank you in advance for your help.

Body:
The problem is in the line

total + data[i];

This code will be executed at some result will be generated. But then nothing happens to that value. In javascript Numbers are primitive types. Except objects all data types object. You can't mutate them with =(assigning them to a value).

You need to use assignment expression.

total = total + data[i];

Or the short for that will be

total += data[i];

Another problem is that you are not converting the result of prompt() to a Number. Use Unary Plus + to convert string to number.

Below is corrected version of your code.

var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
  var newdata = +prompt("Enter a piece of data (must be a number)");
  data.push(newdata);
  var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
  while (i < data.length) {
    total += data[i];
    i++;
  }
  var average = total / data.length;
  document.write(average);
}

A cleaner and better version can be achieved using do-while and reduce()

var data = [];
var yesno;
do{
  var newdata = +prompt("Enter a piece of data (must be a number)");
  yesno = confirm("Would you like to add more data?");
  data.push(newdata);
}
while (yesno);
var total = data.reduce((ac,a) => ac + a,0);
var average = total / data.length;
document.write(average);


问:
verify device phone number on android
i am writing an app that will use persons phone number (on a device) to identify the user on my network. what methods can i use to verify that the phone number retrieved from the device is real and not spoofed. i came up with two methods to do it but both of them require use of SMS:

sending SMS from a device to my server

sending SMS from my server to a device and intercepting it with my app

are there any other methods, i would like to omit using SMS if possible.

thanks

答: i think i found the best way to go about it. basically, i will have my app send a special text message to itself, the phone number of the device. i will of course notify the user that this will occur. my application will then intercept the SMS and will know that the number is all good. this should do it...</p>

ContentLicense: CC BY-SA 2.5

Title: verify device phone number on android

ContentLicense: CC BY-SA 3.0


问:
SSAS named calculation referencing another table
I'm doing a multidimensional analysis in the SSAS VS tool. I have two tables, animal animal_intake. Animal is identified with animal_id and animal_intake references animal using animal_id. What I want to acomplish id to create named calculation in view that will have the information about the age of animal at the intake day. In order to calculate age, I have to reference animal birth date in animal_intake named calculation. Based on solution described in documentation [https://learn.microsoft.com/en-us/sql/analysis-services/multidimensional-models/define-named-calculations-in-a-data-source-view-analysis-services?view=sql-server-2017#creating-named-calculations] I have created following query for named calculation

```<code>(SELECT [ANIMAL].[birth_date] FROM [ANIMAL] WHERE [ANIMAL].[animal_id] =[animal_id])
</code>```

just to get access to animal birthdate. Unfortunately, when I click "explore data" VS presents following error

```<code>Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

#
</code>```

I don't understand what is the problem - animal_id is a primary key of ANIMAL table and birth_date field has NOT NULLconstraint. Therefore for given naimal_id there has to be exactly one result for the query.

Here are simplified tables from my db.

ANIMAL

```<code>CREATE TABLE [ANIMAL] (
    [animal_id] CHAR(7) PRIMARY KEY,
    [birth_date] DATE REFERENCES [DATE]([exact_date]) NOT NULL
);
</code>```

ANIMAL_INTAKE

```<code>CREATE TABLE [ANIMAL_INTAKE] (
    [animal_id] CHAR(7) NOT NULL REFERENCES [ANIMAL],
    [stay_number] TINYINT NOT NULL,
    [intake_date] DATE REFERENCES [DATE]([exact_date]) NOT NULL,
    PRIMARY KEY ([animal_id], [stay_number]),
);
</code>```

答:
Try the following:

```<code>(SELECT [ANIMAL].[birth_date] FROM [ANIMAL] WHERE [ANIMAL].[animal_id] = [ANIMAL_INTAKE].[animal_id])
</code>```

I’m assuming that your table in the DSV is named ANIMAL_INTAKE and that’s the table you are putting your named calculation on.

Body:
I'm doing a multidimensional analysis in the SSAS VS tool. I have two tables, animal animal_intake. Animal is identified with animal_id and animal_intake references animal using animal_id. What I want to acomplish id to create named calculation in view that will have the information about the age of animal at the intake day. In order to calculate age, I have to reference animal birth date in animal_intake named calculation. Based on solution described in documentation [https://learn.microsoft.com/en-us/sql/analysis-services/multidimensional-models/define-named-calculations-in-a-data-source-view-analysis-services?view=sql-server-2017#creating-named-calculations] I have created following query for named calculation

(SELECT [ANIMAL].[birth_date] FROM [ANIMAL] WHERE [ANIMAL].[animal_id] =[animal_id])

just to get access to animal birthdate. Unfortunately, when I click "explore data" VS presents following error

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

#

I don't understand what is the problem - animal_id is a primary key of ANIMAL table and birth_date field has NOT NULLconstraint. Therefore for given naimal_id there has to be exactly one result for the query.

Here are simplified tables from my db.

ANIMAL

CREATE TABLE [ANIMAL] (
    [animal_id] CHAR(7) PRIMARY KEY,
    [birth_date] DATE REFERENCES [DATE]([exact_date]) NOT NULL
);

ANIMAL_INTAKE

CREATE TABLE [ANIMAL_INTAKE] (
    [animal_id] CHAR(7) NOT NULL REFERENCES [ANIMAL],
    [stay_number] TINYINT NOT NULL,
    [intake_date] DATE REFERENCES [DATE]([exact_date]) NOT NULL,
    PRIMARY KEY ([animal_id], [stay_number]),
);

Body:
Try the following:

(SELECT [ANIMAL].[birth_date] FROM [ANIMAL] WHERE [ANIMAL].[animal_id] = [ANIMAL_INTAKE].[animal_id])

I’m assuming that your table in the DSV is named ANIMAL_INTAKE and that’s the table you are putting your named calculation on.


问:
Retrieve image reference from MySQL database when selected radiobutton changes
I have a MySQL database that stores the paths to images.

I would like the displayed image to change based on the selected radiobutton option. I am trying to use AJAX to update the the displayed image, but my understanding of this technology is very limited.

This is the radiobutton list and the image. A JS function is called when the selected element changes.

```<code><img class="img-responsive center-block" src="../images/1.png" id="buildimage" />

<ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateImage(this.id);">
    <label for="item-1">Item 1</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="2.00" type="radio" onchange="updateImage(this.id);">
    <label for="item-2">Item 2</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="3.00" type="radio" onchange="updateImage(this.id);">
    <label for="item-3">Item 3</label>
  </li>
</ul>
</code>```

This is the function updateImage:

```<code><script>
    function updateImage(caseid) {
        selectmenuID = document.getElementById(caseid);

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("buildimage").innerHTML = this.responseText;
            }
        };
        xhttp.open("GET", "displayImage.php", true);
        xhttp.send("id='selectmenuID'");

    }

</script>
</code>```

PHP file that retrieves the path:

```<code><?php

require_once("config.php");

$id = $_GET["id"];

$stmt = $pdo->prepare("SELECT link FROM cases WHERE id=?");
$stmt->bind_param("s", $id);
$stmt->execute([$id]);
$result = $stmt->fetch();
echo '<img src="data:image/jpeg;base64,'.base64_encode($result['image'] ).'"/>';

?>
</code>```

The problem I have is that I do not understand how to use AJAX to call the PHP file passing the selected element ID, and then change the src file path based on the response.

Is this possible? Thank you.

答:
First, you have to use xhttp.responseText instead of this.responseText to get the response from the server.

Then, you should directly replace the src attribute of the image instead of trying to replace its html :

```<code>document.getElementById("buildimage").src = xhttp.responseText;
</code>```

serverside :

```<code>echo $result['image'];
</code>```

You also have to replace this line :

```<code>xhttp.send("id='selectmenuID'");
</code>```

by this :

```<code>xhttp.send("id="+selectmenuID);
</code>```

Body:
I have a MySQL database that stores the paths to images.

I would like the displayed image to change based on the selected radiobutton option. I am trying to use AJAX to update the the displayed image, but my understanding of this technology is very limited.

This is the radiobutton list and the image. A JS function is called when the selected element changes.

    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateImage(this.id);">
    Item 1

    <input id="item-2" name="config-prod" value="2.00" type="radio" onchange="updateImage(this.id);">
    Item 2

    <input id="item-3" name="config-prod" value="3.00" type="radio" onchange="updateImage(this.id);">
    Item 3

This is the function updateImage:

PHP file that retrieves the path:

<?php

require_once("config.php");

$id = $_GET["id"];

$stmt = $pdo->prepare("SELECT link FROM cases WHERE id=?");
$stmt->bind_param("s", $id);
$stmt->execute([$id]);
$result = $stmt->fetch();
echo '';

?>

The problem I have is that I do not understand how to use AJAX to call the PHP file passing the selected element ID, and then change the src file path based on the response.

Is this possible? Thank you.

Body:
First, you have to use xhttp.responseText instead of this.responseText to get the response from the server.

Then, you should directly replace the src attribute of the image instead of trying to replace its html :

document.getElementById("buildimage").src = xhttp.responseText;

serverside :

echo $result['image'];

You also have to replace this line :

xhttp.send("id='selectmenuID'");

by this :

xhttp.send("id="+selectmenuID);


问:
Create Jpeg from NSData
I am getting images from sever using this :

```<code>- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (!error)
         {
             completionBlock(YES, data);
         }
         else
         {
             completionBlock(NO, nil);
         }
     }];
}
</code>```

Which provide me NSData . Now for better performance i would like to present the image in jpeg.

I know how to convert NSData to UIImage, with UIImage *image=[UIImage imageWithData:data];
And how to create NSData from image NSData *imageData = UIImagePNGRepresentation(image);

But both are not do what i need, i would like to take that NSData i get from the server, and create out of it JPEG image . how would i do that ?
(do i have to create first a new data with jpeg ,than the image from this data? )

答:
With Swift 5 and iOS 12, you can use CGImage, CGImageDestination and CGDataProvider in order to convert some image data. The following function implementation shows how to do so:

```<code>import Foundation
import ImageIO
import MobileCoreServices

func convertImageData(_ data: Data) -> Data? {
    guard let provider = CGDataProvider(data: data as CFData) else {
        print("Could not create data provider from data")
        return nil
    }

    guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
        print("Could not create cgImage from provider")
        return nil
    }

    let data = NSMutableData()
    guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, kUTTypeJPEG, 1, nil) else {
        print("Could not create an image destination from url")
        return nil
    }

    let options = [
        kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
        kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
    ] as CFDictionary

    CGImageDestinationAddImage(imageDestination, cgImage, options)
    let imageIsWritten = CGImageDestinationFinalize(imageDestination)

    if !imageIsWritten {
        print("Image could not be written")
        return nil
    }

    return data as Data
}
</code>```

Usage:

```<code>let data: Data = …
let newData = convertImageData(data)
</code>```

As an alternative, you can use CGImage, CGImageDestination and CGDataProvider in order to write some JPEG image data to a given URL. The following function implementation shows how to do so:

```<code>import Foundation
import ImageIO
import MobileCoreServices

func saveImageData(_ data: Data, to fileUrl: URL) {
    guard let provider = CGDataProvider(data: data as CFData) else {
        print("Could not create data provider from data")
        return
    }

    guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
        print("Could not create cgImage from provider")
        return
    }

    guard let imageDestination = CGImageDestinationCreateWithURL(fileUrl as CFURL, kUTTypeJPEG, 1, nil) else {
        print("Could not create an image destination from url")
        return
    }

    let options = [
        kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
        kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
    ] as CFDictionary

    CGImageDestinationAddImage(imageDestination, cgImage, options)
    let imageIsWritten = CGImageDestinationFinalize(imageDestination)

    if !imageIsWritten {
        print("Image could not be written")
    }
}
</code>```

Usage:

```<code>let data: Data = …
let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileUrl = documentDirectoryUrl.appendingPathComponent("image.jpeg")
saveImageData(data, to: fileUrl)
</code>```

Sources:

Image I/O Programming Guide - Working with Image Destinations

Thinking about Memory: Converting UIImage to Data in Swift

Title: Create Jpeg from NSData

Body:
I am getting images from sever using this :

- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (!error)
         {
             completionBlock(YES, data);
         }
         else
         {
             completionBlock(NO, nil);
         }
     }];
}

Which provide me NSData . Now for better performance i would like to present the image in jpeg.

I know how to convert NSData to UIImage, with UIImage *image=[UIImage imageWithData:data];
And how to create NSData from image NSData *imageData = UIImagePNGRepresentation(image);

But both are not do what i need, i would like to take that NSData i get from the server, and create out of it JPEG image . how would i do that ?
(do i have to create first a new data with jpeg ,than the image from this data? )

Body:
With Swift 5 and iOS 12, you can use CGImage, CGImageDestination and CGDataProvider in order to convert some image data. The following function implementation shows how to do so:

import Foundation
import ImageIO
import MobileCoreServices

func convertImageData(_ data: Data) -> Data? {
    guard let provider = CGDataProvider(data: data as CFData) else {
        print("Could not create data provider from data")
        return nil
    }

    guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
        print("Could not create cgImage from provider")
        return nil
    }

    let data = NSMutableData()
    guard let imageDestination = CGImageDestinationCreateWithData(data as CFMutableData, kUTTypeJPEG, 1, nil) else {
        print("Could not create an image destination from url")
        return nil
    }

    let options = [
        kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
        kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
    ] as CFDictionary

    CGImageDestinationAddImage(imageDestination, cgImage, options)
    let imageIsWritten = CGImageDestinationFinalize(imageDestination)

    if !imageIsWritten {
        print("Image could not be written")
        return nil
    }

    return data as Data
}

Usage:

let data: Data = …
let newData = convertImageData(data)

As an alternative, you can use CGImage, CGImageDestination and CGDataProvider in order to write some JPEG image data to a given URL. The following function implementation shows how to do so:

import Foundation
import ImageIO
import MobileCoreServices

func saveImageData(_ data: Data, to fileUrl: URL) {
    guard let provider = CGDataProvider(data: data as CFData) else {
        print("Could not create data provider from data")
        return
    }

    guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
        print("Could not create cgImage from provider")
        return
    }

    guard let imageDestination = CGImageDestinationCreateWithURL(fileUrl as CFURL, kUTTypeJPEG, 1, nil) else {
        print("Could not create an image destination from url")
        return
    }

    let options = [
        kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
        kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
    ] as CFDictionary

    CGImageDestinationAddImage(imageDestination, cgImage, options)
    let imageIsWritten = CGImageDestinationFinalize(imageDestination)

    if !imageIsWritten {
        print("Image could not be written")
    }
}

Usage:

let data: Data = …
let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileUrl = documentDirectoryUrl.appendingPathComponent("image.jpeg")
saveImageData(data, to: fileUrl)

Sources:

Image I/O Programming Guide - Working with Image Destinations

Thinking about Memory: Converting UIImage to Data in Swift


问:
A* algorithm - ellipse property of expension
Based on the ellipse property of A*, why this algorithm closes
all nodes in a series of expanding ellipses?</p>

答:
A* uses the function f(x) = g(x) + h(x) to assess what node to visit next, where g(x) is the actual cost for going from the start to x and h(x) is the estimated cost to go from x to the target (= heuristic).

Let's take a look at this in the continuous case in the Euclidean plane, where we want to go from (0, 0) to (10, 20). Then:

```<code>g(x) = Length(x)
</code>```

The shape of the exploration front depends heavily on the heuristic. Let's start with the perfect heuristic

```<code>h(x) = Length(x - (10, 20))
</code>```

We can plot the value of g(x) + h(x) over the plane and see the order of visited nodes (points with smaller f will be visited first). Doing so, we should be aware that a node cannot be visited if none of its neighbors have been visited before, so the actual value is only an indication of the order. We'll keep this in mind. Using the perfect heuristic, we get the following picture:

All points on the connection between start and target have the same f cost, which is equal to the distance of start and target. And if we inspect f, we see that

```<code>f = Length(x - (0, 0)) + Length(x - (10, 20)),
</code>```

which is exactly the implicit form of an ellipse with the start and target as foci.

I said that the shape depends on the heuristic. A heuristic is valid if it is a lower bound of the actual distance. Let's try

```<code>h(x) = 0.5 * Length(x - (10, 20))
</code>```

Now, the algorithm will start to explore more points surrounding the start before it reaches the target. Especially, all points within the contour before the target point will be visited.

We can even go one step further and set

```<code>h(x) = 0
</code>```

This is the setting for Dijkstra's algorithm, where we cannot say anything about the distance to the target:

Here, the algorithm will visit nodes in disks around the start point.

One common approximation of the distance to the target is the Manhattan distance because it is cheap to compute:

```<code>h(x, y) = |x - 10| + |y - 20|
</code>```

This heuristic is not valid because it is not a lower bound on the actual distance. It gives us:

This is exactly a case where points close to the target have a lower f score than those close to the start. Although they have a lower value in this figure, they will of course not be visited first because their neighbors have not been explored yet. Here is a close-up:

We can make the heuristic valid by introducing a constant factor:

```<code>h(x, y) = 1/sqrt(2) * (|x - 10| + |y - 20|)
</code>```

This will give us a valid heuristic with a proper front shape:

Body:
A* uses the function f(x) = g(x) + h(x) to assess what node to visit next, where g(x) is the actual cost for going from the start to x and h(x) is the estimated cost to go from x to the target (= heuristic).

Let's take a look at this in the continuous case in the Euclidean plane, where we want to go from (0, 0) to (10, 20). Then:

g(x) = Length(x)

The shape of the exploration front depends heavily on the heuristic. Let's start with the perfect heuristic

h(x) = Length(x - (10, 20))

We can plot the value of g(x) + h(x) over the plane and see the order of visited nodes (points with smaller f will be visited first). Doing so, we should be aware that a node cannot be visited if none of its neighbors have been visited before, so the actual value is only an indication of the order. We'll keep this in mind. Using the perfect heuristic, we get the following picture:

All points on the connection between start and target have the same f cost, which is equal to the distance of start and target. And if we inspect f, we see that

f = Length(x - (0, 0)) + Length(x - (10, 20)),

which is exactly the implicit form of an ellipse with the start and target as foci.

I said that the shape depends on the heuristic. A heuristic is valid if it is a lower bound of the actual distance. Let's try

h(x) = 0.5 * Length(x - (10, 20))

Now, the algorithm will start to explore more points surrounding the start before it reaches the target. Especially, all points within the contour before the target point will be visited.

We can even go one step further and set

h(x) = 0

This is the setting for Dijkstra's algorithm, where we cannot say anything about the distance to the target:

Here, the algorithm will visit nodes in disks around the start point.

One common approximation of the distance to the target is the Manhattan distance because it is cheap to compute:

h(x, y) = |x - 10| + |y - 20|

This heuristic is not valid because it is not a lower bound on the actual distance. It gives us:

This is exactly a case where points close to the target have a lower f score than those close to the start. Although they have a lower value in this figure, they will of course not be visited first because their neighbors have not been explored yet. Here is a close-up:

We can make the heuristic valid by introducing a constant factor:

h(x, y) = 1/sqrt(2) * (|x - 10| + |y - 20|)

This will give us a valid heuristic with a proper front shape:


答:
total + data[i] is an "orphaned expression". Use = or +=.

var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
  var newdata = +prompt("Enter a piece of data (must be a number)");
  data.push(newdata);
  var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
  while (i < data.length) {
    total += data[i];
    i++;
  }
  var average = total / data.length;
  document.write(average);
}```

Title: Average finder always prints “0”


问:
Cannot assign value to datetimepicker
I want to assign value to datetimepicker, but isn't work anymore.

I tried, but the results were not as expected.

Jquery to assign value :

```<code>$('#iTTDateOpen').data('datetimepicker').setLocalDate(new Date(2019, 6, 2, 10, 55));
</code>```

HTML Code :

```<code><div class="form-group">
<label class="col-md-3 control-label">TT Date Open</label>
<div class="col-md-7">
<input type="text" id="iTTDateOpen" class="form-control txt filter-time" placeholder="Trouble Ticket Date Open" onkeydown="return false" required>
</div>
</div>
</code>```

I expected the output is 2019-06-02 10:55, but the actual output is /Date(1559001300000)/

答:
Maybe something like this?</p>

```<code>$('#iTTDateOpen').html(new Date(2019, 6, 2, 10, 55));
</code>```

Title: Cannot assign value to datetimepicker

Body:
I want to assign value to datetimepicker, but isn't work anymore.

I tried, but the results were not as expected.

Jquery to assign value :

$('#iTTDateOpen').data('datetimepicker').setLocalDate(new Date(2019, 6, 2, 10, 55));

HTML Code :

TT Date Open

<input type="text" id="iTTDateOpen" class="form-control txt filter-time" placeholder="Trouble Ticket Date Open" onkeydown="return false" required>

I expected the output is 2019-06-02 10:55, but the actual output is /Date(1559001300000)/

Body:
Maybe something like this?

$('#iTTDateOpen').html(new Date(2019, 6, 2, 10, 55));


问:
How to pull from a string into first, middle, and last name. And how to recognize when there is no middle name inputed
I need to do the following:

Many documents use a specific format for a person's name. Write a program whose input is: firstName middleName lastName, and whose output is: lastName, firstName middleInitial.

It's through a textbook so I haven't been taught how to split strings. That's all I can find online, but that's not what the textbook is asking for. So far I've been taught how to compare strings, get a strings length, branches, switch statements, string operations.

    import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);

      String firstName;
      String middleName;
      String lastName;
      String name;

      name = scnr.nextLine();

      int firstSpace = name.indexOf(" ");
      firstName = name.substring(0, firstSpace);

      int secondSpace = name.indexOf(" ", firstSpace + 1);

      if (secondSpace < 0) {
         lastName = name.substring(firstSpace);
         System.out.println(lastName + ", " + firstName);
      }
      else {
         middleName = name.substring(firstSpace, secondSpace);
         lastName = name.substring(secondSpace);
         System.out.println(lastName + ", " + firstName + " " + middleName.charAt(0) + ".");
      }

   }
}

```

This is what I have so far.

答:
If you cannot use the split() you can read the first two entries with scnr.next() and then the third input will be the rest of the line, and then you can take a substring of it taking the space off.

```<code>import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        String name1;
        String name2;
        String name3;

        name1 = scnr.next();
        name2 = scnr.next();
        name3 = scnr.nextLine();

        if (name3.equals("")){
            System.out.println(name2 + ", " + name1);
        }
        else{
            name3 = name3.substring(1);
            System.out.println(name3 + ", " + name1 + " " + name2.charAt(0) + ".");
        }
   }
}
</code>```

Body:
I need to do the following:

Many documents use a specific format for a person's name. Write a program whose input is: firstName middleName lastName, and whose output is: lastName, firstName middleInitial.

It's through a textbook so I haven't been taught how to split strings. That's all I can find online, but that's not what the textbook is asking for. So far I've been taught how to compare strings, get a strings length, branches, switch statements, string operations.

    import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);

      String firstName;
      String middleName;
      String lastName;
      String name;

      name = scnr.nextLine();

      int firstSpace = name.indexOf(" ");
      firstName = name.substring(0, firstSpace);

      int secondSpace = name.indexOf(" ", firstSpace + 1);

      if (secondSpace < 0) {
         lastName = name.substring(firstSpace);
         System.out.println(lastName + ", " + firstName);
      }
      else {
         middleName = name.substring(firstSpace, secondSpace);
         lastName = name.substring(secondSpace);
         System.out.println(lastName + ", " + firstName + " " + middleName.charAt(0) + ".");
      }

   }
}

This is what I have so far.

Body:
If you cannot use the split() you can read the first two entries with scnr.next() and then the third input will be the rest of the line, and then you can take a substring of it taking the space off.

import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

        String name1;
        String name2;
        String name3;

        name1 = scnr.next();
        name2 = scnr.next();
        name3 = scnr.nextLine();

        if (name3.equals("")){
            System.out.println(name2 + ", " + name1);
        }
        else{
            name3 = name3.substring(1);
            System.out.println(name3 + ", " + name1 + " " + name2.charAt(0) + ".");
        }
   }
}


问:
Can migrations be applied to fixtures in Ruby on Rails?
I find fixtures a bit tedious to use in Ruby on Rails, partly because I need to manually correct them after most migrations.

Is there a way (a plugin?) I can have my fixtures modified when I run my migrations?

答: Factory Girl or Machinist are both great alternatives to fixtures, you just need to define a valid instance of your model and then use as many or as few as you need. I was using Machinist, but started using Factory Girl as it has better support for associations between your models.</p>

OwnerDisplayName: MiniQuark

OwnerDisplayName: railsninja


问:
Square Brackets Javascript Object Key
Can anyone explain how the why/how the below method of assigning keys in JavaScript works?

```<code>a = "b"
c = {[a]: "d"}
</code>```

return:

```<code>Object {b: "d"}
</code>```

答: Also, only condition to use <code>[]</code> notation for accessing or assigning stuff in objects when we don't yet know what it's going to be until evaluation or runtime.   </p>

Title: Square Brackets Javascript Object Key

Body:
Can anyone explain how the why/how the below method of assigning keys in JavaScript works?

a = "b"
c = {[a]: "d"}

return:

Object {b: "d"}

Body: Also, only condition to use [] notation for accessing or assigning stuff in objects when we don't yet know what it's going to be until evaluation or runtime.


答:
Try this:</p>

```<code>var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
    var newdata = prompt("Enter a piece of data (must be a
    number)");
    data.push(newdata);
    var yesno = confirm("Would you like to add more
    data?");
}
var total = 0;
var i = 0;
if (!yesno) {
    while (i < data.length) {
        total += data[i];
        i ++;
        var average = total / data.length;
document.write(average);
        }
    }
</code>```

Title: Average finder always prints “0”

Body:
Try this:

var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
    var newdata = prompt("Enter a piece of data (must be a
    number)");
    data.push(newdata);
    var yesno = confirm("Would you like to add more
    data?");
}
var total = 0;
var i = 0;
if (!yesno) {
    while (i < data.length) {
        total += data[i];
        i ++;
        var average = total / data.length;
document.write(average);
        }
    }


问:
how to get value of checkbox in Google Apps script
I have created a checkbox in Google sheet sidebar which has a form with a checkbox field.

Regardless of whether i check the checkbox or not, i get the value as "on".

I need to know whether the checkbox was checked or not

```<code>    <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>

            <form>
    <div>
    <p>
          <label>
            <input name="item" id="Agree" type="checkbox" class="red"/>
            <span>Agree</span>

          </label>
        </p>
        </div>

            <div class="input-field col s12">

            <button class="btn waves-effect waves-light" type="submit" name="action" id="btn">Generate
        <i class="material-icons right">send</i>
      </button>

        </div>
        </form>

       <script>

                var agreeValue = document.getElementById("Agree")

                document.getElementById("btn").addEventListener("click", addRecord);

                function addRecord() {
                var data = {
                agreeValue               : Agree.value
                };

                google.script.run.appendData(data);
                }

    </script>

  </body>
</html>
</code>```

答:
If you want to confirm the checkbox by on and off, how about modifying as follows?

From:

```<code>var data = {
  agreeValue: Agree.value
};
</code>```

To:

```<code>var data = {
  agreeValue: agreeValue.checked ? "on" : "off" // or Agree.checked ? "on" : "off"
};
</code>```

By this modification, when the checkbox is checked and unchecked, data becomes {agreeValue: "on"} and {agreeValue: "off"}, respectively.

Note:

When var data = {agreeValue: agreeValue.checked} is used, you can retrieve the value of checkbox as a boolean.

If I misunderstood your question and this was not the result you want, I apologize.

Body:
I have created a checkbox in Google sheet sidebar which has a form with a checkbox field.

Regardless of whether i check the checkbox or not, i get the value as "on".

I need to know whether the checkbox was checked or not

    <!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

            <form>

            <input name="item" id="Agree" type="checkbox" class="red"/>
            Agree

            <button class="btn waves-effect waves-light" type="submit" name="action" id="btn">Generate
        send
      </button>

        </form>

Body:
If you want to confirm the checkbox by on and off, how about modifying as follows?

From:

var data = {
  agreeValue: Agree.value
};

To:

var data = {
  agreeValue: agreeValue.checked ? "on" : "off" // or Agree.checked ? "on" : "off"
};

By this modification, when the checkbox is checked and unchecked, data becomes {agreeValue: "on"} and {agreeValue: "off"}, respectively.

Note:

When var data = {agreeValue: agreeValue.checked} is used, you can retrieve the value of checkbox as a boolean.

If I misunderstood your question and this was not the result you want, I apologize.


问:
Show an element... unless the user has javascript turned on, then fade it in nice and pretty?
I have an element which shows important text to the user, as such I'd like to animate it in to the pane (motion draws the eye) rather than just have it somewhere where the user may miss it.

How can I have it showing by default (for the 1% or so of users who surf with javascript off), but animated in for the rest?

Using

```<code>    $(document).ready(function(){
        $('#messagecenter').hide();
        $('#messagecenter').show('fade', 'slow');
    })
</code>```

Causes the element to load visible, then disapear, then fade.

```<code>display:hidden;

    $(document).ready(function(){
        $('#messagecenter').show('fade', 'slow');
    })
</code>```

Will of course hide it for users with no Javascript.

Is there any good way to do this?

答:
Always use the ...</nosript> tag for those 1% users.

And keep the code for the normal users untouched.

Body:
I have an element which shows important text to the user, as such I'd like to animate it in to the pane (motion draws the eye) rather than just have it somewhere where the user may miss it.

How can I have it showing by default (for the 1% or so of users who surf with javascript off), but animated in for the rest?

Using

    $(document).ready(function(){
        $('#messagecenter').hide();
        $('#messagecenter').show('fade', 'slow');
    })

Causes the element to load visible, then disapear, then fade.

display:hidden;

    $(document).ready(function(){
        $('#messagecenter').show('fade', 'slow');
    })

Will of course hide it for users with no Javascript.

Is there any good way to do this?

Body:
Always use the <noscript>...</nosript> tag for those 1% users.

And keep the code for the normal users untouched.


问:
Relational database (RDBMS) denormalized data
I believe this question does not address specifically MySQL - which is the database that I'm using -, and it's one about best practices.

Up until now, my problems could be solved by creating tables and querying them (sometimes JOINing here and there). But there is something that I'm doing that doesn't feel right, and it triggers me whenever I need a denormalized data alongside my "common" queries.

Example Use-case

So that I can express myself better, let's create a superficial scenario where:

a user can buy a product, generating a purchase (let's ignore the fact that the purchase can only have a single product);

and we need to query the products with the total amount of times it has been purchased;

To solve our use-case, we could define a simple structure made by:

product table:

product_id [INT PK]

user table:

user_id [INT PK]

purchase table:

purchase_id [INT PK]

product_id [INT FK NOT NULL]

user_id [INT FK NOT NULL]

Here is where it doesn't feel right: When we need to retrieve a list of products with the total times it has been purchased, I would create the query:

```<code># There are probably faster queries than this to reach the same output
SELECT
    product.product_id,
    (SELECT COUNT(*) FROM purchase
      WHERE purchase.product_id = product.product_id)
FROM
    product
</code>```

My concern origin is that I've read that COUNT does a full table scan, and it scares me to perform the query above when scaled to thousands of products being purchased - even though I've created an INDEX with the product_id FK on purchase (MySQL does this by default).

Possible solutions

My knowledge with relational databases is pretty shallow, so I'm kind of lost when comparing what are the alternatives (plausible ones) for these kinds of problems. To not say that I haven't done my homework (searching before asking), I've found plausible to:

Create Transactions:

When INSERTing a new purchase, it must always be inside a transaction that also updates the product table with the purchase.product_id.

Possible Problems: human error. Someone might manually insert a purchase without doing the transaction and BAM - we have an inconsistency.

Create Triggers:

Whenever I insert, delete or update some row in some specific table, I would update my products table with a new value (bought_amount). So the table would become:

product table:

product_id [INT PK]

bought_amount [INT NOT NULL];

Possible problems: are triggers expensive? is there a way that the insertion succeeds but the trigger won't - thus leaving me with an inconsistency?

Question

Updating certain tables to store data that constantly changes is a plausible approach with RDBMSs? Is it safer and - in the long term - more beneficial to just keep joining and counting/summing other occurrences?

I've found a couple of useful questions/answers regarding this matter, but none of them addressed this subject in a wide perspective.
Please take into consideration my ignorance about RDBMS, as I may be suggesting nonsense Possible solutions.

答:
This query:

```<code>SELECT p.product_id,
      (SELECT COUNT(*)
       FROM purchase pu
       WHERE pu.product_id = p.product_id
      )
FROM product p;
</code>```

has to scan both product and purchase.  I'm not sure why you are emotional about one table scan but not the other.

As for performance, this can take advantage of an index on purchase(product_id).  In MySQL, this will probably be faster than the equivalent (left) join version.

You should not worry about performance of such queries until that becomes an issue.  If you need to increase performance of such a query, first I would ask:  Why?  That is a lot of information being returned -- about all products over all time.  More typically, I would expect someone to care about one product or a period of time or both.  And, those concerns would suggest the development of a datamart.

If performance is an issue, you have many alternatives, such as:

Defining a data mart to periodically summarize the data into more efficient structures for such queries.

Adding triggers to the database to summarize the data, if the results are needed in real-time.

Developing a methodology for maintaining the data that also maintains the summaries, either at the application-level or using stored procedures.

What doesn't "feel right" to you is actually the tremendous strength of a relational database (with a reasonable data model).  You can keep it up-to-date.  And you can query it using a pretty concise language that meets business needs.

Body:
I believe this question does not address specifically MySQL - which is the database that I'm using -, and it's one about best practices.

Up until now, my problems could be solved by creating tables and querying them (sometimes JOINing here and there). But there is something that I'm doing that doesn't feel right, and it triggers me whenever I need a denormalized data alongside my "common" queries.

Example Use-case

So that I can express myself better, let's create a superficial scenario where:

a user can buy a product, generating a purchase (let's ignore the fact that the purchase can only have a single product);

and we need to query the products with the total amount of times it has been purchased;

To solve our use-case, we could define a simple structure made by:

product table:

product_id [INT PK]

user table:

user_id [INT PK]

purchase table:

purchase_id [INT PK]

product_id [INT FK NOT NULL]

user_id [INT FK NOT NULL]

Here is where it doesn't feel right: When we need to retrieve a list of products with the total times it has been purchased, I would create the query:

# There are probably faster queries than this to reach the same output
SELECT
    product.product_id,
    (SELECT COUNT(*) FROM purchase
      WHERE purchase.product_id = product.product_id)
FROM
    product

My concern origin is that I've read that COUNT does a full table scan, and it scares me to perform the query above when scaled to thousands of products being purchased - even though I've created an INDEX with the product_id FK on purchase (MySQL does this by default).

Possible solutions

My knowledge with relational databases is pretty shallow, so I'm kind of lost when comparing what are the alternatives (plausible ones) for these kinds of problems. To not say that I haven't done my homework (searching before asking), I've found plausible to:

Create Transactions:

When INSERTing a new purchase, it must always be inside a transaction that also updates the product table with the purchase.product_id.

Possible Problems: human error. Someone might manually insert a purchase without doing the transaction and BAM - we have an inconsistency.

Create Triggers:

Whenever I insert, delete or update some row in some specific table, I would update my products table with a new value (bought_amount). So the table would become:

product table:

product_id [INT PK]

bought_amount [INT NOT NULL];

Possible problems: are triggers expensive? is there a way that the insertion succeeds but the trigger won't - thus leaving me with an inconsistency?

Question

Updating certain tables to store data that constantly changes is a plausible approach with RDBMSs? Is it safer and - in the long term - more beneficial to just keep joining and counting/summing other occurrences?

I've found a couple of useful questions/answers regarding this matter, but none of them addressed this subject in a wide perspective.
Please take into consideration my ignorance about RDBMS, as I may be suggesting nonsense Possible solutions.

Body:
This query:

SELECT p.product_id,
      (SELECT COUNT(*)
       FROM purchase pu
       WHERE pu.product_id = p.product_id
      )
FROM product p;

has to scan both product and purchase.  I'm not sure why you are emotional about one table scan but not the other.

As for performance, this can take advantage of an index on purchase(product_id).  In MySQL, this will probably be faster than the equivalent (left) join version.

You should not worry about performance of such queries until that becomes an issue.  If you need to increase performance of such a query, first I would ask:  Why?  That is a lot of information being returned -- about all products over all time.  More typically, I would expect someone to care about one product or a period of time or both.  And, those concerns would suggest the development of a datamart.

If performance is an issue, you have many alternatives, such as:

Defining a data mart to periodically summarize the data into more efficient structures for such queries.

Adding triggers to the database to summarize the data, if the results are needed in real-time.

Developing a methodology for maintaining the data that also maintains the summaries, either at the application-level or using stored procedures.

What doesn't "feel right" to you is actually the tremendous strength of a relational database (with a reasonable data model).  You can keep it up-to-date.  And you can query it using a pretty concise language that meets business needs.


问:
uiautomatorviewer - Error: Could not create the Java Virtual Machine
I am trying to run uiautomatorviewer in terminal. I am getting this error:

```<code>-Djava.ext.dirs=/Users/<Username>/Library/Android/sdk/tools/lib/x86_64:/Users/<Username>/Library/Android/sdk/tools/lib is not supported.  Use -classpath instead.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
</code>```

I think this might be related to the java version I am using. Here is the output of java -version:

```<code>java version "10" 2018-03-20
Java(TM) SE Runtime Environment 18.3 (build 10+46)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)
</code>```

I have already seen this question on SO, but it recommends downgrading to java 8.

Am I missing anything here? I would appreciate any help.

答:
Djava.ext.dirs=/Users//Library/Android/sdk/tools/lib/x86_64:/Users//Library/Android/sdk/tools/lib is not supported.  Use -classpath instead.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Following worked for me (Ubuntu 16.04, Java 11):

$ export YOUR_SDK_PATH="/home/user/Android/Sdk/"

$ java -Xmx1600M -Dcom.android.uiautomator.bindir="$YOUR_SDK_PATH/tools" -cp "$YOUR_SDK_PATH/tools/lib/x86_64/swt.jar":"$YOUR_SDK_PATH/tools/lib/*" com.android.uiautomator.UiAutomatorViewer
```

Body:
I am trying to run uiautomatorviewer in terminal. I am getting this error:

-Djava.ext.dirs=/Users/<Username>/Library/Android/sdk/tools/lib/x86_64:/Users/<Username>/Library/Android/sdk/tools/lib is not supported.  Use -classpath instead.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

I think this might be related to the java version I am using. Here is the output of java -version:

java version "10" 2018-03-20
Java(TM) SE Runtime Environment 18.3 (build 10+46)
Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10+46, mixed mode)

I have already seen this question on SO, but it recommends downgrading to java 8.

Am I missing anything here? I would appreciate any help.


问:
Stop a For Loop at an Index Value
I am attempting to use a for loop to iterate through a list of items. I do not need all items in the list and would like to end on a certain index position. How would I go about this in python?

I've attempted to use enumerate and alter my code to other options. After hours of searching I am having a hard time understanding how to end a loop upon a certain parameter in python. The code I am providing WORKS excellent for my interests. I would only like to stop the for loop upon a certain index.

```<code>train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')

print("Schedule for 900 East Station:")

for i in train_times:
    print('There is a train at {}'.format(i))
    print('--------------------------------------')
</code>```

答:
You can use break for loops:

train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')

print("Schedule for 900 East Station:")

for i, train in enumerate(train_times):
    if i == 400:
        break
    print('There is a train at {}'.format(train))
    print('--------------------------------------')
```

See more about break on loops: https://docs.python.org/3.7/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

Title: Stop a For Loop at an Index Value

Body:
I am attempting to use a for loop to iterate through a list of items. I do not need all items in the list and would like to end on a certain index position. How would I go about this in python?

I've attempted to use enumerate and alter my code to other options. After hours of searching I am having a hard time understanding how to end a loop upon a certain parameter in python. The code I am providing WORKS excellent for my interests. I would only like to stop the for loop upon a certain index.

train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')

print("Schedule for 900 East Station:")

for i in train_times:
    print('There is a train at {}'.format(i))
    print('--------------------------------------')

Body:
You can use break for loops:

train_times = driver.find_element_by_class_name('stop-times').text
str(train_times)
train_times=train_times.split('\n')

print("Schedule for 900 East Station:")

for i, train in enumerate(train_times):
    if i == 400:
        break
    print('There is a train at {}'.format(train))
    print('--------------------------------------')

See more about break on loops: https://docs.python.org/3.7/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops


问:
How to convert SELECT statement to Eloquent?
This works in existing website, trying to convert to Laravel 5.8 code:

SELECT
  DATE_FORMAT(created_at, '%M %Y') AS 'article',
  DATE_FORMAT(created_at, '%m')AS 'm',
  DATE_FORMAT(created_at,'%Y') AS 'y',
  COUNT(id) AS 'total'
FROM posts
GROUP BY DATE_FORMAT(created_at, '%Y%M')
ORDER BY m DESC
```

<p>I tried:</p>

<pre class="lang-php prettyprint-override"><code>$archives = DB::select("SELECT DATE_FORMAT(created_at, '%M %Y') AS 'article',DATE_FORMAT(created_at, '%m')AS 'm', DATE_FORMAT(created_at,'%Y') AS 'y', COUNT(id) AS 'total' FROM posts GROUP BY DATE_FORMAT(created_at, '%Y%M') ORDER BY m DESC");`
</code>```

I got:

Error:  SQLSTATE[42000]: Syntax error or access violation: 1055
  'amohdb.posts.created_at' isn't in GROUP BY (SQL: SELECT
  DATE_FORMAT(created_at, '%M %Y') AS 'article',DATE_FORMAT(created_at,
  '%m')AS 'm', DATE_FORMAT(created_at,'%Y') AS 'y', COUNT(id) AS 'total'
  FROM posts GROUP BY DATE_FORMAT(created_at, '%Y%M') ORDER BY m DESC)

答:
Answer turned out to be much simpler than I thought</p>

```<code>$archives =  Post::select(DB::raw("DATE_FORMAT(created_at, '%M %Y') as article"),
DB::raw("COUNT(id) as total"))
->groupBy('article')
->get();
</code>```

Body:
This works in existing website, trying to convert to Laravel 5.8 code:

SELECT
  DATE_FORMAT(created_at, '%M %Y') AS 'article',
  DATE_FORMAT(created_at, '%m')AS 'm',
  DATE_FORMAT(created_at,'%Y') AS 'y',
  COUNT(id) AS 'total'
FROM posts
GROUP BY DATE_FORMAT(created_at, '%Y%M')
ORDER BY m DESC

I tried:

$archives = DB::select("SELECT DATE_FORMAT(created_at, '%M %Y') AS 'article',DATE_FORMAT(created_at, '%m')AS 'm', DATE_FORMAT(created_at,'%Y') AS 'y', COUNT(id) AS 'total' FROM posts GROUP BY DATE_FORMAT(created_at, '%Y%M') ORDER BY m DESC");`

I got:

Error:  SQLSTATE[42000]: Syntax error or access violation: 1055
  'amohdb.posts.created_at' isn't in GROUP BY (SQL: SELECT
  DATE_FORMAT(created_at, '%M %Y') AS 'article',DATE_FORMAT(created_at,
  '%m')AS 'm', DATE_FORMAT(created_at,'%Y') AS 'y', COUNT(id) AS 'total'
  FROM posts GROUP BY DATE_FORMAT(created_at, '%Y%M') ORDER BY m DESC)

Body:
Answer turned out to be much simpler than I thought

$archives =  Post::select(DB::raw("DATE_FORMAT(created_at, '%M %Y') as article"),
DB::raw("COUNT(id) as total"))
->groupBy('article')
->get();


问:
How to update Dompdf header and footer in HTML
I am trying to display client details as a pdf using dompdf from HTML. Also added a header and footer in the pdf. Some contents in the pdf are displayed under the footer section.

This is the Image of pdf generated, here the data under Other Details are displayed under the footer section. How can change the alignment of content into the next page with a header and footer?

This is  the code have written, give a solution

```<code><html>

<head>
  <title>Prescription</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      padding: 0;
      margin: 0;
      font-family: "Times New Roman", Times, serif;
    }

    header {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      height: 200px;
      padding: 10px 50px;
      background-color: #ccc;
      border-bottom: 1px solid #1f1f1f;
      z-index: 1000;
    }

    .text-center {
      text-align: center;
    }

    .phone {
      float: right;
      margin-bottom: 10px;
      margin-right: 150px;
    }

    .phone h4 {
      text-align: center;
      right: 50px;
    }

    main {
      margin-top: 200px;
      padding: 10px 50px;
    }

    .after-header {
      height: 30px;
      padding: 10px 0;
    }

    .patient-id {
      float: left;
    }

    .date-day {
      float: right;
    }

    .page-header {
      margin-top: 5px;
      padding: 5px;
      background-color: aqua;
    }

    .page-header h2 {
      font-family: monospace;
      font-size: 20px;
      text-align: center;
    }

    footer {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      border-bottom: 1px solid #1f1f1f;
      border-top: 1px solid #1f1f1f;
      z-index: 1000;
    }

    footer h3 {
      padding-left: 50px;
    }

    .details {
      margin-top: 0;
      padding: 2px 0;
    }

    table {
      margin: 5px 0;
      width: 100%;
      border-top: 1px dotted #1f1f1f;
      border-right: 1px dotted #1f1f1f;
    }

    td {
      text-align: justify;
      padding: 10px;
      border-bottom: 1px dotted #1f1f1f;
      border-left: 1px dotted #1f1f1f;
    }

    table tr>td:first-child {
      border-left: none;
    }

    label {
      font-weight: bold;
      font-size: 15px;
    }
  </style>
</head>

<body>
  <header>
    <div class="text-center">
      <h1>SPECIALITY CLINIC</h1>
      <h2>xxxxxxxx</sub>
      </h2>
      <h3>Pediatrition</h3>
    </div>
    <div class="phone">
      <h4>Phone: xxxxx</h4>
    </div>
  </header>
  <footer>
    <h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.</h3>
  </footer>
  <main>
    <div class="after-header">
      <div class="patient-id">
        <h3>Patient Id: 1001</h3>
      </div>
      <div class="date-day">
        <h3>Date: 17/05/2019</h3>
      </div>
    </div>
    <div class="page-header">
      <h2>Patient Details</h2>
      <hr>
    </div>
    <div class="details">
      <div>
        <div style="background-color: #f2f2f2; padding: 5px;">
          <h3>General Details</h3>
        </div>
      </div>
      <table>
        <col width="10%">
        <col width="20%">
        <col width="10%">
        <col width="10%">
        <col width="30%">
        <tr>
          <td><label>Name:</label></td>
          <td colspan="3"><label>Agreesh V S</label></td>
          <td rowspan="4"><img src="img.jpg"></td>

        </tr>
        <tr>
          <td><label>Age:</label></td>
          <td><label>24</label></td>
          <td><label>Gender: </label></td>
          <td><label>Male</label></td>
        </tr>
        <tr>
          <td><label>Phone: </label></td>
          <td colspan="3"><label>9876543210</label></td>
        </tr>
        <tr>
          <td><label>Email: </label></td>
          <td colspan="3"><label>9876543210</label></td>
        </tr>

      </table>

      <div>
        <div style="background-color: #f2f2f2; padding: 5px;">
          <h3>Personal Details</h3>
        </div>
      </div>

      <table>
        <col width="50%">
        <col width="50%">

        <tr>
          <td><label>Date Of Birth:</label></td>
          <td colspan="3"><label>18/04/1995</label></td>
        </tr>
        <tr>
          <td><label>Weight</label></td>
          <td><label>65 KG</label></td>
        </tr>
        <tr>
          <td><label>Weight at Birth </label></td>
          <td colspan="3"><label>2.5 KG</label></td>
        </tr>
        <tr>
          <td><label>Blood Group </label></td>
          <td colspan="3"><label>B+ve</label></td>
        </tr>

      </table>
      <div>
        <div style="background-color: #f2f2f2; padding: 5px;">
          <h3>Other Details</h3>
        </div>
      </div>
      <table>
        <col width="50%">
        <col width="50%">

        <tr>
          <td><label>Date Of Birth:</label></td>
          <td colspan="3"><label>18/04/1995</label></td>
        </tr>
        <tr>
          <td><label>Weight</label></td>
          <td><label>65 KG</label></td>
        </tr>
        <tr>
          <td><label>Weight at Birth </label></td>
          <td colspan="3"><label>2.5 KG</label></td>
        </tr>
        <tr>
          <td><label>Blood Group </label></td>
          <td colspan="3"><label>B+ve</label></td>
        </tr>

      </table>
    </div>
  </main>
</body>

</html>
</code>```

答:
Keep in mind that when Dompdf positions content it is based on the bounds of the body. If you have a header/footer on the page you need to push it outside the bounds of the body or it will overlap the document content.

A small tweak to your CSS should fix things. First, add a page margin to accommodate your header. Something along the lines of:

```<code>@page {
  margin: 220px 1in 1in 1in;
}
</code>```

Then modify the top positioning of your header to push it into that space:

```<code>header {
  position: fixed;
  top: -200px;
  left: 0;
  right: 0;
  height: 200px;
  padding: 10px 50px;
  background-color: #ccc;
  border-bottom: 1px solid #1f1f1f;
  z-index: 1000;
}
</code>```

Body:
I am trying to display client details as a pdf using dompdf from HTML. Also added a header and footer in the pdf. Some contents in the pdf are displayed under the footer section.

This is the Image of pdf generated, here the data under Other Details are displayed under the footer section. How can change the alignment of content into the next page with a header and footer?

This is  the code have written, give a solution

  <title>Prescription</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

SPECIALITY CLINIC

xxxxxxxx

Pediatrition

Phone: xxxxx

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.

Patient Id: 1001

Date: 17/05/2019

Patient Details

General Details

        <col width="10%">
        <col width="20%">
        <col width="10%">
        <col width="10%">
        <col width="30%">

          Name:
          Agreesh V S

          Age:
          24
          Gender:
          Male

          Phone:
          9876543210

          Email:
          9876543210

Personal Details

        <col width="50%">
        <col width="50%">

          Date Of Birth:
          18/04/1995

          Weight
          65 KG

          Weight at Birth
          2.5 KG

          Blood Group
          B+ve

Other Details

        <col width="50%">
        <col width="50%">

          Date Of Birth:
          18/04/1995

          Weight
          65 KG

          Weight at Birth
          2.5 KG

          Blood Group
          B+ve

Body:
Keep in mind that when Dompdf positions content it is based on the bounds of the body. If you have a header/footer on the page you need to push it outside the bounds of the body or it will overlap the document content.

A small tweak to your CSS should fix things. First, add a page margin to accommodate your header. Something along the lines of:

@page {
  margin: 220px 1in 1in 1in;
}

Then modify the top positioning of your header to push it into that space:

header {
  position: fixed;
  top: -200px;
  left: 0;
  right: 0;
  height: 200px;
  padding: 10px 50px;
  background-color: #ccc;
  border-bottom: 1px solid #1f1f1f;
  z-index: 1000;
}


问:
How to grab a value from a dictionary which contains multiple keys?
I have this dictionary:

```<code> mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}
</code>```

My question is, how do I obtain value value1 by using only one of the keys e.g 950001?

In other words, I want to do something like:

```<code>mydict['950001']
</code>```

and get printed:

```<code>value1
</code>```

I know I may reverse the keys and values, but in this case it won't work for the script I am working on.

答:
A dictionary in Python consist of key-value-pairs. So in your example, one key would be '950001,959070,959071,959072,950908,959073'. In my explanations below, I will call 950001, 959070 and so on just "numbers".

Method 1: You could write a loop over all keys of your dict and split each key into a list at every comma , with str.split. Your list then contains your numbers and you can check if your requested number n is in there:

```<code>mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}

n = '950001'
for key in mydict:
    if n in key.split(','):
        print(mydict[key])
</code>```

Which prints:

```<code>value1
</code>```

Method 2: Alternatively, you could convert your dictionary mydict into a new dictionary new_dict so every number gets its own key:

```<code>mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}

new_dict = {}
for key in mydict:
    for new_key in key.split(','):
        new_dict[new_key] = mydict[key]

print(new_dict)
</code>```

Which prints:

```<code>{'950001': 'value1', '959070': 'value1', '959071': 'value1', '959072': 'value1', '950908': 'value1', '959073': 'value1', '400856': 'value2', '400857': 'value2', '400858': 'value2', '400859': 'value2', '400860': 'value2', '400861': 'value2', '920100': 'value3', '950107': 'value4', '950109': 'value4', '950108': 'value4'}
</code>```

Then you can access your value just like you said with new_dict['950001'].

The code above is written with emphasis on clarity. Depending on your use case, you could write a function and/or use a dict comprehension to make your code look nicer if you're comfortable with that:

```<code>mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}
new_dict = {nk: v for k, v in mydict.items() for nk in k.split(',')}
print(new_dict['950001'])
</code>```

Body:
I have this dictionary:

 mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}

My question is, how do I obtain value value1 by using only one of the keys e.g 950001?

In other words, I want to do something like:

mydict['950001']

and get printed:

value1

I know I may reverse the keys and values, but in this case it won't work for the script I am working on.

Body:
A dictionary in Python consist of key-value-pairs. So in your example, one key would be '950001,959070,959071,959072,950908,959073'. In my explanations below, I will call 950001, 959070 and so on just "numbers".

Method 1: You could write a loop over all keys of your dict and split each key into a list at every comma , with str.split. Your list then contains your numbers and you can check if your requested number n is in there:

mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}

n = '950001'
for key in mydict:
    if n in key.split(','):
        print(mydict[key])

Which prints:

value1

Method 2: Alternatively, you could convert your dictionary mydict into a new dictionary new_dict so every number gets its own key:

mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}

new_dict = {}
for key in mydict:
    for new_key in key.split(','):
        new_dict[new_key] = mydict[key]

print(new_dict)

Which prints:

{'950001': 'value1', '959070': 'value1', '959071': 'value1', '959072': 'value1', '950908': 'value1', '959073': 'value1', '400856': 'value2', '400857': 'value2', '400858': 'value2', '400859': 'value2', '400860': 'value2', '400861': 'value2', '920100': 'value3', '950107': 'value4', '950109': 'value4', '950108': 'value4'}

Then you can access your value just like you said with new_dict['950001'].

The code above is written with emphasis on clarity. Depending on your use case, you could write a function and/or use a dict comprehension to make your code look nicer if you're comfortable with that:

mydict = {'950001,959070,959071,959072,950908,959073': 'value1', '400856,400857,400858,400859,400860,400861': 'value2', '920100': 'value3', '950107,950109,950108': 'value4'}
new_dict = {nk: v for k, v in mydict.items() for nk in k.split(',')}
print(new_dict['950001'])


问:
Xcode - View Screen size
I am in the process of learning iOS development with XCode.  I created a project to implement some of the things I've been learning and to begin learning how to manage image sizes and placement on different sized screens i.e. iPhone 8, iPhone 8+, iPad, etc.  I am currently using XCode 10 Beta and I noticed that the View size on the main storyboard is half the actual screen size of any device I select to to View As:.  For instance if I select View As: iPhone 8 the screen size is 375x667 instead of being 750x1334 like the actual device.  I discovered this because I created a square image of 100x100px and thought I would be able to line up 7 across the screen.  To my surprise the images took up twice as much screen as I had calculated.

Can anyone let me know why the screen Views in XCode are half that of actual screen size?

Do I just always assume to make my graphics half the size I would actually want them?

Edit: Here's a screenshot of what I am referring to in XCode

When I click on the empty view in the the XCode storyboard pane this is this resolution it displays for the view.  Also, when I export my graphics from Illustrator the are exported with the @1x, @2x, and @3x variants.  However, when I place an image in the view that is 100x100px it takes up about 1/3 of the screen instead of 1/7 of the screen as I would expect on a iPhone 8 which has a resolution of 750x1334.

Edit #2: So after playing around more with XCode I do see that the resolution for the views are in Points not pixels however, in this screenshot for a iPhone 8+ View:

I would assume with a screen resolution of 1080x1920 @3x the Point resolution would be 360x640 for an iPhone 8+ not 414x736.

答:
It has to do with the difference between points and pixels. On the original iPhone when it was release it was 1 point per pixel but as resolution got better it became 2x pixels per point (4 pixels). Now the resolution is 3x pixels per point on some of the newer devices (9 pixels).

https://www.google.com/amp/s/blog.fluidui.com/designing-for-mobile-101-pixels-points-and-resolutions/amp/

Title: Xcode - View Screen size