问:
Checking within a range of field of fields
I wasn't quite sure how to word the title, sorry if it doesn't make sense/is misleading.

Note - a "boat" is 3 O's next to each other in an array, so

```<code>_|O|_  _|_|_
_|O|_  O|O|O
 |O|    | |
</code>```

are boats.

So I have an a list of lists (n x n) (working with lists) in which I generate n boats at random spaces. I don't want the boats to be next to each other, touch by corners, or be on top of each other.

A tried checking if a boat would end up on top of another boat in the vein of this:

```<code>if board[y - 2][x] == 'O' or board[y + 2][x] == 'O' ...
</code>```

and so on, which ended up being unsurprisingly long.

I also got index out of range errors, since I was sometimes checking for coordinates not in the field.

So, is there a way I can check for boats in every direction without going out of index range?

Better yet, any ideas on how to make the boats not generate next to each other?

The code for boat generation is here:

```<code>from random import *

side = int(input())
game_state = []

def generate_initial_state():

    for i in range(side):
        game_state.append([])
        for j in range(side):
            game_state[i].append('.')

    for i in range(side):
        # Generate boat origin on random coordinates within the game board,
        # if there's a boat already, generate new ones
        y_cor = randint(0, side-1)
        x_cor = randint(0, side-1)
        while game_state[y_cor][x_cor] == 'O':
            y_cor = randint(0, side - 1)
            x_cor = randint(0, side - 1)
        # Direct chooses if the boat will be generated up, down, or sideways
        direct = randint(1, 4)
        cycle = 0

        while cycle < 3:
        # Generates a boat going from origin in one direction,
        # if the boat would end outside the board, chooses a different direction
            if direct == 1:
                if y_cor + 2 >= side:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor + cycle][x_cor] = 'O'
                    cycle += 1
            elif direct == 2:
                if x_cor + 2 >= side:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor][x_cor + cycle] = 'O'
                    cycle += 1
            elif direct == 3:
                if y_cor - 2 < 0:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor - cycle][x_cor] = 'O'
                    cycle += 1
            elif direct == 4:
                if x_cor - 2 < 0:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor][x_cor - cycle] = 'O'
                    cycle += 1

for i in range(side):
    print(*game_state[i])
</code>```

答:
You can try the following class and see if it solves your problem:</p>

```<code>#! /usr/bin/env python3
import collections
import enum
import random

def main():
    board = Board(10, 10)
    print(board)
    board.place_boats([2, 3, 3, 4, 5])
    print('\n' + '=' * 21 + '\n')
    print(board)

Point = collections.namedtuple('Point', 'x, y')
# noinspection PyArgumentList
Orientation = enum.Enum('Orientation', 'HORIZONTAL, VERTICAL')

class Board:
    def __init__(self, width, height):
        self.__width = width
        self.__height = height
        self.__matrix = [[False] * height for _ in range(width)]
        self.__available = {Point(x, y)
                            for x in range(width)
                            for y in range(height)}

    def __str__(self):
        width = self.__width * 2 + 1
        height = self.__height * 2 + 1
        grid = [[' '] * width for _ in range(height)]
        for yo, xo, character in (0, 1, '|'), (1, 0, '-'), (1, 1, '+'):
            for y in range(yo, height, 2):
                for x in range(xo, width, 2):
                    grid[y][x] = character
        for x, column in enumerate(self.__matrix):
            for y, cell in enumerate(column):
                if cell:
                    grid[y << 1][x << 1] = '#'
        return '\n'.join(''.join(row) for row in grid)

    # noinspection PyAssignmentToLoopOrWithParameter
    def place_boats(self, sizes, patience=10):
        matrix_backup = [column.copy() for column in self.__matrix]
        available_backup = self.__available.copy()
        for _ in range(patience):
            # try to place all the boats
            for size in sizes:
                for _ in range(patience):
                    # try to place boat of current size
                    point = random.choice(tuple(self.__available))
                    method = random.choice(tuple(Orientation))
                    try:
                        # try to place a boat; does not mangle the matrix
                        self.make_boat(point, size, method)
                    except RuntimeError:
                        pass
                    else:
                        # break out of inner patience loop; go to next size
                        break  # on success
                else:
                    # break to outer patience loop; start from beginning
                    self.__matrix = [column.copy() for column in matrix_backup]
                    self.__available = available_backup.copy()
                    break  # on failure
            else:
                # break out of outer patience loop; all sizes were placed
                break  # on success
        else:
            raise RuntimeError('could not place the requested boats')

    def make_boat(self, point, size, method):
        backup = [column.copy() for column in self.__matrix]
        unusable = set()
        for offset in range(size):
            if method is Orientation.HORIZONTAL:
                block = self.mark_cell(point, x_offset=offset)
            elif method is Orientation.VERTICAL:
                block = self.mark_cell(point, y_offset=offset)
            else:
                raise ValueError('method was not understood')
            if block:
                unusable.update(block)
            else:
                self.__matrix = backup
                raise RuntimeError('cannot place boat')
        self.__available -= unusable

    def mark_cell(self, point, *, x_offset=0, y_offset=0):
        target = Point(point.x + x_offset, point.y + y_offset)
        if target in self.__available and \
                0 <= target.x < self.__width and \
                0 <= target.y < self.__height:
            self.__matrix[target.x][target.y] = True
            return {Point(target.x + xo, target.y + yo)
                    for xo in range(-1, 2)
                    for yo in range(-1, 2)}

if __name__ == '__main__':
    main()
</code>```

Body:
I wasn't quite sure how to word the title, sorry if it doesn't make sense/is misleading.

Note - a "boat" is 3 O's next to each other in an array, so

_|O|_  _|_|_
_|O|_  O|O|O
 |O|    | |

are boats.

So I have an a list of lists (n x n) (working with lists) in which I generate n boats at random spaces. I don't want the boats to be next to each other, touch by corners, or be on top of each other.

A tried checking if a boat would end up on top of another boat in the vein of this:

if board[y - 2][x] == 'O' or board[y + 2][x] == 'O' ...

and so on, which ended up being unsurprisingly long.

I also got index out of range errors, since I was sometimes checking for coordinates not in the field.

So, is there a way I can check for boats in every direction without going out of index range?

Better yet, any ideas on how to make the boats not generate next to each other?

The code for boat generation is here:

from random import *

side = int(input())
game_state = []

def generate_initial_state():

    for i in range(side):
        game_state.append([])
        for j in range(side):
            game_state[i].append('.')

    for i in range(side):
        # Generate boat origin on random coordinates within the game board,
        # if there's a boat already, generate new ones
        y_cor = randint(0, side-1)
        x_cor = randint(0, side-1)
        while game_state[y_cor][x_cor] == 'O':
            y_cor = randint(0, side - 1)
            x_cor = randint(0, side - 1)
        # Direct chooses if the boat will be generated up, down, or sideways
        direct = randint(1, 4)
        cycle = 0

        while cycle < 3:
        # Generates a boat going from origin in one direction,
        # if the boat would end outside the board, chooses a different direction
            if direct == 1:
                if y_cor + 2 >= side:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor + cycle][x_cor] = 'O'
                    cycle += 1
            elif direct == 2:
                if x_cor + 2 >= side:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor][x_cor + cycle] = 'O'
                    cycle += 1
            elif direct == 3:
                if y_cor - 2 < 0:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor - cycle][x_cor] = 'O'
                    cycle += 1
            elif direct == 4:
                if x_cor - 2 < 0:
                    direct = randint(1, 4)
                else:
                    game_state[y_cor][x_cor - cycle] = 'O'
                    cycle += 1

for i in range(side):
    print(*game_state[i])

Body:
You can try the following class and see if it solves your problem:

#! /usr/bin/env python3
import collections
import enum
import random

def main():
    board = Board(10, 10)
    print(board)
    board.place_boats([2, 3, 3, 4, 5])
    print('\n' + '=' * 21 + '\n')
    print(board)

Point = collections.namedtuple('Point', 'x, y')
# noinspection PyArgumentList
Orientation = enum.Enum('Orientation', 'HORIZONTAL, VERTICAL')

class Board:
    def __init__(self, width, height):
        self.__width = width
        self.__height = height
        self.__matrix = [[False] * height for _ in range(width)]
        self.__available = {Point(x, y)
                            for x in range(width)
                            for y in range(height)}

    def __str__(self):
        width = self.__width * 2 + 1
        height = self.__height * 2 + 1
        grid = [[' '] * width for _ in range(height)]
        for yo, xo, character in (0, 1, '|'), (1, 0, '-'), (1, 1, '+'):
            for y in range(yo, height, 2):
                for x in range(xo, width, 2):
                    grid[y][x] = character
        for x, column in enumerate(self.__matrix):
            for y, cell in enumerate(column):
                if cell:
                    grid[y << 1][x << 1] = '#'
        return '\n'.join(''.join(row) for row in grid)

    # noinspection PyAssignmentToLoopOrWithParameter
    def place_boats(self, sizes, patience=10):
        matrix_backup = [column.copy() for column in self.__matrix]
        available_backup = self.__available.copy()
        for _ in range(patience):
            # try to place all the boats
            for size in sizes:
                for _ in range(patience):
                    # try to place boat of current size
                    point = random.choice(tuple(self.__available))
                    method = random.choice(tuple(Orientation))
                    try:
                        # try to place a boat; does not mangle the matrix
                        self.make_boat(point, size, method)
                    except RuntimeError:
                        pass
                    else:
                        # break out of inner patience loop; go to next size
                        break  # on success
                else:
                    # break to outer patience loop; start from beginning
                    self.__matrix = [column.copy() for column in matrix_backup]
                    self.__available = available_backup.copy()
                    break  # on failure
            else:
                # break out of outer patience loop; all sizes were placed
                break  # on success
        else:
            raise RuntimeError('could not place the requested boats')

    def make_boat(self, point, size, method):
        backup = [column.copy() for column in self.__matrix]
        unusable = set()
        for offset in range(size):
            if method is Orientation.HORIZONTAL:
                block = self.mark_cell(point, x_offset=offset)
            elif method is Orientation.VERTICAL:
                block = self.mark_cell(point, y_offset=offset)
            else:
                raise ValueError('method was not understood')
            if block:
                unusable.update(block)
            else:
                self.__matrix = backup
                raise RuntimeError('cannot place boat')
        self.__available -= unusable

    def mark_cell(self, point, *, x_offset=0, y_offset=0):
        target = Point(point.x + x_offset, point.y + y_offset)
        if target in self.__available and \
                0 <= target.x < self.__width and \
                0 <= target.y < self.__height:
            self.__matrix[target.x][target.y] = True
            return {Point(target.x + xo, target.y + yo)
                    for xo in range(-1, 2)
                    for yo in range(-1, 2)}

