问:
Why does my custom checkbox not correctly propagate change value if I set the type after view init?
I am writing some wrappers for normal form controls in my angular app by writing components / directives that have selectors like 'input[custom-input]'. By doing that I am able to setup public methods that can later be used when doing content projection.

My Html then looks like

```<code><a-component-that-handles-animating-placeholder-etc>
    <input custom-checkbox formControlName="field"/>
</<a-component-that-handles-animating-placeholder-etc>
</code>```

The advantage here is that the input is available directly to any component that might want to use it, whereas if I wrote a wrapper I would have to implement a pipeline for every functionality such as disabled e.g

```<code><custom-input [disabled]="isDisabled"]></custom-input>
</code>```

Another advantage is that I do not have to implement new custom control value accessors to bind formcontrolName on and make the framework happy, when in reality the implementation of custom-input would be to just internally use input, which for every control adds a lot of complexity to the project.

The problem is that the reactive form control is not being updated with the correct value when the checkbox is checked and unchecked. In my custom component with this selector input[custom-checkbox] I am doing this logic:

```<code>  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'checkbox');
  }
</code>```

Thats because I dont want consumers to have to specify that this element is a checkbox twice like so:

```<code><input type="checkbox" custom-checkbox/>
</code>```

But for some reason setting the type after the render is breaking the event that updated the form control. I have no idea why.

EDIT: I forked one of the stackblitz and replicated my problem.
https://stackblitz.com/edit/angular-dzqp4k

答:
Following your blitz (& mine), I remembered that inputs are already managed by angular forms. You can control them through NgControl.

Here is the result

```<code>export class InputSelectorDirective {

  @HostBinding('attr.type') inputType: string = "checkbox";

  ngControl: NgControl;

  constructor(
    private R: Renderer2,
    private elRef: ElementRef<HTMLInputElement>,
    private injector: Injector
  ) {
    this.ngControl = injector.get(NgControl);

  }

  ngOnInit() {
    // this.inputType = "checkbox";
    this.ngControl.control.valueChanges
      .subscribe(value => this.ngControl.control.setValue(this.elRef.nativeElement.checked, { emitEvent: false }));
  }
}
</code>```

Body:
I am writing some wrappers for normal form controls in my angular app by writing components / directives that have selectors like 'input[custom-input]'. By doing that I am able to setup public methods that can later be used when doing content projection.

My Html then looks like

    <input custom-checkbox formControlName="field"/>
</

The advantage here is that the input is available directly to any component that might want to use it, whereas if I wrote a wrapper I would have to implement a pipeline for every functionality such as disabled e.g

<custom-input [disabled]="isDisabled"]></custom-input>

Another advantage is that I do not have to implement new custom control value accessors to bind formcontrolName on and make the framework happy, when in reality the implementation of custom-input would be to just internally use input, which for every control adds a lot of complexity to the project.

The problem is that the reactive form control is not being updated with the correct value when the checkbox is checked and unchecked. In my custom component with this selector input[custom-checkbox] I am doing this logic:

  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'checkbox');
  }

Thats because I dont want consumers to have to specify that this element is a checkbox twice like so:

<input type="checkbox" custom-checkbox/>

But for some reason setting the type after the render is breaking the event that updated the form control. I have no idea why.

EDIT: I forked one of the stackblitz and replicated my problem.
https://stackblitz.com/edit/angular-dzqp4k

Body:
Following your blitz (& mine), I remembered that inputs are already managed by angular forms. You can control them through NgControl.

Here is the result

export class InputSelectorDirective {

  @HostBinding('attr.type') inputType: string = "checkbox";

  ngControl: NgControl;

  constructor(
    private R: Renderer2,
    private elRef: ElementRef<HTMLInputElement>,
    private injector: Injector
  ) {
    this.ngControl = injector.get(NgControl);

  }

  ngOnInit() {
    // this.inputType = "checkbox";
    this.ngControl.control.valueChanges
      .subscribe(value => this.ngControl.control.setValue(this.elRef.nativeElement.checked, { emitEvent: false }));
  }
}


来源: stackexchange

问:
Why are my PostgreSQL "real" data being rounded?
I have a table with a column named total having the real data type.

But I'm finding that this column is being rounded when I query its value, as illustrated in the following:

```<code>SELECT total FROM data WHERE id='xe54g';
 total
---------
  105861

UPDATE data SET total=105860.5 WHERE id='xe54g';
UPDATE 1

SELECT total FROM data WHERE id='xe54g';
 total
---------
  105860

UPDATE data SET total=105860.7 WHERE id='xe54g';
UPDATE 1

SELECT total FROM data WHERE id='xe54g';
 total
---------
  105861

\d+ data
   Column  |  Type | Collation | Nullable |  Default  | Storage  | Stats target | Description
-----------+-------+-----------+----------+-----------+----------+--------------+-------------
 total     | real  |           |          | 0         | plain    |              |
</code>```

How do I get it to return the full precision?  I'm using PG 11.1.

答:
You can get the full precision by setting

```<code>extra_float_digits = 3
</code>```

Then PostgreSQL will also display decimal digits that may contain rounding errors.

Note that real has a low number of significant digits. You'd be happier if you used double precision.

ContentLicense: CC BY-SA 4.0

Body:
I have a table with a column named total having the real data type.

But I'm finding that this column is being rounded when I query its value, as illustrated in the following:

SELECT total FROM data WHERE id='xe54g';
 total
---------
  105861

UPDATE data SET total=105860.5 WHERE id='xe54g';
UPDATE 1

SELECT total FROM data WHERE id='xe54g';
 total
---------
  105860

UPDATE data SET total=105860.7 WHERE id='xe54g';
UPDATE 1

SELECT total FROM data WHERE id='xe54g';
 total
---------
  105861

\d+ data
   Column  |  Type | Collation | Nullable |  Default  | Storage  | Stats target | Description
-----------+-------+-----------+----------+-----------+----------+--------------+-------------
 total     | real  |           |          | 0         | plain    |              |

How do I get it to return the full precision?  I'm using PG 11.1.

Body:
You can get the full precision by setting

extra_float_digits = 3

Then PostgreSQL will also display decimal digits that may contain rounding errors.

Note that real has a low number of significant digits. You'd be happier if you used double precision.


问:
Select from a 3-dimensional array with a 2-dimensional array
I have two arrays:

a: a 3-dimensional source array (N x M x 2)

b: a 2-dimensional index array (N x M) containing 0 and 1s.

I want to use the indices in b to select the corresponding elements of a in its third dimension. The resulting array should have the dimensions N x M. Here is the example as code:

```<code>import numpy as np

a = np.array( # dims: 3x3x2
    [[[ 0,  1],
     [ 2,  3],
     [ 4,  5]],
    [[ 6,  7],
     [ 8,  9],
     [10, 11]],
    [[12, 13],
     [14, 15],
     [16, 17]]]
)
b = np.array( # dims: 3x3
    [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
)

# select the elements in a according to b
# to achieve this result:
desired = np.array(
  [[ 1,  3,  5],
   [ 7,  9, 11],
   [13, 15, 17]]
)
</code>```

At first, I thought this must have a simple solution but I could not find one at all. Since I would like to port it to tensorflow, I would appreciate if somebody knows a numpy-type solution for this.

Edit: The third dimension of a might contain more than two elements. Hence, b might also contain indices different from 0 and 1 - it is not a boolean mask.

Body:
I have two arrays:

a: a 3-dimensional source array (N x M x 2)

b: a 2-dimensional index array (N x M) containing 0 and 1s.

I want to use the indices in b to select the corresponding elements of a in its third dimension. The resulting array should have the dimensions N x M. Here is the example as code:

import numpy as np