if __name__ == '__main__':
    main()


来源: stackexchange

问:
Cannot list items with *ngFor
i want to make a simple adding friend and friend requests page for my app. i am using angularjs , angularfire2 and ionic 3.

```<code>    <ion-list>

  <ion-item *ngFor="let friendrequest of friendRequestArray; let i = index">
    <h2>{{friendrequest.$value}}</h2>

    <button ion-button  item-end>Accept</button>
    <button ion-button  item-end>Decline</button>
  </ion-item>

</ion-list>
</code>```

my ts code:

```<code>constructor(public navCtrl: NavController, public navParams: NavParams,
public alertCtrl: AlertController, private afDatabase: AngularFireDatabase, private afAuth: AngularFireAuth) {

  this.myUid = this.afAuth.auth.currentUser.uid;

  this.afDatabase.list(`users/${this.myUid}/friendrequests/`).subscribe(data => {

    this.friendRequestArray = data;
    console.log(this.friendRequestArray);
  });
</code>```

}

i am getting a console output like this:

so its working

error is:

```<code>   ERROR Error: Uncaught (in promise): Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
</code>```

my data:

```<code> "users" : {
"3YG0aYta1AP28COa7hdopwvICt63" : {
  "friendrequests" : {
    "test2" : "7LXXTyAH9MeKyqRBg3oP7b2Juox2",
    "test4" : "BaKWaeGrTzXHe4EQ60gpWYOoxKD2",
    "test6" : "nNl6pa0s7ZXULV0yFSIV4dLP0s13"
</code>```

i couldnt understand what it says. what i am doing wrong ? i can subscribe data in array form like i want but cannot list it with *ngfor please assist me thanks.

答:
I don't know how you have structured your data from firebase but friend request is not an Array so Angular can't iterate over it.

You can fix this by re-structuring your data to:

```<code>"users" : {
"3YG0aYta1AP28COa7hdopwvICt63" : {
  "friendrequests" : [
   { "test1" : "7LXXTyAH9MeKyqRBg3oP7b2Juox2" },
   { "test2" : "7LXXTyAH9MeKyqRBg3oP7b2Juox2" },
]
</code>```

Then you can do the loop from the template but don't forget to next the response value properly like this:

```<code>this.afDatabase.list(`users/${this.myUid}/friendrequests/`).subscribe(data => {

    this.friendRequestArray = data.this.myuid.friendrequests;
    console.log(this.friendRequestArray);
  });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cannot list items with *ngFor

Body:
i want to make a simple adding friend and friend requests page for my app. i am using angularjs , angularfire2 and ionic 3.

    <ion-list>

  <ion-item *ngFor="let friendrequest of friendRequestArray; let i = index">

{{friendrequest.$value}}

    <button ion-button  item-end>Accept</button>
    <button ion-button  item-end>Decline</button>
  </ion-item>

</ion-list>

my ts code:

constructor(public navCtrl: NavController, public navParams: NavParams,
public alertCtrl: AlertController, private afDatabase: AngularFireDatabase, private afAuth: AngularFireAuth) {

  this.myUid = this.afAuth.auth.currentUser.uid;

  this.afDatabase.list(`users/${this.myUid}/friendrequests/`).subscribe(data => {

    this.friendRequestArray = data;
    console.log(this.friendRequestArray);
  });

}

i am getting a console output like this:

so its working

error is:

   ERROR Error: Uncaught (in promise): Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

my data:

 "users" : {
"3YG0aYta1AP28COa7hdopwvICt63" : {
  "friendrequests" : {
    "test2" : "7LXXTyAH9MeKyqRBg3oP7b2Juox2",
    "test4" : "BaKWaeGrTzXHe4EQ60gpWYOoxKD2",
    "test6" : "nNl6pa0s7ZXULV0yFSIV4dLP0s13"

i couldnt understand what it says. what i am doing wrong ? i can subscribe data in array form like i want but cannot list it with *ngfor please assist me thanks.

Body:
I don't know how you have structured your data from firebase but friend request is not an Array so Angular can't iterate over it.

You can fix this by re-structuring your data to:

"users" : {
"3YG0aYta1AP28COa7hdopwvICt63" : {
  "friendrequests" : [
   { "test1" : "7LXXTyAH9MeKyqRBg3oP7b2Juox2" },
   { "test2" : "7LXXTyAH9MeKyqRBg3oP7b2Juox2" },
]

Then you can do the loop from the template but don't forget to next the response value properly like this:

this.afDatabase.list(`users/${this.myUid}/friendrequests/`).subscribe(data => {

    this.friendRequestArray = data.this.myuid.friendrequests;
    console.log(this.friendRequestArray);
  });


问:
How to log IP address in text file
```<code><?php
header ('Location: http://proxy4free.com');
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
   fwrite($handle, $variable);
   fwrite($handle, "=");
   fwrite($handle, $value);
   fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
</code>```

This is my code currently i'm practicing and i would like to know how to log ip address in text file with PHP. I have no idea, but made attempts.

答:
```<code><?php

$ip = $_SERVER['REMOTE_ADDR']; //get supposed IP

$handle = fopen("log.txt", "a"); //open log file

foreach($_POST as $variable => $value) { //loop through POST vars
fwrite($handle, $variable . "+" . $value . "\r\n");
}
fwrite($handle, "IP: $ip \r\n \r\n");
fclose($handle);

header ('Location: http://proxy4free.com');
exit;
</code>```

Title: How to log IP address in text file

Body:
<?php
header ('Location: http://proxy4free.com');
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
   fwrite($handle, $variable);
   fwrite($handle, "=");
   fwrite($handle, $value);
   fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>

This is my code currently i'm practicing and i would like to know how to log ip address in text file with PHP. I have no idea, but made attempts.


问:
Python: subtracting 2 already defined variables in a function
I seem to have having an issue with While Loops...

```<code>while True:
leave=input("\n"
           "\nDo you..."
            "\n"
            "\nA: Leave the ship and go out into forrest"
            "\nB: Stay in the ship and sleep through the night"
            "\n"
            "\n: ")
if leave.lower()in ("a","leave","leave the ship"):
    leaveA=("\n"
            "\nYou slowly make your way out through the hole"
            "\nand you slide down the ship. Once you reach the"
            "\nyou start to make your way through the dense"
            "\nforrest. As you make your way through the woods"
            "\nYou start to hear faint voices from your right."
            "\n")
    for char in leaveA:  # applying to each character
        time.sleep(0.01)  # the time delay
        sys.stdout.write(char)  # adding the typing effect
        sys.stdout.flush()
    health-=injure
    injury()
    print("\n"
          "\n-----Statistics-----"
          "\n"
          "\nHealth:", health,
          "\nEnergy:", energy,
          "\nArmour:", armour,
          "\nStamina:", stamina,
          "\nStrength:", strength,
          "\nAccuracy:", accuracy)

    flee=input("\n"
               "\nThis leaves you with two choices..."
               "\n"
               "\nA: Move towards the voices, in hopes that they will help
                you."
               "\nB: Run back to the ship to look for a weapon to defend
                 yourself."
               "\n"
               "\n: ")
</code>```

My problem is that if you choose option A in leave it never breaks so the loop will loop back to leave and if I break after the if statement the code will never reach the flee input. What I'm trying to do is to have option A in leave lead to flee and option B lead to something else I have later in the code. Any advice is appreciated.

答:
To help you solve your problem, allow me to present you the general strategy about how to go about this or many, many, many other problems:

Use the "divide and conquer" strategy:

You have a system that is consisting of multiple parts and the system doesn't work as expected. What do you do? You take each part and ask yourself: can I take this part away, without destroying the one function of the system that I am trying to get to work (that is not working now)?

If you can answer that question with "yes, I can take this away", then do so. That will reduce your problem and make it easier to understand until you ultimately have only those parts before you that are necessary.

Applied to your problem at hand: there are many lines of code, that server no purpose in the essential function your are trying to get to work.

The 'print("Statistics")' statement f.ex. can be dropped, it serves no purpose in your quest to get the loop working correctly.

Go ahead with this strategy and you should end up with a much shorter program in which you'll be able to spot the root problem at a glance.

Body:
I seem to have having an issue with While Loops...

while True:
leave=input("\n"
           "\nDo you..."
            "\n"
            "\nA: Leave the ship and go out into forrest"
            "\nB: Stay in the ship and sleep through the night"
            "\n"
            "\n: ")
if leave.lower()in ("a","leave","leave the ship"):
    leaveA=("\n"
            "\nYou slowly make your way out through the hole"
            "\nand you slide down the ship. Once you reach the"
            "\nyou start to make your way through the dense"
            "\nforrest. As you make your way through the woods"
            "\nYou start to hear faint voices from your right."
            "\n")
    for char in leaveA:  # applying to each character
        time.sleep(0.01)  # the time delay
        sys.stdout.write(char)  # adding the typing effect
        sys.stdout.flush()
    health-=injure
    injury()
    print("\n"
          "\n-----Statistics-----"
          "\n"
          "\nHealth:", health,
          "\nEnergy:", energy,
          "\nArmour:", armour,
          "\nStamina:", stamina,
          "\nStrength:", strength,
          "\nAccuracy:", accuracy)

    flee=input("\n"
               "\nThis leaves you with two choices..."
               "\n"
               "\nA: Move towards the voices, in hopes that they will help
                you."
               "\nB: Run back to the ship to look for a weapon to defend
                 yourself."
               "\n"
               "\n: ")

My problem is that if you choose option A in leave it never breaks so the loop will loop back to leave and if I break after the if statement the code will never reach the flee input. What I'm trying to do is to have option A in leave lead to flee and option B lead to something else I have later in the code. Any advice is appreciated.


问:
How to make a responsive row of images
I'm trying to work out how to make a row of images responsive to the window width. So far I have:

```<code><div class="image-slider">
  <div><img src="/img1.jpg"></div>
  <div><img src="/img2.jpg"></div>
  <div><img src="/img3.jpg"></div>
  <div><img src="/img4.jpg"></div>
  <div><img src="/img5.jpg"></div>
</div>
</code>```

and...

```<code>.image-slider {
  display: flex;
  overflow-y: scroll;
}

.image-slider div {
  flex: 1;
  margin: 5px
}

.image-slider div img {
  width: 100%;
  height: auto;
  min-width: 125px;
}
</code>```

This works nicely but what I want now is to make the fifth image disappear when the window is less than 880px and have the remaining four images resize to take up the remaining space.

I've tried adding a wide-only class to the fifth div tag:

```<code><div class="wide-only"><img src="/img5.jpg"></div>
</code>```

and then added a few media rules as shown below but it isn't quite working:

```<code>.image-slider div img.wide-only {
  display:none;
}

@media(min-width:880px) {
  .image-slider div img.wide-only {
    flex: 1 /* not sure what this should be - tried display: flex too */
  }
}
</code>```

答:
You added display:none so in the media query your should add display:block (i also corrected some CSS selector as you were not targeting the correct tag) :

```<code>.image-slider .wide-only {
  display:none;
}

@media(min-width:880px) {
  .image-slider .wide-only {
    display:block;
    flex: 1 /* not sure what this should be - tried display: flex too */
  }
}
</code>```

a full code :

.image-slider {
  display: flex;
  overflow-y: scroll;
}

.image-slider div {
  flex: 1;
  margin: 5px
}

.image-slider div img {
  width: 100%;
  height: auto;
  min-width: 125px;
}

.image-slider  .wide-only {
  display: none;
}

@media(min-width:880px) {
  .image-slider .wide-only {
    display: block;
    flex: 1/* not sure what this should be - tried display: flex too */
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-slider">
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div class="wide-only"><img src="https://lorempixel.com/400/400/"></div>
</div></code>```

Title: How to make a responsive row of images

Body:
I'm trying to work out how to make a row of images responsive to the window width. So far I have:

and...

.image-slider {
  display: flex;
  overflow-y: scroll;
}

.image-slider div {
  flex: 1;
  margin: 5px
}

.image-slider div img {
  width: 100%;
  height: auto;
  min-width: 125px;
}

This works nicely but what I want now is to make the fifth image disappear when the window is less than 880px and have the remaining four images resize to take up the remaining space.

I've tried adding a wide-only class to the fifth div tag:

and then added a few media rules as shown below but it isn't quite working:

.image-slider div img.wide-only {
  display:none;
}

@media(min-width:880px) {
  .image-slider div img.wide-only {
    flex: 1 /* not sure what this should be - tried display: flex too */
  }
}

Body:
You added display:none so in the media query your should add display:block (i also corrected some CSS selector as you were not targeting the correct tag) :

.image-slider .wide-only {
  display:none;
}

@media(min-width:880px) {
  .image-slider .wide-only {
    display:block;
    flex: 1 /* not sure what this should be - tried display: flex too */
  }
}

a full code :

.image-slider {
  display: flex;
  overflow-y: scroll;
}

.image-slider div {
  flex: 1;
  margin: 5px
}

.image-slider div img {
  width: 100%;
  height: auto;
  min-width: 125px;
}

.image-slider  .wide-only {
  display: none;
}

@media(min-width:880px) {
  .image-slider .wide-only {
    display: block;
    flex: 1/* not sure what this should be - tried display: flex too */
  }
}

<div class="image-slider">
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div class="wide-only"><img src="https://lorempixel.com/400/400/"></div>
</div>


问:
Tooltip doesn't let me type text when it is appeared. IDEA's editor
I am working with Itellij IDEA (2017.2.4). I am not sure whether the reason is new version of IDEA, but I started to face it after new version installed.

When I type some code in editor and Tooltip is shown (it can be inspection or just parameters of method shown ect.) I cannot type new symbols until pressing ESCAPE button, it is not useful for me. Before updating the IDEA there was behavior when user types new code, tooltip is hidden without ESCAPE pressing. It was made hidden by any key pressed.

Actually maybe I just change some setting property unconsciously, if yes - what is the property needed to be restored to default?

How to make it hidden not by ESCAPE but by any button?

In next image I pictured the moment when only ESCAPE key can be pressed.

答:
As I divined there was a property in settings that influences to the behavior described in a question. So to continue writing code without pressing ESCAPE key you must uncheck the following property:

Menu page Settings -> Appearance & Behavior -> System Settings

Checkbox Accessibility -> Support screen readers (requires start)

(for more details see the link)


问:
How to migrate two tomcat applications from separate servers to a single server?
I have a question about best practice around Tomcat installation.

Now we have two applications on separated server, with one tomcat instance for each application.

We want to merge the application into the same server, but I don't know the best practice to do that.

I see two possibilities:

I have one tomcat per application

I have one tomcat for all applications

Do you have experiences to share with me. I want to make sure that we proceed with the best option.

答:
I would recommend you to have only one Tomcat, however if there's a valid reason why need two instances you will have to run them on different ports, check this answer if you need help.

Note: I've never needed to run two instances of Tomcat on the same server, not even one time I had one app on https and other apps on http, almost everything is possible with the correct configuration.


问:
Linking a Button to a script on Google Docs
I'm trying to assign an image/button to a script function. Usually, in GSheets, I would right-click, and select the options, and then select a script. Is this not possible on Google Docs?

Example Image below on a GSheet.

答: You see the "Assign Script..." option. Click on it, and manually type-in the name of the function/script that you have in the Script Editor.</p>


问:
Matplotlib mathtext: Glyph errors in tick labels
I've observed errors when rendering math in matplotlib 2.0.2, when using the default mathtext as opposed to the LaTeX math rendering engine. It seems that some glyphs (in my case the minus and the multiplication sign) is not recognized by mathtext. What makes it really weird is that the error only occurs when these particular glyphs appear in tick labels. When I deliberately type some mathy expression into e.g. the figure title, it works fine.

Consider the below example and the resultant image:

```<code>import matplotlib
import matplotlib.pyplot as plt

# Customize matplotlib
matplotlib.rcParams.update({# Use mathtext, not LaTeX
                            'text.usetex': False,
                            # Use the Computer modern font
                            'font.family': 'serif',
                            'font.serif': 'cmr10',
                            'mathtext.fontset': 'cm',
                            })

# Plot
plt.semilogy([-0.03, 0.05], [0.3, 0.05])
plt.title(r'$-6\times 10^{-2}$')
plt.savefig('test.png')
</code>```

As seen on the image, multiplication and some minus signs in the tick labels have been replaced with other characters. If I use LaTeX (by setting 'text.usetex' to True), everything renders nicely. Why does this happen, and more importantly, how can I fix it without changing from mathtext to LaTeX?

Additional information

This is the warning which gets printed when running the example code:

```<code>mathtext.py:866: MathTextWarning: Font 'default' does not have a glyph for '\times' [U+d7]
  MathTextWarning)
mathtext.py:867: MathTextWarning: Substituting with a dummy symbol.
  warn("Substituting with a dummy symbol.", MathTextWarning)
</code>```

Note that the minus signs appearing in exponents get rendered correctly. These also do not render probably if I leave out 'mathtext.fontset': 'cm', producing another, similar warning:

```<code>mathtext.py:866: MathTextWarning: Font 'default' does not have a glyph for '-' [U+2212]
  MathTextWarning)
mathtext.py:867: MathTextWarning: Substituting with a dummy symbol.
  warn("Substituting with a dummy symbol.", MathTextWarning)
</code>```

Also, if I include 'axes.unicode_minus': False in the rcParams (and keep 'mathtext.fontset': 'cm'), all minus signs render properly, though the problem remains for the multiplication signs.

The multiplication sign error do not seem to be a problem on older versions of matplotlib (I've tested 1.5.1, 1.4.3 and 1.3.1). However, these matplotib's insist on only producing tick labels at 10⁻², 10⁻¹, 1, 10, 10² etc., and so no multiplication sign is ever needed.

Bug report

This has been submitted as a bug report to Matplotlib.

答:
I find the STIX fonts to be acceptable substitutes for computer modern.

```<code>import matplotlib
import matplotlib.pyplot as plt

# Customize matplotlib
matplotlib.rcParams.update(
    {
        'text.usetex': False,
        'font.family': 'stixgeneral',
        'mathtext.fontset': 'stix',
    }
)

# Plot
plt.semilogy([-0.03, 0.05], [0.3, 0.05])
plt.title(r'$-6\times 10^{-2}$')
plt.savefig('test.png')
</code>```

This produces the following output on my laptop:

ContentLicense: CC BY-SA 4.0

Body:
I've observed errors when rendering math in matplotlib 2.0.2, when using the default mathtext as opposed to the LaTeX math rendering engine. It seems that some glyphs (in my case the minus and the multiplication sign) is not recognized by mathtext. What makes it really weird is that the error only occurs when these particular glyphs appear in tick labels. When I deliberately type some mathy expression into e.g. the figure title, it works fine.

Consider the below example and the resultant image:

import matplotlib
import matplotlib.pyplot as plt

# Customize matplotlib
matplotlib.rcParams.update({# Use mathtext, not LaTeX
                            'text.usetex': False,
                            # Use the Computer modern font
                            'font.family': 'serif',
                            'font.serif': 'cmr10',
                            'mathtext.fontset': 'cm',
                            })

# Plot
plt.semilogy([-0.03, 0.05], [0.3, 0.05])
plt.title(r'$-6\times 10^{-2}$')
plt.savefig('test.png')

As seen on the image, multiplication and some minus signs in the tick labels have been replaced with other characters. If I use LaTeX (by setting 'text.usetex' to True), everything renders nicely. Why does this happen, and more importantly, how can I fix it without changing from mathtext to LaTeX?

Additional information

This is the warning which gets printed when running the example code:

mathtext.py:866: MathTextWarning: Font 'default' does not have a glyph for '\times' [U+d7]
  MathTextWarning)
mathtext.py:867: MathTextWarning: Substituting with a dummy symbol.
  warn("Substituting with a dummy symbol.", MathTextWarning)

Note that the minus signs appearing in exponents get rendered correctly. These also do not render probably if I leave out 'mathtext.fontset': 'cm', producing another, similar warning:

mathtext.py:866: MathTextWarning: Font 'default' does not have a glyph for '-' [U+2212]
  MathTextWarning)
mathtext.py:867: MathTextWarning: Substituting with a dummy symbol.
  warn("Substituting with a dummy symbol.", MathTextWarning)

Also, if I include 'axes.unicode_minus': False in the rcParams (and keep 'mathtext.fontset': 'cm'), all minus signs render properly, though the problem remains for the multiplication signs.