a = np.array( # dims: 3x3x2
    [[[ 0,  1],
     [ 2,  3],
     [ 4,  5]],
    [[ 6,  7],
     [ 8,  9],
     [10, 11]],
    [[12, 13],
     [14, 15],
     [16, 17]]]
)
b = np.array( # dims: 3x3
    [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
)

# select the elements in a according to b
# to achieve this result:
desired = np.array(
  [[ 1,  3,  5],
   [ 7,  9, 11],
   [13, 15, 17]]
)

At first, I thought this must have a simple solution but I could not find one at all. Since I would like to port it to tensorflow, I would appreciate if somebody knows a numpy-type solution for this.

Edit: The third dimension of a might contain more than two elements. Hence, b might also contain indices different from 0 and 1 - it is not a boolean mask.

Body:
You can use np.take_along_axis:

import numpy as np

a = np.array(
    [[[ 0,  1],
      [ 2,  3],
      [ 4,  5]],
     [[ 6,  7],
      [ 8,  9],
      [10, 11]],
     [[12, 13],
      [14, 15],
      [16, 17]]])
b = np.array(
    [[1, 1, 1],
     [1, 1, 1],
     [1, 1, 1]])
print(np.take_along_axis(a, b[..., np.newaxis], axis=-1)[..., 0])
# [[ 1  3  5]
#  [ 7  9 11]
#  [13 15 17]]


问:
CMake with Boost could not find static libraries
I have some troubles with CMake and Boost library. I have the following error :

```<code>CMake Error at C:/Program Files (x86)/CMake
2.8/share/cmake-2.8/Modules/FindBoost.cmake:1111 (message):   Unable to find the requested Boost libraries.

  Boost version: 1.55.0

  Boost include path: C:/local/boost_1_55_0

  Could not find the following static Boost libraries:

          boost_system
          boost_date_time
          boost_regex

  No Boost libraries were found.  You may need to set BOOST_LIBRARYDIR
to the   directory containing Boost libraries or BOOST_ROOT to the
location of   Boost. Call Stack (most recent call first):
CMakeLists.txt:10 (find_package)

-- Configuring incomplete, errors occurred!
</code>```

I did everything I found to internet in my CMakeLists.txt but it's not working, I don't understand.
I'm using Windows 8 with Visual Studio 12 and Boost is installed in the default directory. (C:/local/boost_1_55_0)

Here my CMakeLists.txt :

```<code>cmake_minimum_required(VERSION 2.6)

project (server)

set(BOOST_ROOT "c:\\local\\boost_1_55_0")

set (Boost_USE_STATIC_LIBS ON) set (Boost_MULTITHREADED ON) set
(Boost_USE_STATIC_RUNTIME OFF)

find_package(Boost 1.55 COMPONENTS system date_time regex REQUIRED)
add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})

set(SRCS main.cpp Server.cpp Client.cpp)

set(HEADERS Server.h Client.h)

include_directories(${Boost_INCLUDE_DIR})

add_executable(babel_server ${SRCS} ${HEADERS})

target_link_libraries(babel_server ${Boost_LIBRARIES})
</code>```

Anyone can help me please ?

Thanks

答:
Make sure you've selected the right platform for the generator.

For example if your Boost is 64-bit and CMake's generator is set to Win32 (default on Windows), it will not be able to find the libraries. This is set whenever you first try to configure the project and you can reset it by deleting the cache.

ContentLicense: CC BY-SA 3.0

Body:
I have some troubles with CMake and Boost library. I have the following error :

CMake Error at C:/Program Files (x86)/CMake
2.8/share/cmake-2.8/Modules/FindBoost.cmake:1111 (message):   Unable to find the requested Boost libraries.

  Boost version: 1.55.0

  Boost include path: C:/local/boost_1_55_0

  Could not find the following static Boost libraries:

          boost_system
          boost_date_time
          boost_regex

  No Boost libraries were found.  You may need to set BOOST_LIBRARYDIR
to the   directory containing Boost libraries or BOOST_ROOT to the
location of   Boost. Call Stack (most recent call first):
CMakeLists.txt:10 (find_package)

-- Configuring incomplete, errors occurred!

I did everything I found to internet in my CMakeLists.txt but it's not working, I don't understand.
I'm using Windows 8 with Visual Studio 12 and Boost is installed in the default directory. (C:/local/boost_1_55_0)

Here my CMakeLists.txt :

cmake_minimum_required(VERSION 2.6)

project (server)

set(BOOST_ROOT "c:\\local\\boost_1_55_0")

set (Boost_USE_STATIC_LIBS ON) set (Boost_MULTITHREADED ON) set
(Boost_USE_STATIC_RUNTIME OFF)

find_package(Boost 1.55 COMPONENTS system date_time regex REQUIRED)
add_definitions(${Boost_LIB_DIAGNOSTIC_DEFINITIONS})

set(SRCS main.cpp Server.cpp Client.cpp)

set(HEADERS Server.h Client.h)

include_directories(${Boost_INCLUDE_DIR})

add_executable(babel_server ${SRCS} ${HEADERS})

target_link_libraries(babel_server ${Boost_LIBRARIES})

Anyone can help me please ?

Thanks


问:
Putting values of a dictionary in a graph
I want make a graph of a part of the values of a dictionary.

I already stored the necessary values in a variable, but I just don't understand how to put them in a simple graph with just the numbers 1 to 500 on the x-axis and my values on the y-axis.

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

# Plot frequencies of the most 500 words
frequencies = freqs_sorted[len(freqs_sorted)-500:len(freqs_sorted)]
</code>```

Everything I tried so far resulted in an empty graph. Thanks in advance!

答:
From the matplotlib tutorial:

```<code>fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.plot(range(1, 501), frequencies)
plt.show()
</code>```

P.S. In matplotlib you often have several ways to draw whatever you want. It is just one of them. Here is shorter version from @gboffi:

```<code>plt.plot(frequencies)
plt.show()
</code>```

Body:
I want make a graph of a part of the values of a dictionary.

I already stored the necessary values in a variable, but I just don't understand how to put them in a simple graph with just the numbers 1 to 500 on the x-axis and my values on the y-axis.

%matplotlib inline
import matplotlib.pyplot as plt

# Plot frequencies of the most 500 words
frequencies = freqs_sorted[len(freqs_sorted)-500:len(freqs_sorted)]

Everything I tried so far resulted in an empty graph. Thanks in advance!

Body:
From the matplotlib tutorial:

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
plt.plot(range(1, 501), frequencies)
plt.show()

P.S. In matplotlib you often have several ways to draw whatever you want. It is just one of them. Here is shorter version from @gboffi:

plt.plot(frequencies)
plt.show()


问:
How to make UIPopoverController keep same position after rotating?
I can't keep popover the same position on the screen after rotation. Is there any good way to do that, because just setting some frame to popover works terrible after rotating.popover.frame = CGRectMake(someFrame); After rotation popover looks fine only if it is in the center of the screen.

答:
Initialize PopOver Controller

```<code>var popoverContent: PopoverContentViewController?
</code>```

Write Defination for PopOver Controller

```<code>popoverContent = self.storyboard?.instantiateViewController(withIdentifier: "PopoverContentViewController") as? PopoverContentViewController
popoverContent?.modalPresentationStyle = .popover
let popover = popoverContent?.popoverPresentationController!
popover?.delegate = self
popoverContent?.preQuestionInfoPopUpViewDelegateObject = self
popover?.permittedArrowDirections = UIPopoverArrowDirection()
popover?.sourceView = self.view
popover?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 330, height: 330)
</code>```

Present PopOver Controller

self.present(popoverContent, animated: true, completion:nil)

Write below method and assign new size to popover:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        let popover = popoverContent?.popoverPresentationController!
        popover?.sourceRect = CGRect(x: size.width/2, y: size.height/2, width: 0, height: 0)
}

Body:
Initialize PopOver Controller

var popoverContent: PopoverContentViewController?

Write Defination for PopOver Controller

popoverContent = self.storyboard?.instantiateViewController(withIdentifier: "PopoverContentViewController") as? PopoverContentViewController
popoverContent?.modalPresentationStyle = .popover
let popover = popoverContent?.popoverPresentationController!
popover?.delegate = self
popoverContent?.preQuestionInfoPopUpViewDelegateObject = self
popover?.permittedArrowDirections = UIPopoverArrowDirection()
popover?.sourceView = self.view
popover?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 330, height: 330)

Present PopOver Controller

self.present(popoverContent, animated: true, completion:nil)

Write below method and assign new size to popover:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        let popover = popoverContent?.popoverPresentationController!
        popover?.sourceRect = CGRect(x: size.width/2, y: size.height/2, width: 0, height: 0)
}


问:
"Print" value in checkbox from database
I´m trying to make the checkbox "check" if at the database is a value.
So, if someone checks the first checkbox I want it to be checked the next time someone tries to edit it.

So I check the first like on the print and it puts on the database the value 0.

If I open the website again I want it to be checked.
I think this is an if, but I don´t know how can I check the box.

```<code><tr>
  <th width="15%"> Atividade extra escola </th>
  <td>
    <label class="checkbox-inline" for="checkboxes-30">
      <input type="checkbox" name="checkboxes30" id="checkboxes-30" value="Não">
      Não
    </label>
    <label class="checkbox-inline" for="checkboxes-40">
      <input type="checkbox" name="checkboxes40" id="checkboxes-40" value="Sim">
      Sim (qual?)
    </label>
    <input type="text" maxlength="9" class="input-field4" id="input" name="teste">
    </td>