The multiplication sign error do not seem to be a problem on older versions of matplotlib (I've tested 1.5.1, 1.4.3 and 1.3.1). However, these matplotib's insist on only producing tick labels at 10⁻², 10⁻¹, 1, 10, 10² etc., and so no multiplication sign is ever needed.

Bug report

This has been submitted as a bug report to Matplotlib.

Body:
I find the STIX fonts to be acceptable substitutes for computer modern.

import matplotlib
import matplotlib.pyplot as plt

# Customize matplotlib
matplotlib.rcParams.update(
    {
        'text.usetex': False,
        'font.family': 'stixgeneral',
        'mathtext.fontset': 'stix',
    }
)

# Plot
plt.semilogy([-0.03, 0.05], [0.3, 0.05])
plt.title(r'$-6\times 10^{-2}$')
plt.savefig('test.png')

This produces the following output on my laptop:


问:
How can 'String#reverse' return non-'String' objects?
I have a class Word:

```<code>class Word < String
end

w = Word.new("level")
y = w.reverse
y.class # => Word
</code>```

1) How is this possible? Word#reverse should return a String because it inherits String#reverse, which returns a String.

I added this code:

```<code>class Word < String
  attr_accessor :s

  def magic
    @s = Time.now
  end
end

y.magic
sleep(5)
w.magic
y.s == w # => false
y == w # => true
</code>```

2) w and y are Word, and are equal, hence they both have the same methods, such as magic. Where did y acquire the magic method?

3) How come y == w evaluates to true while y.s and w.s return unequal values?

答:
While the documentation for String#reverse states:

Returns a new string with the characters from str in reverse order.

and so you might expect a return type of String, if you pop open the method you can see the line

```<code>rev = rb_str_new_with_class(str, 0, RSTRING_LEN(str));
</code>```

and that rev is what actually gets returned. My C is fairly rusty, but looking around the C code for ruby, that method rb_str_new_with_class seems to be doing exactly what it says, it creates a new instance of whatever class str is, in this case Word. So, what the documentation means when it says it returns a new string, is that it returns a new instance of whatever class this string is, which in most cases is String.

So knowing that it creates a new instance of whatever class the current string is, it's easy to see how w.reverse ended up having a magic method...because Word gave it the method, and it is a Word.

And finally, how are they equal? You don't define a new == method on Word, so it takes the parent String#== method, which doesn't know or care that there are instance variables and just compares the values of the string, coercing things using to_str if necessary and able, you could even do:

```<code>Word.new("level") == "level" # => true
</code>```

(Note: I'm not actually sure if Word gets coerced or not.)

Body:
I have a class Word:

class Word < String
end

w = Word.new("level")
y = w.reverse
y.class # => Word

1) How is this possible? Word#reverse should return a String because it inherits String#reverse, which returns a String.

I added this code:

class Word < String
  attr_accessor :s

  def magic
    @s = Time.now
  end
end

y.magic
sleep(5)
w.magic
y.s == w # => false
y == w # => true

2) w and y are Word, and are equal, hence they both have the same methods, such as magic. Where did y acquire the magic method?

3) How come y == w evaluates to true while y.s and w.s return unequal values?

Body:
While the documentation for String#reverse states:

Returns a new string with the characters from str in reverse order.

and so you might expect a return type of String, if you pop open the method you can see the line

rev = rb_str_new_with_class(str, 0, RSTRING_LEN(str));

and that rev is what actually gets returned. My C is fairly rusty, but looking around the C code for ruby, that method rb_str_new_with_class seems to be doing exactly what it says, it creates a new instance of whatever class str is, in this case Word. So, what the documentation means when it says it returns a new string, is that it returns a new instance of whatever class this string is, which in most cases is String.

So knowing that it creates a new instance of whatever class the current string is, it's easy to see how w.reverse ended up having a magic method...because Word gave it the method, and it is a Word.

And finally, how are they equal? You don't define a new == method on Word, so it takes the parent String#== method, which doesn't know or care that there are instance variables and just compares the values of the string, coercing things using to_str if necessary and able, you could even do:

Word.new("level") == "level" # => true

(Note: I'm not actually sure if Word gets coerced or not.)


问:
improve locality and decrease Cache pollution in a medical image reconstruction implementation
I'm doing a research for my University related to an Image reconstruction algorithm for medical usage.

I'm stuck in something up to 3 weeks, I need to improve the performance of the following code:

```<code>for (lor=lor0[mypid]; lor <= lor1[mypid]; lor++)
{
  LOR_X = P.symmLOR[lor].x;
  LOR_Y = P.symmLOR[lor].y;
  LOR_XY = P.symmLOR[lor].xy;
  lor_z = P.symmLOR[lor].z;
  LOR_Z_X = P.symmLOR[lor_z].x;
  LOR_Z_Y = P.symmLOR[lor_z].y;
  LOR_Z_XY = P.symmLOR[lor_z].xy;

  s0 = P.a2r[lor];
  s1 = P.a2r[lor+1];

  for (s=s0; s < s1; s++)
  {
    pixel     = P.a2b[s];
    v         = P.a2p[s];

    b[lor]    += v * x[pixel];

    p          = P.symm_Xpixel[pixel];
    b[LOR_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel];
    b[LOR_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel];
    b[LOR_XY] += v * x[p];

    // do Z symmetry.
    pixel_z    = P.symm_Zpixel[pixel];
    b[lor_z]  += v * x[pixel_z];

    p          = P.symm_Xpixel[pixel_z];
    b[LOR_Z_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel_z];
    b[LOR_Z_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel_z];
    b[LOR_Z_XY] += v * x[p];

   }

}
</code>```

for anyone who wants to know, The code implements the MLEM forward function and all the variables are FLOAT.

After several tests, I had notice that the big delay was on this part of the code. (you know, the 90 - 10 rule).

Later, I used Papi (http://cl.cs.utk.edu/papi/) to measure L1D cache misses. As I thought, Papi confirm that the performance decreases due to higher amount of misses, particularly for the random access to b vector (huge in size).

Reading information on the Internet I just know two options to improve performance so far: improve data locality or decrease data pollution.

To do the first improvement, I'll try to change the code to be cache aware, just like was propossed by Ulrich Drepper on What every programmer should know about the memory (www.akkadia.org/drepper/cpumemory.pdf) A.1 Matrix multiplication.

I believe that blocking the SpMV (sparse matrix-vector Multiplication) will improve the performance.

On the other hand, every time the program tried to access to b vector, we had what is known as cache pollution.

Is there's a way to do a load a value from the b vector with SIMD instruction without using the Cache?

Also, it is possible to use a function like void _mm_stream_ps(float * p , __m128 a ) to store ONE float value on the vector b without polluting the Cache?

I can't use _mm_stream_ps because always store 4 floats but the access to the b vector is clearly random.

I'd hope to be clear in my dilemma.

More info: v is the column value of an Sparse Matrix store with CRS format. I realize that other optimization could be done if I tried to change CRS format to other, however, like I said before, I'd made several test for months and I know that the performance decrease is related to random access on vector b. from 400.000.000 L1D Misses I can go to 100~ Misses when I don't store in vector b.

Thanks.

答:
I won't even pretend that I know what the code is doing :)  But one possible cause for some extra memory access is aliasing: if the compiler can't be sure that b, x, and the various P.symm arrays don't overlap, then writes to b will affect how reads from x and the P.symm's can be scheduled. If the compiler is particularly pessimistic, it might even force the fields of P to be re-fetched from memory. All of this will contribute to the cache misses you're seeing. Two simple ways to improve this are:

Use __restrict on b. This guarantees that b doesn't overlap the other arrays, so writes to it won't affect reads (or writes) from other arrays.

Reorder things so that all the reads from P.symm's are first, then the reads from x, then finally all the writes to b. This should break up some of the dependencies in the reads and the compiler schedule the reads from P.symm's in parallel, then the reads from x in parallel, and hopefully do the writes to b sensibly.

One other stylistic thing (which will help with point #2) is to not reuse variables so p so much. There's no reason you can't have e.g. p_x, p_y, p_xy, etc. and it will make reordering the code easier.

Once that's all in place, you can start sprinkling prefetch instructions (i.e. __builtin_prefetch on gcc) ahead of known cache misses.

Hope that helps.

ContentLicense: CC BY-SA 2.5

Body:
I'm doing a research for my University related to an Image reconstruction algorithm for medical usage.

I'm stuck in something up to 3 weeks, I need to improve the performance of the following code:

for (lor=lor0[mypid]; lor <= lor1[mypid]; lor++)
{
  LOR_X = P.symmLOR[lor].x;
  LOR_Y = P.symmLOR[lor].y;
  LOR_XY = P.symmLOR[lor].xy;
  lor_z = P.symmLOR[lor].z;
  LOR_Z_X = P.symmLOR[lor_z].x;
  LOR_Z_Y = P.symmLOR[lor_z].y;
  LOR_Z_XY = P.symmLOR[lor_z].xy;

  s0 = P.a2r[lor];
  s1 = P.a2r[lor+1];

  for (s=s0; s < s1; s++)
  {
    pixel     = P.a2b[s];
    v         = P.a2p[s];

    b[lor]    += v * x[pixel];

    p          = P.symm_Xpixel[pixel];
    b[LOR_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel];
    b[LOR_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel];
    b[LOR_XY] += v * x[p];

    // do Z symmetry.
    pixel_z    = P.symm_Zpixel[pixel];
    b[lor_z]  += v * x[pixel_z];

    p          = P.symm_Xpixel[pixel_z];
    b[LOR_Z_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel_z];
    b[LOR_Z_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel_z];
    b[LOR_Z_XY] += v * x[p];

   }

}

for anyone who wants to know, The code implements the MLEM forward function and all the variables are FLOAT.

After several tests, I had notice that the big delay was on this part of the code. (you know, the 90 - 10 rule).

Later, I used Papi (http://cl.cs.utk.edu/papi/) to measure L1D cache misses. As I thought, Papi confirm that the performance decreases due to higher amount of misses, particularly for the random access to b vector (huge in size).

Reading information on the Internet I just know two options to improve performance so far: improve data locality or decrease data pollution.

To do the first improvement, I'll try to change the code to be cache aware, just like was propossed by Ulrich Drepper on What every programmer should know about the memory (www.akkadia.org/drepper/cpumemory.pdf) A.1 Matrix multiplication.

I believe that blocking the SpMV (sparse matrix-vector Multiplication) will improve the performance.

On the other hand, every time the program tried to access to b vector, we had what is known as cache pollution.

Is there's a way to do a load a value from the b vector with SIMD instruction without using the Cache?

Also, it is possible to use a function like void _mm_stream_ps(float * p , __m128 a ) to store ONE float value on the vector b without polluting the Cache?

I can't use _mm_stream_ps because always store 4 floats but the access to the b vector is clearly random.

I'd hope to be clear in my dilemma.

More info: v is the column value of an Sparse Matrix store with CRS format. I realize that other optimization could be done if I tried to change CRS format to other, however, like I said before, I'd made several test for months and I know that the performance decrease is related to random access on vector b. from 400.000.000 L1D Misses I can go to 100~ Misses when I don't store in vector b.

Thanks.


问:
Redux action not present
I have set up correctly according to doc redux boilerplate.
I have a folder of various action files which contains actions.
In this folder I have created an index.js where I am exporting all these files. I import it as named export.
When I console log the function itself it is there, but when I console log out this.props its not present.
I have tried to console log out the function outside the class its undefined.

If I import the action directly from the file it is defined in it works.

actions/formActions.js

```<code>export const formInput = (key, val) => (
    {
        type: FORM_INPUT,
        payload: { key, val }
    }
);
</code>```

actions/index.js

```<code>export * from './formActions';
</code>```

FormComp.js

```<code>import { formInput } from './actions'; //  <-- this.props.formInput = undefined
</code>```

or

```<code>import { formInput } from './actions/formActions'; //  <-- this.props.formInput = func
</code>```

connect:

```<code>class InputField extends Component { ... }

const FormComp = connect(({ forms }) => ({ forms }), { formInput })(InputField);

export { FormComp };
</code>```

edit1: If I inside componentWillMount() console.log(formInput) //without this.props its there.

edit2 (solution?):
I was able to map actions to props with bindActionCreators. How ever I don't understand why I need to use bindActionCreators and why I can't just export connect as it is with actions as second param.

```<code>const FormComp = connect(
  ({ forms }) => ({ forms }),
  dispatch => bindActionCreators({ formInput }, dispatch)
)(InputField);
</code>```

答:
The reason this.props.formInput is not defined but formInput is defined is because the redux connect is not properly setting the function formInput against the variable(property) formInput within the component props.

formInput is the function you are importing,

this.props.formInput is the property that should "point" to the function you import.

Try (I have separated out for clarity)

```<code>function mapStateToProps(state) {
    return {
      forms: state.forms
    }
  }
function mapDispatchToProps(dispatch) {
  return {
    formInput: (key, val) => dispatch(formInput(key val))
  };
}

export connect(
  mapStateToProps,
  mapDispatchToProps
)(InputField);
</code>```

Then anywhere in your code you call

```<code>this.props.formInput(key, val);
</code>```

This will call the action via props, and therefore will dispatch. properly

Title: Redux action not present

Body:
I have set up correctly according to doc redux boilerplate.
I have a folder of various action files which contains actions.
In this folder I have created an index.js where I am exporting all these files. I import it as named export.
When I console log the function itself it is there, but when I console log out this.props its not present.
I have tried to console log out the function outside the class its undefined.

If I import the action directly from the file it is defined in it works.

actions/formActions.js

export const formInput = (key, val) => (
    {
        type: FORM_INPUT,
        payload: { key, val }
    }
);

actions/index.js

export * from './formActions';

FormComp.js

import { formInput } from './actions'; //  <-- this.props.formInput = undefined

or

import { formInput } from './actions/formActions'; //  <-- this.props.formInput = func

connect:

class InputField extends Component { ... }

const FormComp = connect(({ forms }) => ({ forms }), { formInput })(InputField);

export { FormComp };

edit1: If I inside componentWillMount() console.log(formInput) //without this.props its there.

edit2 (solution?):
I was able to map actions to props with bindActionCreators. How ever I don't understand why I need to use bindActionCreators and why I can't just export connect as it is with actions as second param.

const FormComp = connect(
  ({ forms }) => ({ forms }),
  dispatch => bindActionCreators({ formInput }, dispatch)
)(InputField);

Body:
The reason this.props.formInput is not defined but formInput is defined is because the redux connect is not properly setting the function formInput against the variable(property) formInput within the component props.

formInput is the function you are importing,

this.props.formInput is the property that should "point" to the function you import.

Try (I have separated out for clarity)

function mapStateToProps(state) {
    return {
      forms: state.forms
    }
  }
function mapDispatchToProps(dispatch) {
  return {
    formInput: (key, val) => dispatch(formInput(key val))
  };
}

export connect(
  mapStateToProps,
  mapDispatchToProps
)(InputField);

Then anywhere in your code you call

this.props.formInput(key, val);

This will call the action via props, and therefore will dispatch. properly


问:
Execute sql query from tab click event
I have a project where I am connecting my database to the windows application in vb.net. I am required to make tabs that sort the data in a specific way. For example, it is a student database with names, etc. So When I press the "Student by Last name" tab, it sorts the data by last name in ascending order. So, I made a query which brought a button, but I don't know how to execute the button automatically when the tab page is clicked. The user can't have the control of sorting. The tab does it itself. Any help will be great! I have been looking everywhere for help.</p>

```<code>Private Sub TabPage2_Click(sender As Object, e As EventArgs) Handles tbLastName.Click
        TabPage1.Hide() "this is made to get rid of previous page, but may be unnecessary"
        tbLastName.Show() "this is supposed to show the data"
        Sort_By_LastNameToolStripButton.Enabled() "My attempt to execute code from the query button that I made hidden"

    End Sub
</code>```

答: Try the tab control Selected event to run your database code</p>

Title: Execute sql query from tab click event

Body:
I have a project where I am connecting my database to the windows application in vb.net. I am required to make tabs that sort the data in a specific way. For example, it is a student database with names, etc. So When I press the "Student by Last name" tab, it sorts the data by last name in ascending order. So, I made a query which brought a button, but I don't know how to execute the button automatically when the tab page is clicked. The user can't have the control of sorting. The tab does it itself. Any help will be great! I have been looking everywhere for help.

Private Sub TabPage2_Click(sender As Object, e As EventArgs) Handles tbLastName.Click
        TabPage1.Hide() "this is made to get rid of previous page, but may be unnecessary"
        tbLastName.Show() "this is supposed to show the data"
        Sort_By_LastNameToolStripButton.Enabled() "My attempt to execute code from the query button that I made hidden"

    End Sub


问:
Insert javascript object in php function
I want to insert some a circle created with javascript in my woocommerce shortcode created in php.
So far i've saved the javascript in assets under js with the file name. So basically i want to show my circle on my wordpress website.

The PHP looks like this:

```<code>// Add Shortcode
function get_cart_count() {

    // Code
/**
 * Check if WooCommerce is active
 **/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     global $woocommerce;
         echo '<script> function(state, circle) </script>';
    echo cat_cart_count( 22 ). "<span> ud af 5 samples </span>";
        echo "<br>Total: ".$woocommerce->cart->get_cart_total();

}
}
add_shortcode( 'cart_count', 'get_cart_count' );
</code>```

and the javascript for drawing the circle is:

```<code>var bar = new ProgressBar.Circle(container, {
  color: '#57bf6d',
  // This has to be the same size as the maximum width to
  // prevent clipping
  strokeWidth: 5,
  trailWidth: 10,
  easing: 'easeInOut',
  duration: 1400,
  text: {
    autoStyleContainer: false

  },
  from: { color: '#333', width: 7 },
  to: { color: '#57bf6d', width: 10 },
  // Set default step function for all animate calls
  step: function(state, circle) {
    circle.path.setAttribute('stroke', state.color);
    circle.path.setAttribute('stroke-width', state.width);

    var value = Math.round(circle.value() * 5);
    if (value === 0) {
      circle.setText('');
    } else {
      circle.setText( value +' / 5');
    }

  }
});
bar.text.style.fontFamily = '"Montserrat", Helvetica, sans-serif';
bar.text.style.fontSize = '2rem';

var newvalue = 2;
bar.animate( newvalue * 0.2);  // Number from 0.0 to 1.0
</code>```

答:
You can do something like this: </p>

```<code>// Add Shortcode
function get_cart_count() {

/**
 * Check if WooCommerce is active
 **/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     global $woocommerce;
     ?>
     <script>
        jQuery( document ).ready(function() {
        function DrawCircle() {
        var bar = new ProgressBar.Circle(container, {
          color: '#57bf6d',
          // This has to be the same size as the maximum width to
          // prevent clipping
          strokeWidth: 5,
          trailWidth: 10,
          easing: 'easeInOut',
          duration: 1400,
          text: {
            autoStyleContainer: false

          },
          from: { color: '#333', width: 7 },
          to: { color: '#57bf6d', width: 10 },
          // Set default step function for all animate calls
          step: function(state, circle) {
            circle.path.setAttribute('stroke', state.color);
            circle.path.setAttribute('stroke-width', state.width);

            var value = Math.round(circle.value() * 5);
            if (value === 0) {
              circle.setText('');
            } else {
              circle.setText( value +' / 5');
            }

          }
        });
        bar.text.style.fontFamily = '"Montserrat", Helvetica, sans-serif';
        bar.text.style.fontSize = '2rem';

        var newvalue = 2;
        bar.animate( newvalue * 0.2);  // Number from 0.0 to 1.0
        }

        DrawCircle();
        });
     </script>
     <?php
        echo cat_cart_count( 22 ). "<span> ud af 5 samples </span>";
        echo "<br>Total: ".$woocommerce->cart->get_cart_total();

}
}
add_shortcode( 'cart_count', 'get_cart_count' );
</code>```

Body:
I want to insert some a circle created with javascript in my woocommerce shortcode created in php.
So far i've saved the javascript in assets under js with the file name. So basically i want to show my circle on my wordpress website.

The PHP looks like this:

// Add Shortcode
function get_cart_count() {

    // Code
/**
 * Check if WooCommerce is active
 **/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     global $woocommerce;
         echo '';
    echo cat_cart_count( 22 ). " ud af 5 samples ";
        echo "
Total: ".$woocommerce->cart->get_cart_total();

}
}
add_shortcode( 'cart_count', 'get_cart_count' );

and the javascript for drawing the circle is:

var bar = new ProgressBar.Circle(container, {
  color: '#57bf6d',
  // This has to be the same size as the maximum width to
  // prevent clipping
  strokeWidth: 5,
  trailWidth: 10,
  easing: 'easeInOut',
  duration: 1400,
  text: {
    autoStyleContainer: false

  },
  from: { color: '#333', width: 7 },
  to: { color: '#57bf6d', width: 10 },
  // Set default step function for all animate calls
  step: function(state, circle) {
    circle.path.setAttribute('stroke', state.color);
    circle.path.setAttribute('stroke-width', state.width);

    var value = Math.round(circle.value() * 5);
    if (value === 0) {
      circle.setText('');
    } else {
      circle.setText( value +' / 5');
    }

  }
});
bar.text.style.fontFamily = '"Montserrat", Helvetica, sans-serif';
bar.text.style.fontSize = '2rem';

var newvalue = 2;
bar.animate( newvalue * 0.2);  // Number from 0.0 to 1.0

Body:
You can do something like this:

// Add Shortcode
function get_cart_count() {

/**
 * Check if WooCommerce is active
 **/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
     global $woocommerce;
     ?>
     <script>
        jQuery( document ).ready(function() {
        function DrawCircle() {
        var bar = new ProgressBar.Circle(container, {
          color: '#57bf6d',
          // This has to be the same size as the maximum width to
          // prevent clipping
          strokeWidth: 5,
          trailWidth: 10,
          easing: 'easeInOut',
          duration: 1400,
          text: {
            autoStyleContainer: false

          },
          from: { color: '#333', width: 7 },
          to: { color: '#57bf6d', width: 10 },
          // Set default step function for all animate calls
          step: function(state, circle) {
            circle.path.setAttribute('stroke', state.color);
            circle.path.setAttribute('stroke-width', state.width);

            var value = Math.round(circle.value() * 5);
            if (value === 0) {
              circle.setText('');
            } else {
              circle.setText( value +' / 5');
            }

          }
        });
        bar.text.style.fontFamily = '"Montserrat", Helvetica, sans-serif';
        bar.text.style.fontSize = '2rem';

        var newvalue = 2;
        bar.animate( newvalue * 0.2);  // Number from 0.0 to 1.0
        }

        DrawCircle();
        });
     </script>
     <?php
        echo cat_cart_count( 22 ). "<span> ud af 5 samples </span>";
        echo "<br>Total: ".$woocommerce->cart->get_cart_total();

}
}
add_shortcode( 'cart_count', 'get_cart_count' );


问:
C: How to find the day name for a given day of the year input by user
The user inputs a day of a month and a month and then the output will give the user the day of the year. For example:

-input: day=24, month=2

-output: day=55

So my question is how do I give the day name like Wednesday, Monday, etc. for the day of the year? For example:

-input: day=1, month=1

-output: day=1, Sunday

Here's my code:

```<code>int countDays(int, int, int[]);

int main() {
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day, month;

  printf("enter day: ");
  scanf("%d", &day);

  printf("Enter month: ");
  scanf("%d", &month);

  printf("There are %d days \n", countDays(day, month, daysInMonth));
  return 0;
}

int countDays(int day, int month, int daysInMonth[]) {
  char *c[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  int charc[6];
  int k, j, a;
  int b = 0;
  int dayno[31][12];
  for (k = 0; k < 12; k++) {
    for (j = 0; j < daysInMonth[k]; j++) {

      dayno[j][k] = ++b;
    }
    a = dayno[day - 1][month - 1];
  }
  return a;
}
</code>```

答:
```<code>#include <stdio.h>

char *WEEK[] =  {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int DAYS_IN_MONTH[] =  {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

int countDays(int day, int month);
char *dayName(int day);

int main(){
    int day, month;

    printf("enter day: ");
    scanf("%d", &day);

    printf("Enter month: ");
    scanf("%d", &month);

    int days = countDays(day, month);
    if(days != -1){
        printf("There are %i days \n", days);
        printf("The day name is %s\n", dayName(days));
    }else{
        printf("Error\n");
    }

    return 0;
}

int countDays(int day, int month){
    if(day >DAYS_IN_MONTH[month-1])
        return -1;

    int num_days = 0;
    for(int i = 0;i < month-1;i++){
        num_days+=DAYS_IN_MONTH[i];
    }
    return num_days+day;

}

char *dayName(int days){
    return WEEK[(days-1) % 7];
}
</code>```

Body:
The user inputs a day of a month and a month and then the output will give the user the day of the year. For example:

-input: day=24, month=2

-output: day=55

So my question is how do I give the day name like Wednesday, Monday, etc. for the day of the year? For example:

-input: day=1, month=1

-output: day=1, Sunday

Here's my code:

int countDays(int, int, int[]);

int main() {
  int daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int day, month;

  printf("enter day: ");
  scanf("%d", &day);

  printf("Enter month: ");
  scanf("%d", &month);

  printf("There are %d days \n", countDays(day, month, daysInMonth));
  return 0;
}

int countDays(int day, int month, int daysInMonth[]) {
  char *c[]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
  int charc[6];
  int k, j, a;
  int b = 0;
  int dayno[31][12];
  for (k = 0; k < 12; k++) {
    for (j = 0; j < daysInMonth[k]; j++) {

      dayno[j][k] = ++b;
    }
    a = dayno[day - 1][month - 1];
  }
  return a;
}


问:
Generate grid with tiles attributes from server
I'm generating grid of tiles with jQuery and now I wanna give them attributes which I wanna get from array and later from server. It would be good to do this without giving an ID for any tile. Any ideas how to do this?

function createGrid() {
    myGrid = $('<tileBox>');
    var rows = 1;
    var cols = 10;
    for (var i = 0; i < rows; i++) {
        var row = $('
').appendTo(myGrid);
        for (var j = 0; j < cols; j++) {
            $('<tile>').appendTo(row);
        }
    }
    myGrid.appendTo("#container");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tile{
  /* width: 50px;
  height: 50px; */
  padding: 50px;
  margin: 15;
  border: 1px solid;
  background-color: red;
}</code>```

    <link rel="stylesheet" type="text/css" href="MetroUI.css">

```

答:
Ok. So if your making a grid in your example its 1 row 10 columns then you would just store the attributes in an array marker 0 being grid 1. So in your array of data (or server data) you need 10 objects. If the grid was 4x4 16 objects.

```<code>var grid=[{name:"grid1"},{name:"grid2"},{name:"grid3"},{name:"grid4"}];
</code>```

I have used name for my attribute it could be anything, my grids being named grid1,grid2 are not id's they are just values they could be a,b,c,d...

All you now do is add the attributes as you draw your grid like so;

I'm using your code for simplicity:

```<code>// i use a marker to step through my array of data!
var gridMarker=0;

for (var i = 0; i < rows; i++) {
    var row = $('<tr>').appendTo(myGrid);
    for (var j = 0; j < cols; j++) {
      // replace the hash on your tile to add my array.name data
      $('<tile data-name="#">'.replace("#",grid[marker].name).appendTo(row);
      // increment my marker;
      marker++;
    }
}
</code>```

You could speed things up and improve the whole thing if you used a client side template engine. If you google jquery templates or just javascript template you will find a number of them, the docs are self explanatory.

Body:
I'm generating grid of tiles with jQuery and now I wanna give them attributes which I wanna get from array and later from server. It would be good to do this without giving an ID for any tile. Any ideas how to do this?

function createGrid() {
    myGrid = $('<tileBox>');
    var rows = 1;
    var cols = 10;
    for (var i = 0; i < rows; i++) {
        var row = $('
').appendTo(myGrid);
        for (var j = 0; j < cols; j++) {
            $('<tile>').appendTo(row);
        }
    }
    myGrid.appendTo("#container");
}

tile{
  /* width: 50px;
  height: 50px; */
  padding: 50px;
  margin: 15;
  border: 1px solid;
  background-color: red;
}

    <link rel="stylesheet" type="text/css" href="MetroUI.css">

Body:
Ok. So if your making a grid in your example its 1 row 10 columns then you would just store the attributes in an array marker 0 being grid 1. So in your array of data (or server data) you need 10 objects. If the grid was 4x4 16 objects.

var grid=[{name:"grid1"},{name:"grid2"},{name:"grid3"},{name:"grid4"}];

I have used name for my attribute it could be anything, my grids being named grid1,grid2 are not id's they are just values they could be a,b,c,d...

All you now do is add the attributes as you draw your grid like so;

I'm using your code for simplicity:

// i use a marker to step through my array of data!
var gridMarker=0;

for (var i = 0; i < rows; i++) {
    var row = $('<tr>').appendTo(myGrid);
    for (var j = 0; j < cols; j++) {
      // replace the hash on your tile to add my array.name data
      $('<tile data-name="#">'.replace("#",grid[marker].name).appendTo(row);
      // increment my marker;
      marker++;
    }
}

You could speed things up and improve the whole thing if you used a client side template engine. If you google jquery templates or just javascript template you will find a number of them, the docs are self explanatory.


问:
picasso image not loading in custom infoWindow why?
I'm trying to layout a custom infoWindow programmatically.  I want to load a streetView preview image using Picasso but the image isn't showing up, any idea why?

```<code>private View prepareInfoView(Marker marker){
    //prepare InfoView programmatically
    LinearLayout infoView = new LinearLayout(EarthquakeActivity.this);
    LinearLayout.LayoutParams infoViewParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    infoView.setOrientation(LinearLayout.VERTICAL);
    // attach the above layout to the infoView
    infoView.setLayoutParams(infoViewParams);

    //create street view preview @ top
    ImageView streetViewPreviewIV = new ImageView(EarthquakeActivity.this);
    // this scales the image to match parents WIDTH?, but retain image's height??
    LinearLayout.LayoutParams streetViewImageViewParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    streetViewPreviewIV.setLayoutParams(streetViewImageViewParams);

    String imageURL = "https://maps.googleapis.com/maps/api/streetview?size=200x200&location=";
    String markerLongitude = Double.toString(marker.getPosition().longitude);
    String markerLatitude = Double.toString(marker.getPosition().latitude);
    imageURL += markerLatitude + "," + markerLongitude + "&fov=120&heading=0&pitch=0";
    Log.wtf("prepareInfoView", imageURL);

    Picasso.with(this).load(imageURL).into(streetViewPreviewIV);
    infoView.addView(streetViewPreviewIV);
</code>```

I've tried with and without the api key appending the url.

It did work for a few clicks without the key, but hasn't since, with or without.  Is the because it's too slow fetching it so Android gives up and loads the info window without it?  Is there a best in class way to do this?

Would another image loading library work better?  Google's volley?

Also with

LinearLayout.LayoutParams

I'd like the image to stretch across the width of the info windows, i.e. match_parent, and to scale vertically to maintain original aspect ratio, how do I do this?

This is my answer

In commonsWare new class I add this flag:

```<code>@Override
public void onSuccess() {
    Log.i(TAG, "image got, should rebuild window");
    if (marker != null && marker.isInfoWindowShown()) {
        Log.i(TAG, "conditions met, redrawing window");
        marker.setTag(new Boolean("True"));
        marker.showInfoWindow();
    }
}
</code>```

And in prepareInfoView, I test for the flags absence.

```<code>    if (marker.getTag() == null ) {
        Log.i("prepareInfoView", "fetching image");
        Picasso.with(this).load(imageURL).fetch(new MarkerCallback(marker));
    }
    else {
        Log.wtf("prepareInfoView", "building info window");
</code>```

Party on! :)

答:
I struggled with this as well, here is a solution with glide inspired from the accepted answer.
This solution did not work for me without resizing the picture to a proper size. With override() (and centerCrop) it did the trick.

Keep track of the latest picture shown

```<code>private String previousImageUrl = null;
</code>```

And use it to see if you need refreshing of the current image

```<code>googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_map_info_window, null);
        MyObject myObject = (MyObject) marker.getTag();
        final String url = myObject.getImageUrl();
        final ImageView imageView = (ImageView) view.findViewById(R.id.image_view);
        GlideApp.with(getContext()).load(url)
                .override(imageWidth, imageHeight) // made the difference
                .centerCrop()
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (!TextUtils.equals(url, previousImageUrl)) {
                            previousImageUrl = url;
                            marker.showInfoWindow();
                        }
                    }
                });
        return view;
    }
});
</code>```

Body:
I'm trying to layout a custom infoWindow programmatically.  I want to load a streetView preview image using Picasso but the image isn't showing up, any idea why?

private View prepareInfoView(Marker marker){
    //prepare InfoView programmatically
    LinearLayout infoView = new LinearLayout(EarthquakeActivity.this);
    LinearLayout.LayoutParams infoViewParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    infoView.setOrientation(LinearLayout.VERTICAL);
    // attach the above layout to the infoView
    infoView.setLayoutParams(infoViewParams);

    //create street view preview @ top
    ImageView streetViewPreviewIV = new ImageView(EarthquakeActivity.this);
    // this scales the image to match parents WIDTH?, but retain image's height??
    LinearLayout.LayoutParams streetViewImageViewParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    streetViewPreviewIV.setLayoutParams(streetViewImageViewParams);

    String imageURL = "https://maps.googleapis.com/maps/api/streetview?size=200x200&location=";
    String markerLongitude = Double.toString(marker.getPosition().longitude);
    String markerLatitude = Double.toString(marker.getPosition().latitude);
    imageURL += markerLatitude + "," + markerLongitude + "&fov=120&heading=0&pitch=0";
    Log.wtf("prepareInfoView", imageURL);

    Picasso.with(this).load(imageURL).into(streetViewPreviewIV);
    infoView.addView(streetViewPreviewIV);

I've tried with and without the api key appending the url.

It did work for a few clicks without the key, but hasn't since, with or without.  Is the because it's too slow fetching it so Android gives up and loads the info window without it?  Is there a best in class way to do this?

Would another image loading library work better?  Google's volley?

Also with

LinearLayout.LayoutParams

I'd like the image to stretch across the width of the info windows, i.e. match_parent, and to scale vertically to maintain original aspect ratio, how do I do this?

This is my answer

In commonsWare new class I add this flag:

@Override
public void onSuccess() {
    Log.i(TAG, "image got, should rebuild window");
    if (marker != null && marker.isInfoWindowShown()) {
        Log.i(TAG, "conditions met, redrawing window");
        marker.setTag(new Boolean("True"));
        marker.showInfoWindow();
    }
}

And in prepareInfoView, I test for the flags absence.

    if (marker.getTag() == null ) {
        Log.i("prepareInfoView", "fetching image");
        Picasso.with(this).load(imageURL).fetch(new MarkerCallback(marker));
    }
    else {
        Log.wtf("prepareInfoView", "building info window");

Party on! :)

Body:
I struggled with this as well, here is a solution with glide inspired from the accepted answer.
This solution did not work for me without resizing the picture to a proper size. With override() (and centerCrop) it did the trick.

Keep track of the latest picture shown

private String previousImageUrl = null;

And use it to see if you need refreshing of the current image

googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_map_info_window, null);
        MyObject myObject = (MyObject) marker.getTag();
        final String url = myObject.getImageUrl();
        final ImageView imageView = (ImageView) view.findViewById(R.id.image_view);
        GlideApp.with(getContext()).load(url)
                .override(imageWidth, imageHeight) // made the difference
                .centerCrop()
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                        if (!TextUtils.equals(url, previousImageUrl)) {
                            previousImageUrl = url;
                            marker.showInfoWindow();
                        }
                    }
                });
        return view;
    }
});