</tr>
</code>```

答:
You need to get the variable from the DB and make a condition like a bellow.

let assume that the variable from the database is a boolean $flag :

```<code><?php echo $flag?'checked':''; ?>
</code>```

In the HTML :

```<code><input type="checkbox" name="checkboxes30" id="checkboxes-30" <?php echo $flag?'checked':''; ?> value="Não"/> Não
</code>```

Title: "Print" value in checkbox from database

Body:
I´m trying to make the checkbox "check" if at the database is a value.
So, if someone checks the first checkbox I want it to be checked the next time someone tries to edit it.

So I check the first like on the print and it puts on the database the value 0.

If I open the website again I want it to be checked.
I think this is an if, but I don´t know how can I check the box.

   Atividade extra escola

      <input type="checkbox" name="checkboxes30" id="checkboxes-30" value="Não">
      Não

      <input type="checkbox" name="checkboxes40" id="checkboxes-40" value="Sim">
      Sim (qual?)

    <input type="text" maxlength="9" class="input-field4" id="input" name="teste">

Body:
You need to get the variable from the DB and make a condition like a bellow.

let assume that the variable from the database is a boolean $flag :

<?php echo $flag?'checked':''; ?>

In the HTML :

<input type="checkbox" name="checkboxes30" id="checkboxes-30" <?php echo $flag?'checked':''; ?> value="Não"/> Não


问:
Could not find iPhone 6 simulator after upgrade to Xcode 10
I updated to Xcode 10 and since I did that, I can't run the simulator in terminal with the command react-native run-ios. I get this error:

Could not find iPhone 6 simulator

When I go to Xcode > Window > Devices and Simulator the simulator is there and when I do xcrun simctl list devices I also see the list of simulator.

I can run the app on my phone with react-native run-ios --device and from Xcode, and I tried with multiple apps so it's not the app.

When I go to Xcode > Preferences > Locations, Xcode 10.0 (10A255) is selected at Command Line Tools.

I tried restarting the computer, as well as deleting and re-installing Xcode.

Any ideas what it could be?

Here is my setup:

MacOs High Sierra 10.13.6

Xcode Version 10.0

react-native-cli: 2.0.1

react-native: 0.57.1

答:
Using react-native version 0.55.3 with XCode 10 I had to do two changes to get react-native run-ios running.

Inside node_modules/react-native/local-cli/runIOS/findMatchingSimulator.js:

The change as described by @martin-leroux :

Change

```<code>// Skipping non-available simulator
if (simulator.availability !== true) {
</code>```

to

```<code>// Skipping non-available simulator
if (
    simulator.availability !== '(available)' &&
    simulator.isAvailable !== 'YES'
) {`
</code>```

Change the line mentioned by @samernady :

Change

```<code>// Making sure the version of the simulator is an iOS or tvOS (Removes Apple Watch, etc)
if (!version.startsWith('iOS') && !version.startsWith('tvOS')) {
</code>```

to

```<code>// Making sure the version of the simulator is an iOS or tvOS (Removes Apple Watch, etc)
if (!version.includes('iOS') && !version.startsWith('tvOS')) {
</code>```

Body:
Using react-native version 0.55.3 with XCode 10 I had to do two changes to get react-native run-ios running.

Inside node_modules/react-native/local-cli/runIOS/findMatchingSimulator.js:

The change as described by @martin-leroux :

Change

// Skipping non-available simulator
if (simulator.availability !== true) {

to

// Skipping non-available simulator
if (
    simulator.availability !== '(available)' &&
    simulator.isAvailable !== 'YES'
) {`

Change the line mentioned by @samernady :

Change

// Making sure the version of the simulator is an iOS or tvOS (Removes Apple Watch, etc)
if (!version.startsWith('iOS') && !version.startsWith('tvOS')) {

to

// Making sure the version of the simulator is an iOS or tvOS (Removes Apple Watch, etc)
if (!version.includes('iOS') && !version.startsWith('tvOS')) {


问:
How do you limit the output of a foreach?
I need to create a website where one can bookmark properties and then only a couple of them get displayed on the homepage.
I already have the list of the bookmarked properties working using cookies, but im having problems with limiting the output when it comes to the display on the hoempage.</p>

```<code><h2>Previously seen properties</h2>
<?php
    if(isset($_COOKIE["bookmark"]))
    {//
        $total = 0;
        $cookie_data = stripslashes($_COOKIE['bookmark']);//removes backslashes
        $bookmark_data = json_decode($cookie_data, true);//converts JSON string to PHP variable
        foreach($bookmark_data as $keys => $values)
        {
    ?> <!---what will be displayed--->

        <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px;width:300px; height:300px;">
            <img src="../01_Global/assets/img/Houses/'. $row['Image'] .'" alt="" class="img-responsive" >
            <p align="center"><strong><a href="productpage.php"> <?php echo $values["property_name"]; ?></a></strong></p>
            <h4 style="text-align:center;" class="text-danger" > <?php echo $values["property_price"]; ?></h4>

        </div>
    <?php
    }
    ?>
    <?php
    }
    else
    {
    echo '';
    }
    ?>
</code>```

答:
You can use a counter and condition to break out a loop:

```<code><?php
$one_to_five = range(1, 5);
$break_out   = 3;
$counter     = 0;
foreach($one_to_five as $num) {
    $counter++;
    if($counter > $break_out)
        break;
    echo $num, "\n";
}
</code>```

Output:

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

Body:
I need to create a website where one can bookmark properties and then only a couple of them get displayed on the homepage.
I already have the list of the bookmarked properties working using cookies, but im having problems with limiting the output when it comes to the display on the hoempage.

Previously seen properties

<?php
    if(isset($_COOKIE["bookmark"]))
    {//
        $total = 0;
        $cookie_data = stripslashes($_COOKIE['bookmark']);//removes backslashes
        $bookmark_data = json_decode($cookie_data, true);//converts JSON string to PHP variable
        foreach($bookmark_data as $keys => $values)
        {
    ?>

 <?php echo $values["property_name"]; ?>

 <?php echo $values["property_price"]; ?>

    <?php
    }
    ?>
    <?php
    }
    else
    {
    echo '';
    }
    ?>

Body:
You can use a counter and condition to break out a loop:

<?php
$one_to_five = range(1, 5);
$break_out   = 3;
$counter     = 0;
foreach($one_to_five as $num) {
    $counter++;
    if($counter > $break_out)
        break;
    echo $num, "\n";
}

Output:

1
2
3


问:
Checking Sucsessfull Validation of Form
I have a C# ViewModel, specifying data annotations for automatic validation.
I render the View in Razor code.
I need to check in javascript, client side, if the ALL validations went through, or not.

I Have tried to catch the Submit event of the form. This worked, but is not fired after the validation completed. I recon I need to check for a state, or listen for some event that will fire when validation succeeded.

```<code>    $(document).ready(function () {
        alert("Before Fade");
        $("#LoaderSpinner").fadeOut('hidden');
    });

    $("#HelloForm").submit(function () {
        alert('SUBMITTED THE FORM');
        // Here i need to check if the form validated before activating the spinner
        $("#LoaderSpinner").fadeIn();
    });

</script>
</code>```

A nudge in the right direction would be appreciated.

答:
```<code>$("#HelloForm").on('submit', function (e) {
    e.preventDefault();

    if($("#HelloForm").valid()) {
        $(this).off('submit').submit();
    }
});
</code>```

Title: Checking Sucsessfull Validation of Form

Body:
I have a C# ViewModel, specifying data annotations for automatic validation.
I render the View in Razor code.
I need to check in javascript, client side, if the ALL validations went through, or not.

I Have tried to catch the Submit event of the form. This worked, but is not fired after the validation completed. I recon I need to check for a state, or listen for some event that will fire when validation succeeded.

    $(document).ready(function () {
        alert("Before Fade");
        $("#LoaderSpinner").fadeOut('hidden');
    });

    $("#HelloForm").submit(function () {
        alert('SUBMITTED THE FORM');
        // Here i need to check if the form validated before activating the spinner
        $("#LoaderSpinner").fadeIn();
    });

</script>

A nudge in the right direction would be appreciated.


问:
How to convert a collection to an array in javascript
I'm trying to figure out how to convert a javascript collection (i.e. something returned from getElementsByTagName/etc) to a normal array so I can perform array functions on the data.

I'm looking for a solution without using any libraries and haven't been able to find any sort of elegant solutions anywhere online. Has anyone written a good util function for this problem?

答:
You can use spread operator:

```<code>var coll = document.getElementsByTagName('div');

var arr = [...coll];
</code>```

Spread syntax

ContentLicense: CC BY-SA 2.5

Body:
You can use spread operator:

var coll = document.getElementsByTagName('div');

var arr = [...coll];

Spread syntax


问:
How to increment the CSS Selector id?
CSS Selector for the list view record.

Contacts_listView_row_1

How can I increment the row by defining a variable?
(#Contacts_listView_row_1)

答: You can try and move to a library like SASS or LESS that support the use of variables. A different approach would be to use a selector that matches on attribute values. That would look something like <code>[id^="Contacts_listView_row_"]</code>. Hope it helps </p>

Title: How to increment the CSS Selector id?

Body: You can try and move to a library like SASS or LESS that support the use of variables. A different approach would be to use a selector that matches on attribute values. That would look something like [id^="Contacts_listView_row_"]. Hope it helps


问:
Get Operation by Name in Google Speech to Text, with nodejs
I'm using Google Speech to Text Node.js client.
When starting long-running speech transcription, I need to split the operation in two steps.
1. Start the transcription, and return the "name".
2. Ask for the status of the operation.
Ie replicating https://cloud.google.com/speech-to-text/docs/async-recognize#speech-async-recognize-gcs-protocol in nodejs.

My problem is to figure out how to create an OperationsClient, and to make the getOperation({name}) to actually return the result of the transcription.

I do run this code inside two firebase cloud functions:
1. The one that starts the trancscription, and then return the "name". This one works really well with the SpeechClient.
2. Another one that should call operationsClient.getOperation aka the same as curl to "https://speech.googleapis.com/v1/operations/"

```<code>import gax, {GrpcClient, GrpcClientOptions, lro} from "google-gax";
const gaxOpts = {
    clientConfig: {}
}
const gaxGrpc = new GrpcClient(gaxOpts);

...

app.get('/operations/:googleSpeechRef', async (req, res) => {
    const googleSpeechRef = req.params.googleSpeechRef;

    const operationsClient = lro({
        auth: gaxGrpc.auth,
        grpc: gaxGrpc.grpc,
    }).operationsClient(gaxOpts);
try {
        const [responses] = await operationsClient.getOperation({name: googleSpeechRef},{});
        if (responses) {
            const operation = responses[0]

            console.log("getOperation. responses: ", responses)
            const initialApiResponse = responses[1]
            operation
                .on("complete", (longRunningRecognizeResponse /*, longRunningRecognizeMetadata, finalApiResponse*/) => {
                    // Adding a listener for the "complete" event starts polling for the
                    // completion of the operation.

                    const speechRecognitionResults = longRunningRecognizeResponse.results as ISpeechRecognitionResult[]
                    // resolve(speechRecognitionResults)
                    console.log("complete: ", speechRecognitionResults)
                })
                .on("progress", async (longRunningRecognizeMetadata /*, apiResponse*/) => {
                    // Adding a listener for the "progress" event causes the callback to be
                    // called on any change in metadata when the operation is polled.

                    const percent = longRunningRecognizeMetadata.progressPercent

                    console.log("progress. Percent", longRunningRecognizeMetadata.progressPercent /*, apiResponse*/)
                })
                .on("error", (error: Error) => {
                    // Adding a listener for the "error" event handles any errors found during polling.
                    // reject(error)
                    console.log("error: ", error)
                })
            res.contentType("application/json").status(200).send(JSON.stringify(initialApiResponse))
        } else {
            res.send(404)
        }
    } catch (error) {
        console.error("Failed to fetch operation by googleSpeechRef: ", googleSpeechRef, ". Error: ", error);
        res.status(500).send(serializeError(error))
    }
}
</code>```

The error i get is:

```<code>{
"code": 13,
"details": "Not enough responses received",
"metadata":{
"internalRepr":{}
},
"note": "Exception occurred in retry method that was not classified as transient",
"name": "Error",
"message": "Not enough responses received",
"stack": "Error: Not enough responses received\n at Http2CallStream.call.on (/srv/node_modules/@grpc/grpc-js/build/src/client.js:102:45)\n at emitOne (events.js:121:20)\n at Http2CallStream.emit (events.js:211:7)\n at Http2CallStream.endCall (/srv/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)\n at /srv/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18\n at <anonymous>\n at process._tickDomainCallback (internal/process/next_tick.js:229:7)"
}
</code>```

答:
For anybody finding this question later. My challenge was solved by this answer https://github.com/googleapis/nodejs-speech/issues/10#issuecomment-415900469 </p>

```<code>const { google } = require('googleapis');

(async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  });
  const { data } = await google.speech('v1').operations.get({ auth, name: OPERATION_NAME });

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

Body:
I'm using Google Speech to Text Node.js client.
When starting long-running speech transcription, I need to split the operation in two steps.
1. Start the transcription, and return the "name".
2. Ask for the status of the operation.
Ie replicating https://cloud.google.com/speech-to-text/docs/async-recognize#speech-async-recognize-gcs-protocol in nodejs.

My problem is to figure out how to create an OperationsClient, and to make the getOperation({name}) to actually return the result of the transcription.

I do run this code inside two firebase cloud functions:
1. The one that starts the trancscription, and then return the "name". This one works really well with the SpeechClient.
2. Another one that should call operationsClient.getOperation aka the same as curl to "https://speech.googleapis.com/v1/operations/"

import gax, {GrpcClient, GrpcClientOptions, lro} from "google-gax";
const gaxOpts = {
    clientConfig: {}
}
const gaxGrpc = new GrpcClient(gaxOpts);

...

app.get('/operations/:googleSpeechRef', async (req, res) => {
    const googleSpeechRef = req.params.googleSpeechRef;

    const operationsClient = lro({
        auth: gaxGrpc.auth,
        grpc: gaxGrpc.grpc,
    }).operationsClient(gaxOpts);
try {
        const [responses] = await operationsClient.getOperation({name: googleSpeechRef},{});
        if (responses) {
            const operation = responses[0]

            console.log("getOperation. responses: ", responses)
            const initialApiResponse = responses[1]
            operation
                .on("complete", (longRunningRecognizeResponse /*, longRunningRecognizeMetadata, finalApiResponse*/) => {
                    // Adding a listener for the "complete" event starts polling for the
                    // completion of the operation.

                    const speechRecognitionResults = longRunningRecognizeResponse.results as ISpeechRecognitionResult[]
                    // resolve(speechRecognitionResults)
                    console.log("complete: ", speechRecognitionResults)
                })
                .on("progress", async (longRunningRecognizeMetadata /*, apiResponse*/) => {
                    // Adding a listener for the "progress" event causes the callback to be
                    // called on any change in metadata when the operation is polled.

                    const percent = longRunningRecognizeMetadata.progressPercent

                    console.log("progress. Percent", longRunningRecognizeMetadata.progressPercent /*, apiResponse*/)
                })
                .on("error", (error: Error) => {
                    // Adding a listener for the "error" event handles any errors found during polling.
                    // reject(error)
                    console.log("error: ", error)
                })
            res.contentType("application/json").status(200).send(JSON.stringify(initialApiResponse))
        } else {
            res.send(404)
        }
    } catch (error) {
        console.error("Failed to fetch operation by googleSpeechRef: ", googleSpeechRef, ". Error: ", error);
        res.status(500).send(serializeError(error))
    }
}

The error i get is:

{
"code": 13,
"details": "Not enough responses received",
"metadata":{
"internalRepr":{}
},
"note": "Exception occurred in retry method that was not classified as transient",
"name": "Error",
"message": "Not enough responses received",
"stack": "Error: Not enough responses received\n at Http2CallStream.call.on (/srv/node_modules/@grpc/grpc-js/build/src/client.js:102:45)\n at emitOne (events.js:121:20)\n at Http2CallStream.emit (events.js:211:7)\n at Http2CallStream.endCall (/srv/node_modules/@grpc/grpc-js/build/src/call-stream.js:74:18)\n at /srv/node_modules/@grpc/grpc-js/build/src/call-stream.js:355:18\n at <anonymous>\n at process._tickDomainCallback (internal/process/next_tick.js:229:7)"
}

Body:
For anybody finding this question later. My challenge was solved by this answer https://github.com/googleapis/nodejs-speech/issues/10#issuecomment-415900469

const { google } = require('googleapis');

(async () => {
  const auth = await google.auth.getClient({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  });
  const { data } = await google.speech('v1').operations.get({ auth, name: OPERATION_NAME });

  console.log(data);
})();


问:
Javascript, draw window with text over
I am more into the simpler desktop programming scene (when it comes to this sort of stuff it is a hell of a lot simpler to deal with).

I have a large .png file I wish to display in the browser which is effectively a map with icons and when a user hovers over the icon I want to draw (preferably) a graphical window of sorts (can be another image pre-designed) and put styled text on this window (a basic display).

The .png is to be used in  tag using <map> and <area>, so <canvas> and applicable javascript functions are out of the question, it does not work, not ever with transparent double trickery (already tried it).

On a side note, why on earth has such a simple task that my 8 year old sister can do in an old IDE and Language on Windows and I can't get close in a browsers LOL!

答:
Check out this question about a canvas quivalent of image map.  From the answers, especially this link seems to hold the answer, albeit with canvas and javascript (which you couldn’t get to work).

You might also find Mark Pilgrim’s Introduction to the HTML5 Canvas useful, especially his live example, since that draws images and text onto a canvas, and handles very precise clicks.

Title: Javascript, draw window with text over <img>


问:
Count all persons who has ticket filed in last 12 months Grouped per month
I have these sample tables:

```<code>CREATE TABLE #tmp_persons (
    PersonID int primary key identity
    , FirstName varchar(max)
    , LastName varchar(max)
)

CREATE TABLE #tmp_tickets (
    TicketNum int primary key identity
    , Title varchar(max)
    , Descr varchar(max)
    , DateFiled datetime
    , SubmittedBy int FOREIGN KEY REFERENCES #tmp_persons(PersonID)
)

CREATE TABLE #tmp_assigned_lead (
    AssignmentID int primary key identity
    , PersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the Lead
    , AssignedPersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the person assigned
)

-- DATA DUMP
INSERT INTO #tmp_persons
VALUES
(1, 'John', 'Doe'), (2, 'Jane', 'Doe'),
(3, 'Carl', 'Smith'), (4, 'Jenny', 'Smith'),
(5, 'John', 'Wick'), (6, 'Stephanie', 'Mathews')

INSERT INTO #tmp_assigned_lead (PersonID, AssignedPersonID)
VALUES
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)

INSERT INTO #tmp_tickets (Title, Descr, DateFiled, SubmittedBy)
VALUES
('Ticket 1', 'blah', '01-01-2019', 2),
('Ticket 2', 'blah', '01-02-2019', 2),
('Ticket 3', 'blah', '05-01-2019', 4),
('Ticket 4', 'blah', '05-01-2019', 2),
('Ticket 5', 'blah', '06-01-2019', 5),
('Ticket 6', 'blah', '07-01-2019', 6),--
('Ticket 7', 'blah', '4-17-2018', 6),
('Ticket 8', 'blah', '12-30-2018', 6),
('Ticket 9', 'blah', '1-28-2019', 3),
('Ticket 10', 'blah', '3-16-2019', 3),
('Ticket 11', 'blah', '3-30-2018', 5),
('Ticket 12', 'blah', '2-4-2018', 4),
('Ticket 13', 'blah', '1-11-2019', 6),
('Ticket 14', 'blah', '9-5-2018', 6)
</code>```

So here are the points:

Each person in #tmp_persons can have a "lead" and this is stored in
a relational table #tmp_assigned_lead.

A person can file a ticket
which is stored in #tmp_tickets

A person is called a Contributor when he filed a ticket but goes back as a normal member when he doesnt file another ticket within 12 months.

Now my requirement is, I want to count all persons under a lead which have transitioned into Contributor per month. This will be a monthly record.

Sample Scenarios:

Person1 was registered Jan 01, 2018 and has never filed a ticket ever since until just Jan 01, 2019 when he filed his first ticket. This will consider Person1 as Contributor only for the month of January 2019 but he is a normal member from Jan 2018 up to Dec 2018.

Person1 filed another ticket in Feb 2019. Although he filed a new ticket, he is still not counted in Feb 2019 records of members who became Contributor since he is already a Contributor in Jan 2019

Person2 is registered in Feb 23, 2019 and immediately filed a ticket. This makes him/her a Contributor and is included in the count for "members who became contributors" in the month of Feb 2019.

This query I have come up so far groups the tickets per person and month:

```<code>SELECT
    SubmittedBy
    , MaxDate = MAX(DateFiled)
    , PeriodMonth = MONTH(DateFiled)
    , PeriodYear = YEAR(DateFiled)
FROM #tmp_tickets
GROUP BY
    SubmittedBy
    , MONTH(DateFiled)
    , YEAR(DateFiled)
</code>```

This is where I am at a roadblock. I can't come up with a query will return number of members under a lead, who became Contributors.

This is what I have so far. I used the above query as a CTE:

```<code>;with cte as (
    SELECT
        SubmittedBy
        , MaxDate = MAX(DateFiled)
        , PeriodMonth = MONTH(DateFiled)
        , PeriodYear = YEAR(DateFiled)
    FROM #tmp_tickets
    GROUP BY
        SubmittedBy
        , MONTH(DateFiled)
        , YEAR(DateFiled)
)
SELECT
    lead.PersonID
    , ContributorsCnt = COUNT(1)
    , PeriodMonth
    , PeriodYear
FROM #tmp_assigned_lead lead
INNER JOIN cte
    ON lead.AssignedPersonID = cte.SubmittedBy
-- WHERE??
-- check if member has no tickets in the past 12 months
GROUP BY
    lead.PersonID
    , PeriodMonth
    , PeriodYear
</code>```

Per data sample here, this is what the records look like in the cte above:

EDIT:

Added data dump and analysis points.

Points:

On 2018-02, PersonID 4 became a contributor. No one else filed a ticket except him. This will give us a row with:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1

On 2018-03, none other than PersonID 5 became a contributor. Again, this will give us another row:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1

On 2018-04, PersonID 6, became a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1

From 2018-05 to 2019-01, no one else became Contributor. PersonID 6 here is not counted because he is still a contributor.

On 2019-01, PersonID 2 and 3 became contributors. This is their first time filing ticket. Again, PersonID 6 is still a contributor. This will give us row:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2

On 2019-02, PersonID 4 is back to being a normal member, not a contributor, since it has been 12 months and he did not file any ticket since then. No row needed for this.

On 2019-03, PersonID 5 becomes a normal member (same logic in point #6). Person 3 filed a ticket but he is still a contributor. Overall, no row needed.

On 2019-05, Person 2 filed a ticket but he is still a contributor. Person 4 filed a ticket and he is already a regular member so he is now a Contributor:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1

On 2019-06, Person 5 becomes a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

On 2019-07, Person 6 filed a ticket but he is still a contributor since his last ticket was filed on 2019-01. (What a busy man!)

Expected Data Set:

```<code>LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1
LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2
LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1
</code>```

I hope this helps clarify my question.

答:
Try to keep a record about whether a person is a contributor or not. Create another table to keep this records or modify

```<code>CREATE TABLE #tmp_persons (
PersonID int primary key identity
, FirstName varchar(max)
, LastName varchar(max)
, isContributor int
, contributorSince datetime
</code>```

)

Each time a person creates a ticket check whether it's a time to update contributorSince and isContributor . If yes update it, otherwise leave it as is.

Group persons by personId and contributorSince (month, year, ...) where isContributor is set to true and contributorSince is within a timeframe you are interested in.

isContributor might not be neccessary. Since you can do it just with contributorSince

Body:
I have these sample tables:

CREATE TABLE #tmp_persons (
    PersonID int primary key identity
    , FirstName varchar(max)
    , LastName varchar(max)
)

CREATE TABLE #tmp_tickets (
    TicketNum int primary key identity
    , Title varchar(max)
    , Descr varchar(max)
    , DateFiled datetime
    , SubmittedBy int FOREIGN KEY REFERENCES #tmp_persons(PersonID)
)

CREATE TABLE #tmp_assigned_lead (
    AssignmentID int primary key identity
    , PersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the Lead
    , AssignedPersonID int FOREIGN KEY REFERENCES #tmp_persons(PersonID) -- ID of the person assigned
)

-- DATA DUMP
INSERT INTO #tmp_persons
VALUES
(1, 'John', 'Doe'), (2, 'Jane', 'Doe'),
(3, 'Carl', 'Smith'), (4, 'Jenny', 'Smith'),
(5, 'John', 'Wick'), (6, 'Stephanie', 'Mathews')

INSERT INTO #tmp_assigned_lead (PersonID, AssignedPersonID)
VALUES
(1, 2), (1, 3), (1, 4), (1, 5), (1, 6)

INSERT INTO #tmp_tickets (Title, Descr, DateFiled, SubmittedBy)
VALUES
('Ticket 1', 'blah', '01-01-2019', 2),
('Ticket 2', 'blah', '01-02-2019', 2),
('Ticket 3', 'blah', '05-01-2019', 4),
('Ticket 4', 'blah', '05-01-2019', 2),
('Ticket 5', 'blah', '06-01-2019', 5),
('Ticket 6', 'blah', '07-01-2019', 6),--
('Ticket 7', 'blah', '4-17-2018', 6),
('Ticket 8', 'blah', '12-30-2018', 6),
('Ticket 9', 'blah', '1-28-2019', 3),
('Ticket 10', 'blah', '3-16-2019', 3),
('Ticket 11', 'blah', '3-30-2018', 5),
('Ticket 12', 'blah', '2-4-2018', 4),
('Ticket 13', 'blah', '1-11-2019', 6),
('Ticket 14', 'blah', '9-5-2018', 6)

So here are the points:

Each person in #tmp_persons can have a "lead" and this is stored in
a relational table #tmp_assigned_lead.

A person can file a ticket
which is stored in #tmp_tickets

A person is called a Contributor when he filed a ticket but goes back as a normal member when he doesnt file another ticket within 12 months.

Now my requirement is, I want to count all persons under a lead which have transitioned into Contributor per month. This will be a monthly record.

Sample Scenarios:

Person1 was registered Jan 01, 2018 and has never filed a ticket ever since until just Jan 01, 2019 when he filed his first ticket. This will consider Person1 as Contributor only for the month of January 2019 but he is a normal member from Jan 2018 up to Dec 2018.

Person1 filed another ticket in Feb 2019. Although he filed a new ticket, he is still not counted in Feb 2019 records of members who became Contributor since he is already a Contributor in Jan 2019

Person2 is registered in Feb 23, 2019 and immediately filed a ticket. This makes him/her a Contributor and is included in the count for "members who became contributors" in the month of Feb 2019.

This query I have come up so far groups the tickets per person and month:

SELECT
    SubmittedBy
    , MaxDate = MAX(DateFiled)
    , PeriodMonth = MONTH(DateFiled)
    , PeriodYear = YEAR(DateFiled)
FROM #tmp_tickets
GROUP BY
    SubmittedBy
    , MONTH(DateFiled)
    , YEAR(DateFiled)

This is where I am at a roadblock. I can't come up with a query will return number of members under a lead, who became Contributors.

This is what I have so far. I used the above query as a CTE:

;with cte as (
    SELECT
        SubmittedBy
        , MaxDate = MAX(DateFiled)
        , PeriodMonth = MONTH(DateFiled)
        , PeriodYear = YEAR(DateFiled)
    FROM #tmp_tickets
    GROUP BY
        SubmittedBy
        , MONTH(DateFiled)
        , YEAR(DateFiled)
)
SELECT
    lead.PersonID
    , ContributorsCnt = COUNT(1)
    , PeriodMonth
    , PeriodYear
FROM #tmp_assigned_lead lead
INNER JOIN cte
    ON lead.AssignedPersonID = cte.SubmittedBy
-- WHERE??
-- check if member has no tickets in the past 12 months
GROUP BY
    lead.PersonID
    , PeriodMonth
    , PeriodYear

Per data sample here, this is what the records look like in the cte above:

EDIT:

Added data dump and analysis points.

Points:

On 2018-02, PersonID 4 became a contributor. No one else filed a ticket except him. This will give us a row with:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1

On 2018-03, none other than PersonID 5 became a contributor. Again, this will give us another row:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1

On 2018-04, PersonID 6, became a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1

From 2018-05 to 2019-01, no one else became Contributor. PersonID 6 here is not counted because he is still a contributor.

On 2019-01, PersonID 2 and 3 became contributors. This is their first time filing ticket. Again, PersonID 6 is still a contributor. This will give us row:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2

On 2019-02, PersonID 4 is back to being a normal member, not a contributor, since it has been 12 months and he did not file any ticket since then. No row needed for this.

On 2019-03, PersonID 5 becomes a normal member (same logic in point #6). Person 3 filed a ticket but he is still a contributor. Overall, no row needed.

On 2019-05, Person 2 filed a ticket but he is still a contributor. Person 4 filed a ticket and he is already a regular member so he is now a Contributor:

LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1

On 2019-06, Person 5 becomes a contributor:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

On 2019-07, Person 6 filed a ticket but he is still a contributor since his last ticket was filed on 2019-01. (What a busy man!)

Expected Data Set:

LeadID: 1, PeriodYear: 2018, PeriodMonth: 2, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 3, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 4, Contributor: 1
LeadID: 1, PeriodYear: 2019, PeriodMonth: 1, Contributor: 2
LeadID: 1, PeriodYear: 2019, PeriodMonth: 5, Contributor: 1
LeadID: 1, PeriodYear: 2018, PeriodMonth: 5 Contributor: 1

I hope this helps clarify my question.

Body:
Try to keep a record about whether a person is a contributor or not. Create another table to keep this records or modify

CREATE TABLE #tmp_persons (
PersonID int primary key identity
, FirstName varchar(max)
, LastName varchar(max)
, isContributor int
, contributorSince datetime

)

Each time a person creates a ticket check whether it's a time to update contributorSince and isContributor . If yes update it, otherwise leave it as is.

Group persons by personId and contributorSince (month, year, ...) where isContributor is set to true and contributorSince is within a timeframe you are interested in.

isContributor might not be neccessary. Since you can do it just with contributorSince


问:
Angular removing template white space
If  I have this Bootstrap markup it renders the buttons fine with spaces between them

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <form>
    <button type="submit" class="btn btn-primary">Submit</button>
    <button type="reset" class="btn btn-secondary">Reset</button>
  </form>

```
</div>
</div>
</p>

<p>But if I have the same markup in an Angular template as in this StackBlitz https://stackblitz.com/edit/angular-fqw3g6?file=src/app/app.component.html then the white space is removed and the buttons touch each other.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link _ngcontent-cyj-c2="" crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" rel="stylesheet"><div _ngcontent-cyj-c2="" class="container-fluid"><form _ngcontent-cyj-c2="" novalidate="" class="ng-untouched ng-pristine ng-valid"><button _ngcontent-cyj-c2="" class="btn btn-primary" type="submit">Submit</button><button _ngcontent-cyj-c2="" class="btn btn-secondary" type="reset">Reset</button></form></div></code>```

Is it possible to get Angular to preserve template white space as it is particularly important in this case.

答:
Angular has a white space optimization which is turned on by default. If you want to prevent that you can either set in the @Component preserveWhitespaces: true

```<code>@Component({
   selector: 'my-app',
   templateUrl: './app.component.html',
   styleUrls: [ './app.component.css' ],
   preserveWhitespaces: true
})
export class AppComponent  {}
</code>```

or

for the full application in the tsconfig.app.json in the section "compilerOptions" by adding the value preserveWhitespaces: true

If possible use the first option because whitespaces blow your bundles.

Title: Angular removing template white space

Body:
If  I have this Bootstrap markup it renders the buttons fine with spaces between them

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <form>
    <button type="submit" class="btn btn-primary">Submit</button>
    <button type="reset" class="btn btn-secondary">Reset</button>
  </form>

But if I have the same markup in an Angular template as in this StackBlitz https://stackblitz.com/edit/angular-fqw3g6?file=src/app/app.component.html then the white space is removed and the buttons touch each other.

<link _ngcontent-cyj-c2="" crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" rel="stylesheet">
<form _ngcontent-cyj-c2="" novalidate="" class="ng-untouched ng-pristine ng-valid"><button _ngcontent-cyj-c2="" class="btn btn-primary" type="submit">Submit</button><button _ngcontent-cyj-c2="" class="btn btn-secondary" type="reset">Reset</button></form>

Is it possible to get Angular to preserve template white space as it is particularly important in this case.

Body:
Angular has a white space optimization which is turned on by default. If you want to prevent that you can either set in the @Component preserveWhitespaces: true

@Component({
   selector: 'my-app',
   templateUrl: './app.component.html',
   styleUrls: [ './app.component.css' ],
   preserveWhitespaces: true
})
export class AppComponent  {}

or

for the full application in the tsconfig.app.json in the section "compilerOptions" by adding the value preserveWhitespaces: true

If possible use the first option because whitespaces blow your bundles.


问:
How to center a Node in Graphviz
I have this graph:

```<code>digraph Database {
graph [bb="0 0 180 96",
    fontname="Verdana-Bold",
    fontsize=14,
    labeljust=r,
    labelloc=t,
    margin=12,
    nodesep=0.5555555555555556,
    pad=0.5,
    rankdir=RL,
    ranksep=0.3472222222222222,
    sep=0.05,
    splines=spline
];
node [fixedsize=true,
    fontname=Verdana,
    fontsize=11,
    height=40,
    label="correct me",
    labelloc=c,
    margin=0,
    shape=box,
    style=rounded,
    width=100
];
Node1   [fontsize=14.0,
    height=1.3333333333333333,
    label="Here a long enough
example of a node.
Unfortunately, the text
won't remain in the box",
        width=2.4944932725694446];
}
</code>```

which produces this output:

Why is that so? (not sure why picture itself is so small)
The text/label should be centered (labelloc=c) but isn't.

答:
Apparently, this code is created with some "tool" that adds lots of nonsensical stuff to the code. graphviz, if instructed in clear and simple terms, doesn't have that problem:

```<code>digraph Database
{
    Node1 [ shape = box, style = rounded,
    label="Here a long enough example of a node.\nUnfortunately, the text won't remain in the box"]
}
</code>```

yields

How does this help you? If you want to create a graph with your tool, you will need to find out how to fine tune the settings in a way that it does what you want. Or you start (which would be my recommendation) working with graphviz directly. Then, you could start with the basics and move to the more complicated formatting options only when and to the extent actually needed.

Title: How to center a Node in Graphviz

Body:
I have this graph:

digraph Database {
graph [bb="0 0 180 96",
    fontname="Verdana-Bold",
    fontsize=14,
    labeljust=r,
    labelloc=t,
    margin=12,
    nodesep=0.5555555555555556,
    pad=0.5,
    rankdir=RL,
    ranksep=0.3472222222222222,
    sep=0.05,
    splines=spline
];
node [fixedsize=true,
    fontname=Verdana,
    fontsize=11,
    height=40,
    label="correct me",
    labelloc=c,
    margin=0,
    shape=box,
    style=rounded,
    width=100
];
Node1   [fontsize=14.0,
    height=1.3333333333333333,
    label="Here a long enough
example of a node.
Unfortunately, the text
won't remain in the box",
        width=2.4944932725694446];
}

which produces this output:

Why is that so? (not sure why picture itself is so small)
The text/label should be centered (labelloc=c) but isn't.

Body:
Apparently, this code is created with some "tool" that adds lots of nonsensical stuff to the code. graphviz, if instructed in clear and simple terms, doesn't have that problem:

digraph Database
{
    Node1 [ shape = box, style = rounded,
    label="Here a long enough example of a node.\nUnfortunately, the text won't remain in the box"]
}

yields

How does this help you? If you want to create a graph with your tool, you will need to find out how to fine tune the settings in a way that it does what you want. Or you start (which would be my recommendation) working with graphviz directly. Then, you could start with the basics and move to the more complicated formatting options only when and to the extent actually needed.


问:
PHP isn't processing some form fields
I recently created a PHP/MySQL comment system, and it was working until a few hours ago (no changes at all in the code). When I tell the submit form code to echo the query, it shows that the area for commenttext and date is missing. I don't see why. Here's my code:</p>

```
mysql_connect("localhost","commentUser","password");
mysql_select_db("comments");
$name = mysql_real_escape_string($_POST['name']);
$postID = mysql_real_escape_string($_POST['postId']);
if(!is_numeric($postID))
    exit();
$email = mysql_real_escape_string($_POST['email']);
$comment = strip_tags(mysql_real_escape_string($_POST['comment']), '');
$date = mysql_real_escape_string($_POST['date']);

if($email == '' || $comment = '' || $date = '')
    exit();

$query = "INSERT INTO comments (PostID,Name,Email,Text,Date) VALUES($postID, '$name', '$email', '$comment', '$date')";
mysql_query($query) or die(mysql_error());
mysql_close();

    echo "

            window.location = \"snippet.php?id=$postID\";

    ";

```

答:
You are trying to compare $comment and $date with invalid character
please replace this line:
if($email == '' || $comment = '' || $date = '')
with
if($email == '' || $comment = '' || $date == '')

Title: PHP isn't processing some form fields

Body:
I recently created a PHP/MySQL comment system, and it was working until a few hours ago (no changes at all in the code). When I tell the submit form code to echo the query, it shows that the area for commenttext and date is missing. I don't see why. Here's my code:

mysql_connect("localhost","commentUser","password");
mysql_select_db("comments");
$name = mysql_real_escape_string($_POST['name']);
$postID = mysql_real_escape_string($_POST['postId']);
if(!is_numeric($postID))
    exit();
$email = mysql_real_escape_string($_POST['email']);
$comment = strip_tags(mysql_real_escape_string($_POST['comment']), '');
$date = mysql_real_escape_string($_POST['date']);

if($email == '' || $comment = '' || $date = '')
    exit();

$query = "INSERT INTO comments (PostID,Name,Email,Text,Date) VALUES($postID, '$name', '$email', '$comment', '$date')";
mysql_query($query) or die(mysql_error());
mysql_close();

    echo "

            window.location = \"snippet.php?id=$postID\";

    ";


问:
Inline javascript validation does not work for jsp files
I am working on a java based web application which is being designed using jsp and servlets. I am having a difficulty with a form validation script in my project.

I need to include an external javascript file in one of my jsp pages.

I tried to include it in this way in the jsp page.

The validation script looks like this:

https://github.com/nirmaniPathiranage/Hotel-Property-Management/blob/master/WebContent/js/script.js

And the form looks like this:

https://github.com/nirmaniPathiranage/Hotel-Property-Management/blob/master/WebContent/Register.jsp

But when I am running the application, the system behavior seems like no script is running. The expected validations are not activated.

I have no idea about this. I have included both the .js and .jsp files inside the WebContent folder of the project.

I can't seem to figure this out. Any help would be appreciated.

答: There should be no spaces in your path type="${pageContext.request.contextPath}/Property Management System/WebContent/js/script.js". Remove the spaces in Property Management System and try. It should work.


问:
Ansible playbook with variable
Trying to run script with different arguments on different servers using ansible, example:

```<code>server 192.168.0.1 -> fabric.sh generic1 status
server 192.168.0.2 -> fabric.sh generic2dr status
server 192.168.0.3 -> fabric.sh generic3 status
</code>```

How to use variables in playbook below?

It works when I create group for each server, but it's not efficient

```<code>---
- hosts: esb
  remote_user: root
  tasks:
  - name: Generic_1
    become_user: esb
    shell: "/home/fabric.sh generic1 status"
</code>```

Host file:

```<code>[esb]
192.168.0.1
192.168.0.2
192.168.0.3
</code>```

答:
Next to Basic inventory there is yaml – Uses a specific YAML file as an inventory source.

For example (fit the variables to your needs):

```<code>$ cat hosts
all:
  hosts:
    10.1.0.51:
    10.1.0.52:
    10.1.0.53:
  vars:
    ansible_connection: ssh
    ansible_user: admin
    ansible_become: yes
    ansible_become_user: root
    ansible_become_method: sudo
    ansible_python_interpreter: /usr/local/bin/python3.6
    ansible_perl_interpreter: /usr/local/bin/perl
  children:
    esb:
      hosts:
        10.1.0.51:
          run_string: "fabric.sh generic1 status"
        10.1.0.52:
          run_string: "fabric.sh generic2dr status"
        10.1.0.53:
          run_string: "fabric.sh generic3 status"
</code>```

The play below

```<code>- hosts: esb
  tasks:
  - debug:
      var: run_string
</code>```

gives (abridged):

```<code>ok: [10.1.0.51] => {
    "run_string": "generic1 status"
}
ok: [10.1.0.52] => {
    "run_string": "generic2dr status"
}
ok: [10.1.0.53] => {
    "run_string": "generic3 status"
}
</code>```

Title: Ansible playbook with variable

Body:
Trying to run script with different arguments on different servers using ansible, example:

server 192.168.0.1 -> fabric.sh generic1 status
server 192.168.0.2 -> fabric.sh generic2dr status
server 192.168.0.3 -> fabric.sh generic3 status

How to use variables in playbook below?

It works when I create group for each server, but it's not efficient

---
- hosts: esb
  remote_user: root
  tasks:
  - name: Generic_1
    become_user: esb
    shell: "/home/fabric.sh generic1 status"

Host file:

[esb]
192.168.0.1
192.168.0.2
192.168.0.3

Body:
Next to Basic inventory there is yaml – Uses a specific YAML file as an inventory source.

For example (fit the variables to your needs):

$ cat hosts
all:
  hosts:
    10.1.0.51:
    10.1.0.52:
    10.1.0.53:
  vars:
    ansible_connection: ssh
    ansible_user: admin
    ansible_become: yes
    ansible_become_user: root
    ansible_become_method: sudo
    ansible_python_interpreter: /usr/local/bin/python3.6
    ansible_perl_interpreter: /usr/local/bin/perl
  children:
    esb:
      hosts:
        10.1.0.51:
          run_string: "fabric.sh generic1 status"
        10.1.0.52:
          run_string: "fabric.sh generic2dr status"
        10.1.0.53:
          run_string: "fabric.sh generic3 status"

The play below

- hosts: esb
  tasks:
  - debug:
      var: run_string

gives (abridged):

ok: [10.1.0.51] => {
    "run_string": "generic1 status"
}
ok: [10.1.0.52] => {
    "run_string": "generic2dr status"
}
ok: [10.1.0.53] => {
    "run_string": "generic3 status"
}


问:
ClassCastException with new Appium-java TouchActions
I am getting below error with new TouchActions class.

JDK version: 1.8

Appium: 1.7.2

appium.java-client.version: 6.0.0-BETA2

selenium.java.version: 3.8.1

```<code>TouchActions actions = new TouchActions(appiumDriver);
</code>```

Runtime Error:

java.lang.ClassCastException: io.appium.java_client.ios.IOSDriver cannot be cast to org.openqa.selenium.interactions.HasTouchScreen

Whereas, old below works all fine:

```<code>TouchAction touchAction = new TouchAction(appiumDriver);
</code>```

答:
Use io.appium.java_client.TouchAction class.

Step 1

TouchAction action = new TouchAction(driver);
```
<p>Here <code>driver</code> is an instance of <code>AppiumDriver</code>.</p>
<p><strong>Step 2</strong></p>
<pre class="lang-java prettyprint-override"><code>WebElement ele = driver.findElement(By.id("locator"));

action.tap(new TapOptions().withElement(new ElementOption().withElement(ele))).perform();
</code>```

With the new implementation of TouchAction you cannot directly pass weblement.

dependency used

```<code><dependency>
        <groupId>io.appium</groupId>
        <artifactId>java-client</artifactId>
        <version>7.0.0</version>
    </dependency>
</code>```

Body:
I am getting below error with new TouchActions class.

JDK version: 1.8

Appium: 1.7.2

appium.java-client.version: 6.0.0-BETA2

selenium.java.version: 3.8.1

TouchActions actions = new TouchActions(appiumDriver);

Runtime Error:

java.lang.ClassCastException: io.appium.java_client.ios.IOSDriver cannot be cast to org.openqa.selenium.interactions.HasTouchScreen

Whereas, old below works all fine:

TouchAction touchAction = new TouchAction(appiumDriver);

Body:
Use io.appium.java_client.TouchAction class.

Step 1

TouchAction action = new TouchAction(driver);

Here driver is an instance of AppiumDriver.

Step 2

WebElement ele = driver.findElement(By.id("locator"));

action.tap(new TapOptions().withElement(new ElementOption().withElement(ele))).perform();

With the new implementation of TouchAction you cannot directly pass weblement.

dependency used

<dependency>
        <groupId>io.appium</groupId>
        <artifactId>java-client</artifactId>
        <version>7.0.0</version>
    </dependency>


问:
In Jupyter Lab, execute editor code in Python console
In JupyterLab, I want to send code from the editor to the Python console for execution, preferably with a keyboard shortcut. The documentation doesn't seem to offer a way to do this, but it's such a fundamental aspect of an IDE that I imagine it's probably possible.</p>

答:
The answer:

Select your desired line(s) and use Run > Run Selected Text or Current Line in Console, or define your own shortcut under Settings > Advanced Settings > Keyboard Shortcuts:

```<code>{
    // List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:run-in-console",
            "keys": [
                "F9"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}
</code>```

The details:

Option 1 - Send code from the editor to the Python console:

While the cell is active, click Run and select Run Selected Text or Current Line in Console.

Test run and output:

For those trying JupyterLab for the first time, this is opposed to the standard option of hitting ctrl+Enter and getting the output within JupyterLab itself:

Option 2 - Assign and use a keyboard shortcut:

There's no standard shortcut for this, but you can quite easily set it up yourself if you follow these few easy steps:

2.1 - Go to Settings and select Advanced Settings editor:

**

Step 2.2 for newer versions - Insert the following under User Preferences:

```<code>{
    // List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:run-in-console",
            "keys": [
                "F9"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}
</code>```

Step 2.2 for older versions- Write the following under User Overrides and type in your desired shortcut below keys:

```<code>// [missing schema title]
    // [missing schema description]
    "notebook:run-in-console": {
      "command": "notebook:run-in-console",
      "keys": [
        "F9"
      ],
      "selector": ".jp-Notebook.jp-mod-editMode",
      "title": "Run In Console",
      "category": "Notebook Cell Operations"
    }
</code>```

As you can see, my preferred shortcut is F9.

2.3 - Click Save All under File.

And if you close and reopen your notebook, you'll see that you've assigned F9 as a shortcut in the menu itself:

2.4.1 - Run single line / Send single line to IPython console.

Just put your marker on the desired line and click F9:

2.4.2 - Run selected code / send selected text to IPython console:

Just select your desired code and click F9

Body:
The answer:

Select your desired line(s) and use Run > Run Selected Text or Current Line in Console, or define your own shortcut under Settings > Advanced Settings > Keyboard Shortcuts:

{
    // List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:run-in-console",
            "keys": [
                "F9"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}

The details:

Option 1 - Send code from the editor to the Python console:

While the cell is active, click Run and select Run Selected Text or Current Line in Console.

Test run and output:

For those trying JupyterLab for the first time, this is opposed to the standard option of hitting ctrl+Enter and getting the output within JupyterLab itself:

Option 2 - Assign and use a keyboard shortcut:

There's no standard shortcut for this, but you can quite easily set it up yourself if you follow these few easy steps:

2.1 - Go to Settings and select Advanced Settings editor:

**

Step 2.2 for newer versions - Insert the following under User Preferences:

{
    // List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:run-in-console",
            "keys": [
                "F9"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}

Step 2.2 for older versions- Write the following under User Overrides and type in your desired shortcut below keys:

// [missing schema title]
    // [missing schema description]
    "notebook:run-in-console": {
      "command": "notebook:run-in-console",
      "keys": [
        "F9"
      ],
      "selector": ".jp-Notebook.jp-mod-editMode",
      "title": "Run In Console",
      "category": "Notebook Cell Operations"
    }

As you can see, my preferred shortcut is F9.

2.3 - Click Save All under File.

And if you close and reopen your notebook, you'll see that you've assigned F9 as a shortcut in the menu itself:

2.4.1 - Run single line / Send single line to IPython console.

Just put your marker on the desired line and click F9:

2.4.2 - Run selected code / send selected text to IPython console:

Just select your desired code and click F9


问:
awk: dealing with variable in if statement
I am trying to understand how awk deals with variables in if statements.

Here is a toy text file:

```<code>$ cat myscript.sh
#! /bin/bash

set -eu
set -o pipefail

IFS=$'\n\t'

for arg in $@; do
    echo "do something with file $arg"
done
</code>```

Now I want awk to print the longest line in the file.
I thought of doing that:

```<code>$  awk '{max = 0}{if (length($0) > max) {max = length($0)} else {}} END {print max}' myscript.sh
</code>```

But this print the length of the last line.
However, when I run the following:

```<code>awk '{if (length($0) > max) {max = length($0)} else {}}END{print max}' myscript.sh
</code>```

The outcome is correct and it prints the right length 35.

I cannot really understand why when I specify the max variable before the if statement, the condition is not recognized.
I am sure there is an easy explanation for the awk-gurus, but I personally cannot see it.

Thank you

答:
You could change the first command a little bit to make it work :

```<code>awk 'BEGIN{max = 0}{if (length($0) > max) {max = length($0)} else {}} END {print max}' myscript.sh
</code>```

This way, you initialize the variable max at the beginning of the script. Without the BEGIN statement, max is being updated to 0 at every row.

However, awk variables have default values that depend on the context. You can read this to understand the logic behind.

Variables in awk can be assigned either numeric or string values. The kind of value a variable holds can change over the life of a program. By default, variables are initialized to the empty string, which is zero if converted to a number.

With this command :

```<code>awk '{if (length($0) > max) {max = length($0)} else {}}END{print max}' myscript.sh
</code>```

Awk will initialize max to 0 at the first row because you are comparing it to length($0) which is an integer.

Body:
I am trying to understand how awk deals with variables in if statements.

Here is a toy text file:

$ cat myscript.sh
#! /bin/bash

set -eu
set -o pipefail

IFS=$'\n\t'

for arg in $@; do
    echo "do something with file $arg"
done

Now I want awk to print the longest line in the file.
I thought of doing that:

$  awk '{max = 0}{if (length($0) > max) {max = length($0)} else {}} END {print max}' myscript.sh

But this print the length of the last line.
However, when I run the following:

awk '{if (length($0) > max) {max = length($0)} else {}}END{print max}' myscript.sh

The outcome is correct and it prints the right length 35.

I cannot really understand why when I specify the max variable before the if statement, the condition is not recognized.
I am sure there is an easy explanation for the awk-gurus, but I personally cannot see it.

Thank you

Body:
You could change the first command a little bit to make it work :

awk 'BEGIN{max = 0}{if (length($0) > max) {max = length($0)} else {}} END {print max}' myscript.sh

This way, you initialize the variable max at the beginning of the script. Without the BEGIN statement, max is being updated to 0 at every row.

However, awk variables have default values that depend on the context. You can read this to understand the logic behind.

Variables in awk can be assigned either numeric or string values. The kind of value a variable holds can change over the life of a program. By default, variables are initialized to the empty string, which is zero if converted to a number.

With this command :

awk '{if (length($0) > max) {max = length($0)} else {}}END{print max}' myscript.sh

Awk will initialize max to 0 at the first row because you are comparing it to length($0) which is an integer.


问:
Python: truncate a file to 100 lines or less
I'm pretty new to Python - just wondering if there was a library function or easy way to truncate a file to the first 100 lines or less? </p>

答:
Use one of the solutions here: Iterate over the lines of a string and just grab the first hundred, i.e.</p>

```<code>import itertools
lines = itertools.islice(iter, 100)
</code>```

Body:
Use one of the solutions here: Iterate over the lines of a string and just grab the first hundred, i.e.

import itertools
lines = itertools.islice(iter, 100)


问:
How to get file from storage by public URL?
I have application Laravel.

There is a storage by the path: \storage\app\reports\

I attempted to get file through GET url like:

```<code>http://localhost:8000/storage/app/reports/report_27-05-19_05.xlsx
</code>```

But it does not work for me.

Also I tried to return file in backend side:

```<code>$file = File::get(storage_path($path.$filename));
$type = File::mimeType($path.$filename);

$response = Response::make($file, 200);
$response->header("Content-Type", $type);

return $response;
</code>```

答:
Try something like this.

The following example is for csv file stored in shared hosting

$filename is the name of the saved file which will be passed with get request

```<code>public function download($filename)
{
    $name = $filename;
    $file = $file = '/home/USERNAME/storage/report/'.$name;

    $header = array(
        'Content-Type' => 'application/csv',
        'Content-Disposition' => 'attachment',
        'Content-lenght' => filesize($file),
        'filename' => $name,
    );

    // auth code
    return Response::download($file, $name, $header);
}
</code>```

Body:
I have application Laravel.

There is a storage by the path: \storage\app\reports\

I attempted to get file through GET url like:

http://localhost:8000/storage/app/reports/report_27-05-19_05.xlsx

But it does not work for me.

Also I tried to return file in backend side:

$file = File::get(storage_path($path.$filename));
$type = File::mimeType($path.$filename);

$response = Response::make($file, 200);
$response->header("Content-Type", $type);

return $response;

Body:
Try something like this.

The following example is for csv file stored in shared hosting

$filename is the name of the saved file which will be passed with get request

public function download($filename)
{
    $name = $filename;
    $file = $file = '/home/USERNAME/storage/report/'.$name;

    $header = array(
        'Content-Type' => 'application/csv',
        'Content-Disposition' => 'attachment',
        'Content-lenght' => filesize($file),
        'filename' => $name,
    );

    // auth code
    return Response::download($file, $name, $header);
}


问:
How can I use type-safe unions (variants) inside a class with template functions?
I would like to place a std::variant inside a class and return its elements with a template function. Here is an example:

#include <string>
#include <variant>
class Class {
   public:
    std::variant<std::string, double> cont;
    Class() {}
    template <class V> Class(const V v) { cont = v; }
    template <typename V> V fun() {
        if (std::holds_alternative<double>(cont))
            return std::get<double>(cont);
        else if (std::holds_alternative<std::string>(cont))
            return std::get<std::string>(cont);
    }
};

int main() {
    Class c;
    c = 20;
    double d = c.fun<double>();
    return 0;
}
```

<p>I try to return the elements of the class <code>Class</code> through the template function <code>fun</code>. However, <code>gcc-9.1</code> refuses to compile the code and tells me  </p>

```Class.cpp:12:46: error: cannot convert ‘std::__cxx11::basic_string<char>’ to ‘double’ in return
   12 |             return std::get<std::string>(cont);
```

Why is there any attempt to convert the string (the second return type of the function foo) to a double? Can I prevent this and solve the problem? Do I use the std::variant class unidiomatic?

答:
The issue here is that you query the current value stored at runtime, while the function signature of the template instantiation is performed at compile time. Consider how the member function looks like when you try using it to retrieve a double:

```<code>double fun() {
    if (/* ... */)
        return std::get<double>(cont); // Ok return type is double, too
    else if (/* ... */)
        return std::get<std::string>(cont); // Error, return type should be string?!
}
</code>```

This can't work. You need to change the way to access the data member, e.g. passing an overload set to std::visit, by providing two getter-like functions returning std::optional<double> and std::optional<std::string> or something similar.

Body:
I would like to place a std::variant inside a class and return its elements with a template function. Here is an example:

#include <string>
#include <variant>
class Class {
   public:
    std::variant<std::string, double> cont;
    Class() {}
    template <class V> Class(const V v) { cont = v; }
    template <typename V> V fun() {
        if (std::holds_alternative<double>(cont))
            return std::get<double>(cont);
        else if (std::holds_alternative<std::string>(cont))
            return std::get<std::string>(cont);
    }
};

int main() {
    Class c;
    c = 20;
    double d = c.fun<double>();
    return 0;
}

I try to return the elements of the class Class through the template function fun. However, gcc-9.1 refuses to compile the code and tells me

Class.cpp:12:46: error: cannot convert ‘std::__cxx11::basic_string<char>’ to ‘double’ in return
   12 |             return std::get<std::string>(cont);

Why is there any attempt to convert the string (the second return type of the function foo) to a double? Can I prevent this and solve the problem? Do I use the std::variant class unidiomatic?

Body:
The issue here is that you query the current value stored at runtime, while the function signature of the template instantiation is performed at compile time. Consider how the member function looks like when you try using it to retrieve a double:

double fun() {
    if (/* ... */)
        return std::get<double>(cont); // Ok return type is double, too
    else if (/* ... */)
        return std::get<std::string>(cont); // Error, return type should be string?!
}

This can't work. You need to change the way to access the data member, e.g. passing an overload set to std::visit, by providing two getter-like functions returning std::optional<double> and std::optional<std::string> or something similar.


问:
Message 'src refspec master does not match any' when pushing commits in Git
I clone my repository with:

```<code>git clone ssh://xxxxx/xx.git
</code>```

But after I change some files and add and commit them, I want to push them to the server:

```<code>git add xxx.php
git commit -m "TEST"
git push origin master
</code>```

But the error I get back is:

error: src refspec master does not match any.
error: failed to push some refs to 'ssh://xxxxx.com/project.git'
```

答:
Two possibilities:

1- Either you forgot to include the .gitignore file.

Here are all the steps required:

Create an empty Git repository on remote,

On local, create the .gitignore
file for your project. GitHub gives you a list of examples here

Launch a terminal, and in your project do the following commands:

```<code>git remote add origin YOUR/ORIGIN.git

git add .

git commit -m "initial commit or whatever message for first commit"

git push -u origin master
</code>```

2- Or you are trying to create a new GitHub project.

GitHub replaced master with main as the default branch name. To resolve the issue:

On your local project:

remove the .git folder if it exists

recreate a clean repository by launching the following in your project:

In the terminal:

```<code>git init

git add .

git commit -m "YOUR FIRST MESSAGE HERE"

git branch -M main

git remote add origin _GIT_LINK_TO_PROJECT_HERE_

git push -u origin main
</code>```

Body:
I clone my repository with:

git clone ssh://xxxxx/xx.git

But after I change some files and add and commit them, I want to push them to the server:

git add xxx.php
git commit -m "TEST"
git push origin master

But the error I get back is:

error: src refspec master does not match any.
error: failed to push some refs to 'ssh://xxxxx.com/project.git'

Body:
Two possibilities:

1- Either you forgot to include the .gitignore file.

Here are all the steps required:

Create an empty Git repository on remote,

On local, create the .gitignore
file for your project. GitHub gives you a list of examples here

Launch a terminal, and in your project do the following commands:

git remote add origin YOUR/ORIGIN.git

git add .

git commit -m "initial commit or whatever message for first commit"

git push -u origin master

2- Or you are trying to create a new GitHub project.

GitHub replaced master with main as the default branch name. To resolve the issue:

On your local project:

remove the .git folder if it exists

recreate a clean repository by launching the following in your project:

In the terminal:

git init

git add .

git commit -m "YOUR FIRST MESSAGE HERE"

git branch -M main

git remote add origin _GIT_LINK_TO_PROJECT_HERE_

git push -u origin main


问:
Cannot find control with unspecified name, dynamic formarrays
I have a list of strings called listcontrols, for every one of this string i need to make a formarray. I want to display this in my html and the label of this display should be the string that are in the listcontrols.

In my console.log I can see that the formArray is created and has the same spelling as the one i am using so this cant be the problem but my html is complaining:

"Cannot find control with unspecified name attribute"

I tried using [formArrayName] and also formArrayName without the brackets i also tried putting my value in strings or in {{ }} but nothing is working :s

```<code><div class="formgroup" *ngFor="let listValue of listControls; let i = index" [formArrayName]=listValue>
  <div [formGroupName]="i">
    <label>{{ listValue }}</label>
  </div>
</div>
</code>```

This is in my ts:

```<code>addList(){
  this.packageTypeForm.addControl(this.packageTypeForm.controls.list.value, this.formBuilder.array([]));
  this.listControls.push(this.packageTypeForm.controls.string.value);
  console.log(this.packageTypeForm.controls);
}
</code>```

答:
Found it, in my addList() i mistyped it should be
this.listControls.push(this.packageTypeForm.controls.string.value);</p>

Body:
I have a list of strings called listcontrols, for every one of this string i need to make a formarray. I want to display this in my html and the label of this display should be the string that are in the listcontrols.

In my console.log I can see that the formArray is created and has the same spelling as the one i am using so this cant be the problem but my html is complaining:

"Cannot find control with unspecified name attribute"

I tried using [formArrayName] and also formArrayName without the brackets i also tried putting my value in strings or in {{ }} but nothing is working :s

    {{ listValue }}

This is in my ts:

addList(){
  this.packageTypeForm.addControl(this.packageTypeForm.controls.list.value, this.formBuilder.array([]));
  this.listControls.push(this.packageTypeForm.controls.string.value);
  console.log(this.packageTypeForm.controls);
}


问:
How to set full Screen Mode of My App which is made in netbeans platform?
I m made Desktop App in netbeans platform in java.now wwhen i run my app it will open by default size of netbeans platform configuration.but i want full screen mode when i run or startup my app. so where and how to do that in my app?</p>

答:
If you are using Netbeans then after initcomponent() method you can use this code, it will help you out:

setExtendedState(MAXIMIZED_BOTH)
```


问:
Formatting Masscan Output
I have the following output output from Masscan's -oG option:

```<code># Masscan 1.0.6 scan initiated Mon May  6 08:45:19 2019
# Ports scanned: TCP(13107;1-13107) UDP(0;) SCTP(0;) PROTOCOLS(0;)
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//
</code>```

How can I manipulate this output using awk, cut, grep, sed, etc. to get the following format:

```<code>192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443
</code>```

答:
Comments in code:

```<code>#!/bin/bash

# create the input file:
cat <<EOF >file
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//
EOF

# extract fields 2 and 5
<file awk '{print $2,$5}' |
# remove all that /open/tcp//https... part
sed 's@/.*@@' |
# Now merging is the worst part...
# script from https://stackoverflow.com/questions/19823941/join-lines-with-the-same-value-in-the-first-column
# This outputs `field1 , field2, field3, field4`
awk -F' ' -v OFS=' ' '{x=$1;$1="";a[x]=a[x]","$0}END{for(x in a) print x,a[x]}' |
# subsitute `, ` for `,` and remove the only remaining first ` ,`
sed 's/, /,/g' | sed 's/ ,/ /'
</code>```

The script will output:

```<code>192.168.1.1 8000,80
192.168.1.2 3478,443
192.168.1.3 8000,80
192.168.1.4 443,80
</code>```

Is there a way to sort the ports in increasing manner?

Sure. Sort numerically using the second column (or using the first then second column) before awk-ing. The awk will keep the order.

```<code># extract fields 2 and 5
<file awk '{print $2,$5}' |
# remove all that /open/tcp//https... part
sed 's@/.*@@' |
# numeric sort using the second column (ie. port)
sort -t' ' -n -k2 |
# Now merging is the worst part...
# script from https://stackoverflow.com/questions/19823941/join-lines-with-the-same-value-in-the-first-column
# This outputs `field1 , field2, field3, field4`
awk -F' ' -v OFS=' ' '{x=$1;$1="";a[x]=a[x]","$0}END{for(x in a) print x,a[x]}' |
# subsitute `, ` for `,` and remove the only remaining first ` ,`
sed 's/, /,/g' | sed 's/ ,/ /'
</code>```

will output:

```<code>192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443
</code>```

Title: Formatting Masscan Output

Body:
I have the following output output from Masscan's -oG option:

# Masscan 1.0.6 scan initiated Mon May  6 08:45:19 2019
# Ports scanned: TCP(13107;1-13107) UDP(0;) SCTP(0;) PROTOCOLS(0;)
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//

How can I manipulate this output using awk, cut, grep, sed, etc. to get the following format:

192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443

Body:
Comments in code:

#!/bin/bash

# create the input file:
cat <<EOF >file
Host: 192.168.1.1 ()  Ports: 8000/open/tcp//unknown//
Host: 192.168.1.2 ()  Ports: 3478/open/tcp//unknown//
Host: 192.168.1.3 ()   Ports: 8000/open/tcp//unknown//
Host: 192.168.1.1 ()        Ports: 80/open/tcp//http//
Host: 192.168.1.2 ()        Ports: 443/open/tcp//https//
Host: 192.168.1.4 () Ports: 443/open/tcp//https//
Host: 192.168.1.3 () Ports: 80/open/tcp//http//
Host: 192.168.1.4 () Ports: 80/open/tcp//http//
EOF

# extract fields 2 and 5
<file awk '{print $2,$5}' |
# remove all that /open/tcp//https... part
sed 's@/.*@@' |
# Now merging is the worst part...
# script from https://stackoverflow.com/questions/19823941/join-lines-with-the-same-value-in-the-first-column
# This outputs `field1 , field2, field3, field4`
awk -F' ' -v OFS=' ' '{x=$1;$1="";a[x]=a[x]","$0}END{for(x in a) print x,a[x]}' |
# subsitute `, ` for `,` and remove the only remaining first ` ,`
sed 's/, /,/g' | sed 's/ ,/ /'

The script will output:

192.168.1.1 8000,80
192.168.1.2 3478,443
192.168.1.3 8000,80
192.168.1.4 443,80

Is there a way to sort the ports in increasing manner?

Sure. Sort numerically using the second column (or using the first then second column) before awk-ing. The awk will keep the order.

# extract fields 2 and 5
<file awk '{print $2,$5}' |
# remove all that /open/tcp//https... part
sed 's@/.*@@' |
# numeric sort using the second column (ie. port)
sort -t' ' -n -k2 |
# Now merging is the worst part...
# script from https://stackoverflow.com/questions/19823941/join-lines-with-the-same-value-in-the-first-column
# This outputs `field1 , field2, field3, field4`
awk -F' ' -v OFS=' ' '{x=$1;$1="";a[x]=a[x]","$0}END{for(x in a) print x,a[x]}' |
# subsitute `, ` for `,` and remove the only remaining first ` ,`
sed 's/, /,/g' | sed 's/ ,/ /'

will output:

192.168.1.1 80,8000
192.168.1.2 443,3478
192.168.1.3 80,8000
192.168.1.4 80,443


答:
All runtime if branches must be compilable even if not taken. If we call fun() with V == double then returning an std::string makes no sense and causes the error (even if that branch would never be taken, the compiler can't know that for certain).

Instead, just return it right away through V:

```<code>template <typename V> V fun() {
    if (std::holds_alternative<V>(cont))
        return std::get<V>(cont);
    return {}; // return default constructed V. You could throw an exception here instead etc.
}
</code>```

Title: How can I use type-safe unions (variants) inside a class with template functions?

Body:
All runtime if branches must be compilable even if not taken. If we call fun() with V == double then returning an std::string makes no sense and causes the error (even if that branch would never be taken, the compiler can't know that for certain).

Instead, just return it right away through V:

template <typename V> V fun() {
    if (std::holds_alternative<V>(cont))
        return std::get<V>(cont);
    return {}; // return default constructed V. You could throw an exception here instead etc.
}


问:
Need to apply class based on the condition in the header of the table
I need to implement a specific class on the td based on if else condition. If you see my code I am looping through th and td elements.  I need to either blank the text in the th or set the color to white if the th class name equals Legal Class ID so that header text is not visible. I have created a class called cellbgcolor. I need to apply only if the header text is  Legal Class ID for all others it should apply class tableItem bold. How do I do that. I have shared the html and jsfiddle below

html

```<code>  <style>
      .cellbgcolor {
        color: white;
    }
   </style>

    <div *ngIf="LegalFundClasses && LegalFundClasses.LegalFundClassDetailsViewModel && ColumnNames">
         <table class="fundClassesTable table-striped">
          <tr *ngFor="let c of ColumnNames">
            <th class="tableItem bold">{{ c }}</th>
            <ng-container *ngFor="let f of LegalFundClasses.LegalFundClassDetailsViewModel; let i=index">
              <td class="tableItem" *ngIf="c == ColumnNames[0]">{{f.Description}}</td>
              <td class="tableItem" *ngIf="c == ColumnNames[1]">{{f.AuditSummary}}</td>
              <td class="tableItem" *ngIf="c == ColumnNames[2]">{{f.Id}}</td
            </ng-container>
          </tr>
        </table>
      </div>

 Component

  public ColumnNames: string[] = ['Legal Class Name',
                                    'Last Edited',
                                    'Legal Class ID'
                                  ];
</code>```

Here is the JSFiddle

https://jsfiddle.net/zyk9xhd1/2/

答:
Use ngClass

```<code>`<th [ngClass]="c == ColumnNames[2] ? 'cellbgcolor' : 'tableItem bold'">{{ c }}</th>`
</code>```

Updated Fiddle

Body:
I need to implement a specific class on the td based on if else condition. If you see my code I am looping through th and td elements.  I need to either blank the text in the th or set the color to white if the th class name equals Legal Class ID so that header text is not visible. I have created a class called cellbgcolor. I need to apply only if the header text is  Legal Class ID for all others it should apply class tableItem bold. How do I do that. I have shared the html and jsfiddle below

html

            {{ c }}
            <ng-container *ngFor="let f of LegalFundClasses.LegalFundClassDetailsViewModel; let i=index">
              {{f.Description}}
              {{f.AuditSummary}}
              {{f.Id}}</td
            </ng-container>

 Component

  public ColumnNames: string[] = ['Legal Class Name',
                                    'Last Edited',
                                    'Legal Class ID'
                                  ];

Here is the JSFiddle

https://jsfiddle.net/zyk9xhd1/2/

Body:
Use ngClass

`<th [ngClass]="c == ColumnNames[2] ? 'cellbgcolor' : 'tableItem bold'">{{ c }}</th>`

Updated Fiddle