问:
Position fixed content overlapping problem
This is my html5 markup

```<code><div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>
</code>```

Now used css

```<code>header {
  height: 95px;
  position: fixed;
  width: 100%;
  min-width: 980px;
}

footer {
  background: #000000;
  bottom: 0;
  height: 30px;
  position: fixed;
  width: 100%;
  min-width: 980px
}
</code>```

Now my problem is when i put any content inside

```<code><div id="content">
</div>
</code>```

The content comes from top:0 which is not required. I dont want to use padding or margin top over content. Is there any way from which content comes below header.

答:
So for what I get from this question, you are trying not to overlap stuff, you could use z-index inside your div's css:

```<code>.example {
  position: absolute;
  z-index: -10;
}
</code>```

*z-index only works on positioned elements (position:absolute, position:relative, or position:fixed)*

Body:
This is my html5 markup

Now used css

header {
  height: 95px;
  position: fixed;
  width: 100%;
  min-width: 980px;
}

footer {
  background: #000000;
  bottom: 0;
  height: 30px;
  position: fixed;
  width: 100%;
  min-width: 980px
}

Now my problem is when i put any content inside

The content comes from top:0 which is not required. I dont want to use padding or margin top over content. Is there any way from which content comes below header.

Body:
So for what I get from this question, you are trying not to overlap stuff, you could use z-index inside your div's css:

.example {
  position: absolute;
  z-index: -10;
}

*z-index only works on positioned elements (position:absolute, position:relative, or position:fixed)*


问:
MacOS - automake: command not found
I am trying to install automake on MacOS using brew. From terminal I write, brew install automake says Warning: automake-1.15 already installed.
When I then try automake version it responds -bash: automake: command not found. I am using OS X El Capitan.

```<code>$ automake version
-bash: automake: command not found
$ brew install automake
Warning: automake-1.15 already installed
$ automake version
-bash: automake: command not found
</code>```

答:
What an infuriating problem! In a Docker situation,

It is so hard to get autoconf 1.15 working that we had to get the aid of a Grand Ultra Master Expert to investigate the issue and get it working on Mac.  It then worked beautifully.

Later I happened to upgrade a Mac to High Sierra, it stopped working! Even though autoconf 1.15 working fine.

How to fix:

Short answer, I simply trashed the local repo, for goodness sake, and checked out the repo again.

It then worked fine!

It has something to do with the aclocal.m4 and similar files.  I endlessly massaged them but nothing.  Someone suggsted just scratching the repo and getting it again: everything then worked!

Title: MacOS - automake: command not found

Body:
I am trying to install automake on MacOS using brew. From terminal I write, brew install automake says Warning: automake-1.15 already installed.
When I then try automake version it responds -bash: automake: command not found. I am using OS X El Capitan.

$ automake version
-bash: automake: command not found
$ brew install automake
Warning: automake-1.15 already installed
$ automake version
-bash: automake: command not found


问:
In moment.js, is it possible to have a date-time string and keep the date but change the time?
I'm using moment.js and want to update a date-time string with a new user-entered time. The date has not changed, only the time. There is no timezone change, just that the hour and minute values have possibly been altered.

How would I take a string like this and convert it such that the time is different?

This is would I'd expect:

```<code>const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
    moment(dateTimeString)
    .changeTime('05:20 PM')
    .format()
)
// newDateTimeString === '2017-11-14T17:20:00.0086709-06:00'
</code>```

答:
There is no built in function like changeTime, you can write your own using set.

You can add changeTime using moment.fn

The Moment prototype is exposed through moment.fn. If you want to add your own functions, that is where you would put them.

You can create a temp moment object with your "time to add" value using moment(String, String), then use set(Object(String, Int)) and getters like hours() and minutes().

Here a live sample:

moment.fn.changeTime = function(timeString) {
  let m1 = moment(timeString, 'hh:mm A');
  return this.set({h: m1.hours(), m: m1.minutes()});
}

const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
    moment(dateTimeString)
    .changeTime('05:20 PM')
    .format()
)

console.log(newDateTimeString);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script></code>```

Body:
I'm using moment.js and want to update a date-time string with a new user-entered time. The date has not changed, only the time. There is no timezone change, just that the hour and minute values have possibly been altered.

How would I take a string like this and convert it such that the time is different?

This is would I'd expect:

const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
    moment(dateTimeString)
    .changeTime('05:20 PM')
    .format()
)
// newDateTimeString === '2017-11-14T17:20:00.0086709-06:00'

Body:
There is no built in function like changeTime, you can write your own using set.

You can add changeTime using moment.fn

The Moment prototype is exposed through moment.fn. If you want to add your own functions, that is where you would put them.

You can create a temp moment object with your "time to add" value using moment(String, String), then use set(Object(String, Int)) and getters like hours() and minutes().

Here a live sample:

moment.fn.changeTime = function(timeString) {
  let m1 = moment(timeString, 'hh:mm A');
  return this.set({h: m1.hours(), m: m1.minutes()});
}

const dateTimeString = '2017-11-14T16:04:54.0086709-06:00'
const newDateTimeString = (
    moment(dateTimeString)
    .changeTime('05:20 PM')
    .format()
)

console.log(newDateTimeString);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>


问:
laravel 5.4 can i use custom method inside a where clause
I'm trying to call a method inside a custom model function during query building but getting error.This way is it possible.Actually i'm trying to break the query in two function because filterData may be long.

In model, i wrote like this

```<code>public function get_filter_sql2($query, $filterData){

        if( count($filterData) > 0 ){

            foreach($filterData as $key=>$value){

                if( $value!=''){

                    if( $key == 'title' ){
                        $query->where('b.title', 'LIKE', '%'.$value.'%');
                    }
                    if( $key == 'bannercatID' ){
                        $query->where('b.bannercatID', '=', $value);
                    }
                    if( $key == 'status' ){
                        $query->where('b.status', '=', $value);
                    }

                }
            }
        }
        return $query;
    }

function scopeGet_all_records2($query,$filterData, $per_page){
        //DB::enableQueryLog();
        $result = DB::table('banner as b')
                ->leftJoin('banner_category as bc', 'bc.bannercatID', '=', 'b.bannercatID')
                ->select('*')
                ->where( function ($query) use ($filterData){
                    $this->get_filter_sql2($query, $filterData);
                 })
                ->orderBy('b.bannercatID', 'ASC')
                ->paginate($per_page)
                ;
        //$result = DB::getQueryLog();
        //print_r($result);
        if( count($result) > 0 ){
            $result = $result;
        }
        else{
            $result = false;
        }
        return $result;

    }
</code>```

答:
You should use more relations instead of raw DB queries. But thats up to you. In the end code would be more elegant with Eloquent.

I think your issue is that you are using $this instead of $query in the where anonymous function.

```<code>->where( function ($query) use ($filterData){
    $query->get_filter_sql2($query, $filterData);
})
</code>```

Body:
I'm trying to call a method inside a custom model function during query building but getting error.This way is it possible.Actually i'm trying to break the query in two function because filterData may be long.

In model, i wrote like this

public function get_filter_sql2($query, $filterData){

        if( count($filterData) > 0 ){

            foreach($filterData as $key=>$value){

                if( $value!=''){

                    if( $key == 'title' ){
                        $query->where('b.title', 'LIKE', '%'.$value.'%');
                    }
                    if( $key == 'bannercatID' ){
                        $query->where('b.bannercatID', '=', $value);
                    }
                    if( $key == 'status' ){
                        $query->where('b.status', '=', $value);
                    }

                }
            }
        }
        return $query;
    }

function scopeGet_all_records2($query,$filterData, $per_page){
        //DB::enableQueryLog();
        $result = DB::table('banner as b')
                ->leftJoin('banner_category as bc', 'bc.bannercatID', '=', 'b.bannercatID')
                ->select('*')
                ->where( function ($query) use ($filterData){
                    $this->get_filter_sql2($query, $filterData);
                 })
                ->orderBy('b.bannercatID', 'ASC')
                ->paginate($per_page)
                ;
        //$result = DB::getQueryLog();
        //print_r($result);
        if( count($result) > 0 ){
            $result = $result;
        }
        else{
            $result = false;
        }
        return $result;

    }

Body:
You should use more relations instead of raw DB queries. But thats up to you. In the end code would be more elegant with Eloquent.

I think your issue is that you are using $this instead of $query in the where anonymous function.

->where( function ($query) use ($filterData){
    $query->get_filter_sql2($query, $filterData);
})


问:
Android Service Stops When App Is Closed
I am starting a service from my main Android activity as follows:

```<code>final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);
</code>```

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?

答: Running an intent service will be easier. Service in creating a thread in the application but it's still in the application. </p>

Body:
I am starting a service from my main Android activity as follows:

final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?


问:
Changing the Status Bar Color for specific ViewControllers using Swift in iOS8
```<code>override func preferredStatusBarStyle() -> UIStatusBarStyle {
 return UIStatusBarStyle.LightContent;
}
</code>```

Using the above code in any ViewController to set the statusBar color to White for a specific viewcontroller doesnt work in iOS8 for me. Any suggestions?  Using the UIApplication.sharedApplication method, the color changes after required changes in the Info.plist for the whole app.

```<code>// Change the colour of status bar from black to white
UIApplication.sharedApplication().statusBarStyle = .LightContent
</code>```

How can I just make changes to the status bar color for some required and specific ViewControllers?

答: What worked with me, in the Storyboard, go to the Navigation Controller, select the navigation bar, click on the Attributes Inspector, then change the style from default to black. That's it!</p>

Body:
override func preferredStatusBarStyle() -> UIStatusBarStyle {
 return UIStatusBarStyle.LightContent;
}

Using the above code in any ViewController to set the statusBar color to White for a specific viewcontroller doesnt work in iOS8 for me. Any suggestions?  Using the UIApplication.sharedApplication method, the color changes after required changes in the Info.plist for the whole app.

// Change the colour of status bar from black to white
UIApplication.sharedApplication().statusBarStyle = .LightContent

How can I just make changes to the status bar color for some required and specific ViewControllers?


问:
hlookup - approximate match and structured reference tables
I have values in my Excel spreadsheet that look like this

```<code>      100    200    300
10     A      B      C
20     D      E      F
30     G      H      I
</code>```

This gives me the correct answer:

```<code>=hlookup(120,B1:D4,2,TRUE)
</code>```

But if I 'format as table', the same formula gives me #N/A.

I'd like to have it formatted as a table but I don't know how to get it to work.

答:
With 120 (as a true number) in F1,

```<code>=HLOOKUP(TEXT(F1, "0;@"), Table2[[#All],[100]:[300]], 2, TRUE)
'... or,
=HLOOKUP(TEXT(F1, "0;@"), B:D, 2, TRUE)
</code>```

Hardcoding 120 into the formula,

```<code>=HLOOKUP("120", Table2[[#All],[100]:[300]], 2, TRUE)
'... or,
=HLOOKUP("120", B:D, 2, TRUE)
</code>```

Body:
I have values in my Excel spreadsheet that look like this

      100    200    300
10     A      B      C
20     D      E      F
30     G      H      I

This gives me the correct answer:

=hlookup(120,B1:D4,2,TRUE)

But if I 'format as table', the same formula gives me #N/A.

I'd like to have it formatted as a table but I don't know how to get it to work.

Body:
With 120 (as a true number) in F1,

=HLOOKUP(TEXT(F1, "0;@"), Table2[[#All],[100]:[300]], 2, TRUE)
'... or,
=HLOOKUP(TEXT(F1, "0;@"), B:D, 2, TRUE)

Hardcoding 120 into the formula,

=HLOOKUP("120", Table2[[#All],[100]:[300]], 2, TRUE)
'... or,
=HLOOKUP("120", B:D, 2, TRUE)


问:
C how to show all unused functions (including ones defined in h files)
Somewhat related to this, but it still doesn't quite answer my question

I have a C project, and i would like to enumerate all unreferenced functions (including non-static, so setting compiler option for werror=unused-function only partially works...) in order to identify and clean up the codebase.

One way I thought is to enumerate all the functions in the project, and then make a script to go through each and see if it is called via cscope... but I'm not sure how to get a list-form of all the functions in the first place. That link above has a solution that is failing for me.

Any other ideas are welcome.

答:
I do this in ncurses, to see which library symbols are used by a (custom) script list-used.sh which makes a list of the symbols exported from its libraries and which of those are used (or not) from programs linked against the libraries.

The output of the script is a report which makes up most of the test/README file.

In other answers, there were tools suggested which would be either (a) unavailable or (b) require extensive rework of the build structure (to put a few hundred files into a single command-line as required by those tools).


问:
SSRS show value only on last page in body of report
I'm attempting to show a sum in a table footer on a report.  It will be in the body of the report and can't be in the header or footer.  The table footer repeats on each page but should show the sum only on the last page.  It will show another piece of text on all other pages.  Is this possible?

Additional pieces of information:
The detail part of the table isn't a consistent height, but the page is a consistent height.  I can't assume a standard number of detail items per page.

Just to be clear.  I was talking about adding it to table footer and not the page footer.  It should still be in the page body.

答: Just add a textbox below the table. The textbox will be visible after the last page of the table.</p>


问:
JavaScript: force 0 to be a Number so it can increment properly
for some weird reason, it doesn't work worth a tinker's damn.  it appends when i need it to increment.  yes, i've read this, and this aaaand this (which doesn't work), but they don't really help (at all) with such a simple case.  :poop:  what i am trying to do, is this:

```<code>  var status = 0;
  console.log('status: '+status);
  status += 1;
  console.log('status: '+status);
  status += 2;
  console.log('status: '+status);
  status += 3;
  console.log('status: '+status);
  ...
</code>```

but all it outputs is 0,01,012,0123 instead of 0,1,3,6.  yes, it's simple, but that's what i need for this particular implementation and the stuff that connects to it. also, the steps matter; otherwise, i'd just status++ and i obviously don't want twenty-six lines of that either. DRY, right?

i've tried to do this, var status = Number(0); and var status = parseInt(0) for fun (no way it would work, but try anyway) and even tried status = status + 1' (pointless variant, but cover the bases...) and none work.  what am i missing?  i understand this, yet don't know how to make 0 == Number(0), as it were.  i thought the increment existed to prevent kind of fumbuckery... its stupid math, for heaven's sake...

so.  how do i force the zero to be a Number so the increment can work as needed and output anumber at each step along the way?

答: would be doing status = +status + 1 be to much? Or the hack +status++?

Body:
for some weird reason, it doesn't work worth a tinker's damn.  it appends when i need it to increment.  yes, i've read this, and this aaaand this (which doesn't work), but they don't really help (at all) with such a simple case.  :poop:  what i am trying to do, is this:

  var status = 0;
  console.log('status: '+status);
  status += 1;
  console.log('status: '+status);
  status += 2;
  console.log('status: '+status);
  status += 3;
  console.log('status: '+status);
  ...

but all it outputs is 0,01,012,0123 instead of 0,1,3,6.  yes, it's simple, but that's what i need for this particular implementation and the stuff that connects to it. also, the steps matter; otherwise, i'd just status++ and i obviously don't want twenty-six lines of that either. DRY, right?

i've tried to do this, var status = Number(0); and var status = parseInt(0) for fun (no way it would work, but try anyway) and even tried status = status + 1' (pointless variant, but cover the bases...) and none work.  what am i missing?  i understand this, yet don't know how to make 0 == Number(0), as it were.  i thought the increment existed to prevent kind of fumbuckery... its stupid math, for heaven's sake...

so.  how do i force the zero to be a Number so the increment can work as needed and output anumber at each step along the way?