问:
Keras: Making a neural network to find a number's modulus
I'm an experienced Python developer, but a complete newbie in machine learning. This is my first attempt to use Keras. Can you tell what I'm doing wrong?

I'm trying to make a neural network that takes a number in binary form, and outputs its modulo when dividing by 7. (My goal was to take a very simple task just to see that everything works.)

In the code below I define the network and I train it on 10,000 random numbers. Then I test it on 500 random numbers.

For some reason the accuracy that I get is around 1/7, which is the accuracy you'd expect from a completely random algorithm, i.e. my neural network isn't doing anything.

Can anyone help me figure out what's wrong?

```<code>import keras.models
import numpy as np
from python_toolbox import random_tools

RADIX = 7

def _get_number(vector):
    return sum(x * 2 ** i for i, x in enumerate(vector))

def _get_mod_result(vector):
    return _get_number(vector) % RADIX

def _number_to_vector(number):
    binary_string = bin(number)[2:]
    if len(binary_string) > 20:
        raise NotImplementedError
    bits = (((0,) * (20 - len(binary_string))) +
            tuple(map(int, binary_string)))[::-1]
    assert len(bits) == 20
    return np.c_[bits]

def get_mod_result_vector(vector):
    return _number_to_vector(_get_mod_result(vector))

def main():
    model = keras.models.Sequential(
        (
            keras.layers.Dense(
                units=20, activation='relu', input_dim=20
            ),
            keras.layers.Dense(
                units=20, activation='relu'
            ),
            keras.layers.Dense(
                units=20, activation='softmax'
            )
        )
    )
    model.compile(optimizer='sgd',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    data = np.random.randint(2, size=(10000, 20))
    labels = np.vstack(map(get_mod_result_vector, data))

    model.fit(data, labels, epochs=10, batch_size=50)
    def predict(number):
        foo = model.predict(_number_to_vector(number))
        return _get_number(tuple(map(round, foo[0])))
    def is_correct_for_number(x):
        return bool(predict(x) == x % RADIX)
    predict(7)
    sample = random_tools.shuffled(range(2 ** 20))[:500]
    print('Total accuracy:')
    print(sum(map(is_correct_for_number, sample)) / len(sample))
    print(f'(Accuracy of random algorithm is {1/RADIX:.2f}')

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

答:
This achieves an accuracy of 99.74% and a validation accuracy of 99.69%.

```<code>import tensorflow as tf, numpy as np

def int2bits(i,fill=20):
    return list(map(int,bin(i)[2:].zfill(fill)))

def bits2int(b):
    return sum(i*2**n for n,i in enumerate(reversed(b)))

# Data.
I = np.random.randint(0,2**20,size=(250_000,))
X = np.array(list(map(int2bits,I)))
Y = np.array([int2bits(2**i,7) for i in I % 7])

# Test Data.
It = np.random.randint(0,2**20,size=(10_000,))
Xt = np.array(list(map(int2bits,It)))
Yt = np.array([int2bits(2**i,7) for i in It % 7])

# Model.
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(1000,'relu'),
    tf.keras.layers.Dense(7,'softmax'),
])
model.compile('adam','categorical_crossentropy',['accuracy'])

# Train.
model.fit(X,Y,10_000,100,validation_data=(Xt,Yt))
</code>```

Some take-aways:

1) You had way too little data. You were uniformly sampling points from 0 to 2**20, but only sampled 10,000, which is only about 1% of the possible vectors that the model is suppose to learn about. The point is that a lot of components (in the binary representation) would be mostly fixed at zero or one without any opportunity to learn how they function in the overall data or how they interact with other components.

2) You needed an embedding layer, namely extend the space into some massive higher dimension, so the neurons can move around more easily. This allows the learning to shuffle things better hopefully finding the algorithm your looking for. A single Dense(1000) seems to work.

3) Ran batches of 10_000 (just so I maximize my CPU usage). Ran 100 epochs. Included my validation_data in the training so I could see how the validation set performs at each epoch (including this doesn't effect the training, just makes it easier to see if the model is doing well, while training).

Thanks. :-)

Body:
I'm an experienced Python developer, but a complete newbie in machine learning. This is my first attempt to use Keras. Can you tell what I'm doing wrong?

I'm trying to make a neural network that takes a number in binary form, and outputs its modulo when dividing by 7. (My goal was to take a very simple task just to see that everything works.)

In the code below I define the network and I train it on 10,000 random numbers. Then I test it on 500 random numbers.

For some reason the accuracy that I get is around 1/7, which is the accuracy you'd expect from a completely random algorithm, i.e. my neural network isn't doing anything.

Can anyone help me figure out what's wrong?

import keras.models
import numpy as np
from python_toolbox import random_tools

RADIX = 7

def _get_number(vector):
    return sum(x * 2 ** i for i, x in enumerate(vector))

def _get_mod_result(vector):
    return _get_number(vector) % RADIX

def _number_to_vector(number):
    binary_string = bin(number)[2:]
    if len(binary_string) > 20:
        raise NotImplementedError
    bits = (((0,) * (20 - len(binary_string))) +
            tuple(map(int, binary_string)))[::-1]
    assert len(bits) == 20
    return np.c_[bits]

def get_mod_result_vector(vector):
    return _number_to_vector(_get_mod_result(vector))

def main():
    model = keras.models.Sequential(
        (
            keras.layers.Dense(
                units=20, activation='relu', input_dim=20
            ),
            keras.layers.Dense(
                units=20, activation='relu'
            ),
            keras.layers.Dense(
                units=20, activation='softmax'
            )
        )
    )
    model.compile(optimizer='sgd',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    data = np.random.randint(2, size=(10000, 20))
    labels = np.vstack(map(get_mod_result_vector, data))

    model.fit(data, labels, epochs=10, batch_size=50)
    def predict(number):
        foo = model.predict(_number_to_vector(number))
        return _get_number(tuple(map(round, foo[0])))
    def is_correct_for_number(x):
        return bool(predict(x) == x % RADIX)
    predict(7)
    sample = random_tools.shuffled(range(2 ** 20))[:500]
    print('Total accuracy:')
    print(sum(map(is_correct_for_number, sample)) / len(sample))
    print(f'(Accuracy of random algorithm is {1/RADIX:.2f}')

if __name__ == '__main__':
    main()

Body:
This achieves an accuracy of 99.74% and a validation accuracy of 99.69%.

import tensorflow as tf, numpy as np

def int2bits(i,fill=20):
    return list(map(int,bin(i)[2:].zfill(fill)))

def bits2int(b):
    return sum(i*2**n for n,i in enumerate(reversed(b)))

# Data.
I = np.random.randint(0,2**20,size=(250_000,))
X = np.array(list(map(int2bits,I)))
Y = np.array([int2bits(2**i,7) for i in I % 7])

# Test Data.
It = np.random.randint(0,2**20,size=(10_000,))
Xt = np.array(list(map(int2bits,It)))
Yt = np.array([int2bits(2**i,7) for i in It % 7])

# Model.
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(1000,'relu'),
    tf.keras.layers.Dense(7,'softmax'),
])
model.compile('adam','categorical_crossentropy',['accuracy'])

# Train.
model.fit(X,Y,10_000,100,validation_data=(Xt,Yt))

Some take-aways:

1) You had way too little data. You were uniformly sampling points from 0 to 2**20, but only sampled 10,000, which is only about 1% of the possible vectors that the model is suppose to learn about. The point is that a lot of components (in the binary representation) would be mostly fixed at zero or one without any opportunity to learn how they function in the overall data or how they interact with other components.

2) You needed an embedding layer, namely extend the space into some massive higher dimension, so the neurons can move around more easily. This allows the learning to shuffle things better hopefully finding the algorithm your looking for. A single Dense(1000) seems to work.

3) Ran batches of 10_000 (just so I maximize my CPU usage). Ran 100 epochs. Included my validation_data in the training so I could see how the validation set performs at each epoch (including this doesn't effect the training, just makes it easier to see if the model is doing well, while training).

Thanks. :-)


来源: stackexchange

问:
PHP: different elements between two arrays
I have two different arrays like this

```<code> $array1 = [1, 2, 8, 10];
 $array2 = [2, 4, 6, 8, 10, 15, 1];
</code>```

I want to get the common elements and uncommon elements between them.
I almost figured out how to get the common ones as the code below but I can't get uncommon elements.

```<code>for($x = 0; $x < count($array1); $x++) {

    for($z = 0; $z < count($array2); $z++) {
            if ( $array1[$x] == $array2[$z] ) {

                $array3 = $array1[$x];
                print_r($array3);

            } elseif ($array1[$x] !== $array2[$z]) {
                // code...
            }

        }
    }
</code>```

How to get those uncommon or different elements between the two arrays without using a built-in PHP method then output them in a new array.

答:
You can get the uncommon elements by using in_array() function

```<code><?php
 $array1 = [1, 2, 8, 10];
 $array2 = [2, 4, 6, 8, 10, 15, 1];

  $result = [];
 for($i = 0;$i < sizeof($array2);$i++){
 if(!in_array($array2[$i],$array1)){
    $result[] =  $array2[$i];
  }
 }
?>
</code>```

Output

```<code>Array
(
    [0] => 4
    [1] => 6
    [2] => 15
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two different arrays like this

 $array1 = [1, 2, 8, 10];
 $array2 = [2, 4, 6, 8, 10, 15, 1];

I want to get the common elements and uncommon elements between them.
I almost figured out how to get the common ones as the code below but I can't get uncommon elements.

for($x = 0; $x < count($array1); $x++) {

    for($z = 0; $z < count($array2); $z++) {
            if ( $array1[$x] == $array2[$z] ) {

                $array3 = $array1[$x];
                print_r($array3);

            } elseif ($array1[$x] !== $array2[$z]) {
                // code...
            }

        }
    }

How to get those uncommon or different elements between the two arrays without using a built-in PHP method then output them in a new array.

Body:
You can get the uncommon elements by using in_array() function

<?php
 $array1 = [1, 2, 8, 10];
 $array2 = [2, 4, 6, 8, 10, 15, 1];

  $result = [];
 for($i = 0;$i < sizeof($array2);$i++){
 if(!in_array($array2[$i],$array1)){
    $result[] =  $array2[$i];
  }
 }
?>

Output

Array
(
    [0] => 4
    [1] => 6
    [2] => 15
)


问:
How to embed a script tag into Angular component
I've got an Angular/Typescript website. I need to embed a third party script. The script generates a table.

How can I display that table inside home.component.html. Not at the start or at the beginning, within. Like so.

I've been able to get the script embedded but it doesn't look like the script is rendering so it just displays it in the source but doesn't render the table.

Update

The table can now rendered but only outside of app-root. It should be inside of home.component.html. Source Image

home.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { DOCUMENT } from '@angular/common'

declare var myExtObject: any;

@Component({
  selector: 'app-careers',
  templateUrl: './careers.component.html',
  styleUrls: ['./careers.component.scss']
})

export class CareersComponent implements OnInit {
  private iife: any

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.iife = myExtObject()
  }

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

<p><strong>home.component.html</strong></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><div id="BambooHR">
    <script src="https://xxxxxxx.xxx.com" type="text/javascript"></script>
    <div></div>
</div></code>```

The code behind the script is found below. I have that in an external.js file.

var myExtObject = function() {

 //add css file to dom so IE8 recognizes it
 document.write('<link href="https://xxx.css" rel="stylesheet" />');

 var divId="BambooHR-ATS";
 var el=document.getElementById(divId);
 if(!el) {
  document.write("

");
 }

 var xmlhttp;
 var ieFlag = 0;
 if (('XDomainRequest' in window && window.XDomainRequest !== null) && document.documentMode < 10) {
  xmlhttp=new XDomainRequest();
  ieFlag = 1;
 } else if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
 } else {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }

 var embedUrl = "https://xxx.php";

 var departmentId = "0";

 if (departmentId) {
  embedUrl += '?departmentId=' + encodeURIComponent(departmentId);
 }

 document.addEventListener('readystatechange', function(event) {
  if (event.target.readyState === "complete") {
   if (ieFlag == 1) { //needed for IE9 CORS
    xmlhttp.onload = loadd;
    xmlhttp.open("GET",embedUrl);
    xmlhttp.send();

   } else {
    xmlhttp.onreadystatechange=function() {
     if(xmlhttp.readyState==4 && xmlhttp.status==200) {

      var content = xmlhttp.responseText;
      var footerId="BambooHR-Footer";
      var fel=document.getElementById(footerId);

      el=document.getElementById(divId);

      if(el && !fel) {
       content += "

";
      }

      if(el) el.innerHTML=content;
     }
    }

    xmlhttp.open("GET",embedUrl,true);
    xmlhttp.send();
   }
  }
 });

 function loadd() { //needed for IE9 CORS
  var content = xmlhttp.responseText;
  var footerId="BambooHR-Footer";
  var fel=document.getElementById(footerId);

  el=document.getElementById(divId);

  if(el && !fel) {
   content += "
Powered by
";
  }
  el.innerHTML=content;
 }
};```

Body:
I've got an Angular/Typescript website. I need to embed a third party script. The script generates a table.

How can I display that table inside home.component.html. Not at the start or at the beginning, within. Like so.

I've been able to get the script embedded but it doesn't look like the script is rendering so it just displays it in the source but doesn't render the table.

Update

The table can now rendered but only outside of app-root. It should be inside of home.component.html. Source Image

home.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { DOCUMENT } from '@angular/common'

declare var myExtObject: any;

@Component({
  selector: 'app-careers',
  templateUrl: './careers.component.html',
  styleUrls: ['./careers.component.scss']
})

export class CareersComponent implements OnInit {
  private iife: any

  ngOnInit() {
  }

  ngAfterViewInit() {
    this.iife = myExtObject()
  }

}

home.component.html

The code behind the script is found below. I have that in an external.js file.

var myExtObject = function() {

 //add css file to dom so IE8 recognizes it
 document.write('<link href="https://xxx.css" rel="stylesheet" />');

 var divId="BambooHR-ATS";
 var el=document.getElementById(divId);
 if(!el) {
  document.write("

");
 }

 var xmlhttp;
 var ieFlag = 0;
 if (('XDomainRequest' in window && window.XDomainRequest !== null) && document.documentMode < 10) {
  xmlhttp=new XDomainRequest();
  ieFlag = 1;
 } else if (window.XMLHttpRequest) {
  xmlhttp=new XMLHttpRequest();
 } else {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }

 var embedUrl = "https://xxx.php";

 var departmentId = "0";

 if (departmentId) {
  embedUrl += '?departmentId=' + encodeURIComponent(departmentId);
 }

 document.addEventListener('readystatechange', function(event) {
  if (event.target.readyState === "complete") {
   if (ieFlag == 1) { //needed for IE9 CORS
    xmlhttp.onload = loadd;
    xmlhttp.open("GET",embedUrl);
    xmlhttp.send();

   } else {
    xmlhttp.onreadystatechange=function() {
     if(xmlhttp.readyState==4 && xmlhttp.status==200) {

      var content = xmlhttp.responseText;
      var footerId="BambooHR-Footer";
      var fel=document.getElementById(footerId);

      el=document.getElementById(divId);

      if(el && !fel) {
       content += "

";
      }

      if(el) el.innerHTML=content;
     }
    }

    xmlhttp.open("GET",embedUrl,true);
    xmlhttp.send();
   }
  }
 });

 function loadd() { //needed for IE9 CORS
  var content = xmlhttp.responseText;
  var footerId="BambooHR-Footer";
  var fel=document.getElementById(footerId);

  el=document.getElementById(divId);

  if(el && !fel) {
   content += "
Powered by
";
  }
  el.innerHTML=content;
 }
};

Body:
All scripts are executed when the page is loaded, <script> tag added to dom after page is loaded does not get executed

As a result of that, embedding a script tag will not load the content of the file seams angular does not reload the page.

A solution is to make the component implement AfterInit interface and import the script dynamically in the ngAfterInit method like this

ngAfterInit() {
   import('./myfile.js')
  }

Assuming that the script to be loaded is myfile.js and is is the same directiory


问:
What is \363\353\377\377\377\177?

(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```

It doesn't look like ascii nor multibyte,what's that?

答: These are octal character escapes. They are usually used to insert bytes into a string that don't have a meaning as text or need to have a certain binary value. \377 for instance is the hexadecimal value ff or decimal 255 which would be this ÿ in ASCII but most likely has a very different meaning in this context.

Title: What is \363\353\377\377\377\177?

Body:
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"

It doesn't look like ascii nor multibyte,what's that?

ContentLicense: CC BY-SA 3.0


问:
How to create an unorganised grid view in React Native
I am working on a React Native project in which I need to create an unorganized grid view. Please refer to the image.

<img src="https://i.stack.imgur.com/6vGKW.png" alt="the multi selection grid view ">

I have no idea how to achieve this type of view dynamically with the below JSON data.

```<code>categories: [
    {
        id: 1,
        title: 'Tolerance'
    },
    {
        id: 2,
        title: 'Equality'
    },
    {
        id: 3,
        title: 'Empowerment'
    },
    {
        id: 4,
        title: 'LGBTQ+'
    },
    {
        id: 6,
        title: 'Equal opportunity'
    },
    {
        id: 5,
        title: 'Success stories'
    },
    {
        id: 7,
        title: 'News'
    },
    {
        id: 8,
        title: 'Inclusivity'
    },
    {
        id: 9,
        title: 'People'
    },
    {
        id: 18,
        title: 'Jobs'
    },
    {
        id: 10,
        title: 'Consciousness'
    },
    {
        id: 11,
        title: 'Responsibility'
    },
    {
        id: 12,
        title: 'Diversity'
    },
    {
        id: 13,
        title: 'Networking'
    },
    {
        id: 14,
        title: 'Lifestyle'
    },
    {
        id: 15,
        title: 'Pride'
    },
    {
        id: 16,
        title: 'Economy'
    },
    {
        id: 17,
        title: 'Climate'
    }
]
</code>```

Right now I am using separate TextView with the separate clicks manually. I need to make it dynamically as I am getting this list from the server.

My concern is that, is it possible to make this type of view or do I need to continue working on the approach on which I am working right now?

答:
What you could do is get the data from the server and store it in Redux.
After that get your data into the component, map it and create a layout with Flexbox.</p>

Body:
I am working on a React Native project in which I need to create an unorganized grid view. Please refer to the image.

<img src="https://i.stack.imgur.com/6vGKW.png" alt="the multi selection grid view ">

I have no idea how to achieve this type of view dynamically with the below JSON data.

categories: [
    {
        id: 1,
        title: 'Tolerance'
    },
    {
        id: 2,
        title: 'Equality'
    },
    {
        id: 3,
        title: 'Empowerment'
    },
    {
        id: 4,
        title: 'LGBTQ+'
    },
    {
        id: 6,
        title: 'Equal opportunity'
    },
    {
        id: 5,
        title: 'Success stories'
    },
    {
        id: 7,
        title: 'News'
    },
    {
        id: 8,
        title: 'Inclusivity'
    },
    {
        id: 9,
        title: 'People'
    },
    {
        id: 18,
        title: 'Jobs'
    },
    {
        id: 10,
        title: 'Consciousness'
    },
    {
        id: 11,
        title: 'Responsibility'
    },
    {
        id: 12,
        title: 'Diversity'
    },
    {
        id: 13,
        title: 'Networking'
    },
    {
        id: 14,
        title: 'Lifestyle'
    },
    {
        id: 15,
        title: 'Pride'
    },
    {
        id: 16,
        title: 'Economy'
    },
    {
        id: 17,
        title: 'Climate'
    }
]

Right now I am using separate TextView with the separate clicks manually. I need to make it dynamically as I am getting this list from the server.

My concern is that, is it possible to make this type of view or do I need to continue working on the approach on which I am working right now?


问:
Select all / Unselect all in Bootstrap Select plugin
```<code><select id="divRatings" class="selectpicker" multiple title='Choose one of the following...' data-size="5" data-selected-text-format="count>2">
    <option value="All" selected="selected">All Ratings</option>
    <option value="EC">EC (Early Childhood)</option>
    <option value="E">E (Everyone)</option>
    <option value="E10+">E10+ (Everyone 10+)</option>
    <option value="T">T (Teen)</option>
    <option value="M">M (Mature)</option>
    <option value="AO">AO (Adults Only)</option>
</select>
</code>```

In html above there are option with value All. I want to select all items if that option is selected and unselect all if i unselect this option.

I think it will be simple to do, but i can't get why nothing happens on $('#divRatings').change(function(){//some logic});

My function to select/ unselect items:

```<code>function toggleSelectAll(control) {
    if (control.val().indexOf("All,") > -1) {
        control.selectpicker('selectAll');
    } else {
        control.selectpicker('deselectAll');
    }
}
</code>```

JSFiddle example

答:
It has been answered, but I found a better way of doing (link to documentation).

Just add data-actions-box="true" as attributes of the select tag.

Eg.

Select/deselect all
<select class="selectpicker form-control" data-style="btn-outline-warning" multiple data-actions-box="true">
    <optgroup label="Condiments">
        <option>Mustard</option>
        <option>Ketchup</option>
        <option>Relish</option>
    </optgroup>
    <optgroup label="Breads">
        <option>Plain</option>
        <option>Steamed</option>
        <option>Toasted</option>
    </optgroup>
</select>

```

Body:
<select id="divRatings" class="selectpicker" multiple title='Choose one of the following...' data-size="5" data-selected-text-format="count>2">
    <option value="All" selected="selected">All Ratings</option>
    <option value="EC">EC (Early Childhood)</option>
    <option value="E">E (Everyone)</option>
    <option value="E10+">E10+ (Everyone 10+)</option>
    <option value="T">T (Teen)</option>
    <option value="M">M (Mature)</option>
    <option value="AO">AO (Adults Only)</option>
</select>

In html above there are option with value All. I want to select all items if that option is selected and unselect all if i unselect this option.

I think it will be simple to do, but i can't get why nothing happens on $('#divRatings').change(function(){//some logic});

My function to select/ unselect items:

function toggleSelectAll(control) {
    if (control.val().indexOf("All,") > -1) {
        control.selectpicker('selectAll');
    } else {
        control.selectpicker('deselectAll');
    }
}

JSFiddle example

Body:
It has been answered, but I found a better way of doing (link to documentation).

Just add data-actions-box="true" as attributes of the select tag.

Eg.

<label>Select/deselect all</label>
<select class="selectpicker form-control" data-style="btn-outline-warning" multiple data-actions-box="true">
    <optgroup label="Condiments">
        <option>Mustard</option>
        <option>Ketchup</option>
        <option>Relish</option>
    </optgroup>
    <optgroup label="Breads">
        <option>Plain</option>
        <option>Steamed</option>
        <option>Toasted</option>
    </optgroup>
</select>


问:
Mapping nested list
I have a object with list of nested object

```<code>@Getter
@Setter
@NoArgsConstructor
public class Notification {
    private Long id
    private Long statusId;
    private List <External> external;
}

@Getter
@Setter
@NoArgsConstructor
public class External{
    private Long externalId;
    private  LocalDate date;
}
</code>```

Dto

```<code>@Getter
@Setter
@NoArgsConstructor
public class NotificationPayload {
    private Long id;
    private Long statusId;
    private List <ExternalReferencePayload> external;
}

@Getter
@Setter
@NoArgsConstructor
public class ExternalReferencePayload {
    private Long externalReferenceId;
}
</code>```

Mapper

```<code>@Mapper(componentModel = "spring")
public interface NotificationMapper{

  public Notification dtoToNotification(NotificationPayload  payload);
}
</code>```

I search the way to map the nested list

答:
In order to perform custom mapping for certain elements it is only needed to define a mapping method and MapStruct will take care of the rest. In your example:

```<code>@Mapper(componentModel = "spring")
public interface NotificationMapper{

  public Notification dtoToNotification(NotificationPayload  payload);

  @Mapping(target = "externalId", source = "externalReferenceId")
  public External dtoExternal(ExternalReferencePayload payload);
}
</code>```

With this the nested list will use the dtoExternal mapping method to perform the mapping. With @Mapping you control how the mapping between externalId and externalReferenceId should be done

Title: Mapping nested list

Body:
I have a object with list of nested object

@Getter
@Setter
@NoArgsConstructor
public class Notification {
    private Long id
    private Long statusId;
    private List <External> external;
}

@Getter
@Setter
@NoArgsConstructor
public class External{
    private Long externalId;
    private  LocalDate date;
}

Dto

@Getter
@Setter
@NoArgsConstructor
public class NotificationPayload {
    private Long id;
    private Long statusId;
    private List <ExternalReferencePayload> external;
}

@Getter
@Setter
@NoArgsConstructor
public class ExternalReferencePayload {
    private Long externalReferenceId;
}

Mapper

@Mapper(componentModel = "spring")
public interface NotificationMapper{

  public Notification dtoToNotification(NotificationPayload  payload);
}

I search the way to map the nested list

Body:
In order to perform custom mapping for certain elements it is only needed to define a mapping method and MapStruct will take care of the rest. In your example:

@Mapper(componentModel = "spring")
public interface NotificationMapper{

  public Notification dtoToNotification(NotificationPayload  payload);

  @Mapping(target = "externalId", source = "externalReferenceId")
  public External dtoExternal(ExternalReferencePayload payload);
}

With this the nested list will use the dtoExternal mapping method to perform the mapping. With @Mapping you control how the mapping between externalId and externalReferenceId should be done


问:
asp:UpdatePanel / Custom Control / RegisterClientScriptResource
I have built a custom control that has a small amount of JavaScript. The JS is maintained as an embeded resource. When my control is rendered, I added it to the page as follows:

```<code>Page.ClientScript.RegisterClientScriptResource(
    GetType(), "Resources.MyControl.js");
</code>```

The control works just fine but when it is rendered inside of an update panel, I am guessing that the JS resource is being added to the page object which is not being sent back to the client (only the contents inside the of the update panel make it back to the client.)

I could add the JS to my application library which fixes the issue as it is loaded at the begining of the initial page request. Any other fixes? Any way to use RegisterClientScriptResource from within an update panel?

答:
You have to register your script with the page ScriptManager to work within an update panel.

Luckily, you don't need to find the instance of the scriptmanager on the page, because there is a handy static class, simply add:

```<code>  ScriptManager.RegisterClientScriptResource(this.GetType(), "Resources.MyControl.js");
</code>```

To your control and you are set.

OwnerDisplayName: Andrew Robinson

ContentLicense: CC BY-SA 2.5

Body:
I have built a custom control that has a small amount of JavaScript. The JS is maintained as an embeded resource. When my control is rendered, I added it to the page as follows:

Page.ClientScript.RegisterClientScriptResource(
    GetType(), "Resources.MyControl.js");

The control works just fine but when it is rendered inside of an update panel, I am guessing that the JS resource is being added to the page object which is not being sent back to the client (only the contents inside the of the update panel make it back to the client.)

I could add the JS to my application library which fixes the issue as it is loaded at the begining of the initial page request. Any other fixes? Any way to use RegisterClientScriptResource from within an update panel?

LastEditorDisplayName: Andrew Robinson

Body:
You have to register your script with the page ScriptManager to work within an update panel.

Luckily, you don't need to find the instance of the scriptmanager on the page, because there is a handy static class, simply add:

  ScriptManager.RegisterClientScriptResource(this.GetType(), "Resources.MyControl.js");

To your control and you are set.

OwnerDisplayName: FlySwat


问:
Hive select a column based on a second column where the second column values are different
Let's say we have a hive table with 4 different columns and I want to select from it for those values in the first column while make sure the values are different in the second column. Any help or guidance to how to do it?

```<code>  ---------------------
  | C1 | C2 | C3 | C4 |
  ---------------------
  | a     1    g.   h |
  | a     1    f.   l |
  | a     3    t.   p |
  | b     1    r.   o |
  | b     1    e.   q |
  | c     1    w.   w |
  | c     2    z.   p |
   -------------------
</code>```

In the above example, I want to hive select return a and c because their values at C2 are different.

答:
I think this should work for you, it will show C1 vales where there is only one match to the C1 + C2 combination

```<code>select distinct C1 from table
group by C1, C2
having count(*) = 1;
</code>```

Very few lines so you should be able to figure out what it does.

Body:
Let's say we have a hive table with 4 different columns and I want to select from it for those values in the first column while make sure the values are different in the second column. Any help or guidance to how to do it?

  ---------------------
  | C1 | C2 | C3 | C4 |
  ---------------------
  | a     1    g.   h |
  | a     1    f.   l |
  | a     3    t.   p |
  | b     1    r.   o |
  | b     1    e.   q |
  | c     1    w.   w |
  | c     2    z.   p |
   -------------------

In the above example, I want to hive select return a and c because their values at C2 are different.

Body:
I think this should work for you, it will show C1 vales where there is only one match to the C1 + C2 combination

select distinct C1 from table
group by C1, C2
having count(*) = 1;

Very few lines so you should be able to figure out what it does.


问:
Why does this pandas calculation return an error
I started learning Python some few hours ago and run into this problem
The script below runs correctly and expected output is generated

```<code>import pandas as pd
brics = pd.read_csv('G:/brics.csv', index_col = 0)
brics
</code>```

However when I use this code (which is intended to calculate the density)

```<code>brics["density"] = brics["population"] / brics["area"] * 1000000
</code>```

I get an error message below:

```<code>d:\python\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2645             try:
-> 2646                 return self._engine.get_loc(key)
   2647             except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'population'
During handling of the above exception, another exception occurred:
KeyError                                  Traceback (most recent call last)
<ipython-input-7-7f590cb7a5d0> in <module>
      1 import pandas as pd
      2 brics = pd.read_csv("G:/brics.csv", index_col = 0)
----> 3 brics["density"] = brics["population"] / brics["area"] * 1000000
      4 brics
d:\python\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2798             if self.columns.nlevels > 1:
   2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
   2801             if is_integer(indexer):
   2802                 indexer = [indexer]
d:\python\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         if indexer.ndim > 1 or indexer.size > 1:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'population'
</code>```

答:
Try something like this

```<code>brics.info()
</code>```

and confirm the column exists, because pandas doesn't think it does. Which likely means it's labeled something other than what you think it is.

Body:
I started learning Python some few hours ago and run into this problem
The script below runs correctly and expected output is generated

import pandas as pd
brics = pd.read_csv('G:/brics.csv', index_col = 0)
brics

However when I use this code (which is intended to calculate the density)

brics["density"] = brics["population"] / brics["area"] * 1000000

I get an error message below:

d:\python\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2645             try:
-> 2646                 return self._engine.get_loc(key)
   2647             except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'population'
During handling of the above exception, another exception occurred:
KeyError                                  Traceback (most recent call last)
<ipython-input-7-7f590cb7a5d0> in <module>
      1 import pandas as pd
      2 brics = pd.read_csv("G:/brics.csv", index_col = 0)
----> 3 brics["density"] = brics["population"] / brics["area"] * 1000000
      4 brics
d:\python\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   2798             if self.columns.nlevels > 1:
   2799                 return self._getitem_multilevel(key)
-> 2800             indexer = self.columns.get_loc(key)
   2801             if is_integer(indexer):
   2802                 indexer = [indexer]
d:\python\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
   2646                 return self._engine.get_loc(key)
   2647             except KeyError:
-> 2648                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2649         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2650         if indexer.ndim > 1 or indexer.size > 1:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'population'

Body:
Try something like this

brics.info()

and confirm the column exists, because pandas doesn't think it does. Which likely means it's labeled something other than what you think it is.


问:
How do I split text file without delimiter into a list of dictionaries in python3?
I have a text file that has data in the following shape:

```<code>{"id": 1, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}{"id": 2, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}
</code>```

There aren't any \n delimiters or , delimiters that I can use here. I'd like to parse this into a list of dictionaries in order to load the data into a dataframe.

I've tried parsing this using .split() and list comprehension doing something like this:

```<code>lst = [x + '}' for x in data.split('}') if x != '']

</code>```

But this obviously breaks for records that have nested objects.

I also tried doing this with regex but I'm struggling to figure out the appropriate way.  This is what I have so far:

```<code>re.split('(\{(.*)\})', data)
</code>```

Per the suggestions below, I also attempted making use of the json library.

```<code>with open('path/to/file', 'r') as f:
    res = json.load(f)
</code>```

However, this resulted in an error with the following message: JSONDecodeError: Extra data. I believe this is due to the fact that there are multiple valid jsons in this file.

I wanted to use the json.load() command with a for loop, but then I ran into trouble figuring out how to properly split the file contents.

Does anyone have a suggestion for how to approach this kind of problem?

答:
Your data sort of looks like JSON, but with single instead of double quotes.

If that is the case, I would first suggest changing your data (if possible) to just use valid json, and then you can easily do:

myfile.json:

```<code>{ "foo": 42 }
</code>```

import json

with open('myfile.json') as f:
  obj = json.load(f)

print(obj) # {'foo': 42}
```

Then obj is a valid python dictionary you can use as normal.

If you can't use double-quoted JSON, you could possibly refer to this question about parsing single-quoted JSON.

Body:
I have a text file that has data in the following shape:

{"id": 1, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}{"id": 2, {"device_data": 123}, "created_at": "2020-04-03"}{"id": 2, {"device_data": 123}, "created_at": '2020-04-03'}

There aren't any \n delimiters or , delimiters that I can use here. I'd like to parse this into a list of dictionaries in order to load the data into a dataframe.

I've tried parsing this using .split() and list comprehension doing something like this:

lst = [x + '}' for x in data.split('}') if x != '']

But this obviously breaks for records that have nested objects.

I also tried doing this with regex but I'm struggling to figure out the appropriate way.  This is what I have so far:

re.split('(\{(.*)\})', data)

Per the suggestions below, I also attempted making use of the json library.

with open('path/to/file', 'r') as f:
    res = json.load(f)

However, this resulted in an error with the following message: JSONDecodeError: Extra data. I believe this is due to the fact that there are multiple valid jsons in this file.

I wanted to use the json.load() command with a for loop, but then I ran into trouble figuring out how to properly split the file contents.

Does anyone have a suggestion for how to approach this kind of problem?

Body:
Your data sort of looks like JSON, but with single instead of double quotes.

If that is the case, I would first suggest changing your data (if possible) to just use valid json, and then you can easily do:

myfile.json:

{ "foo": 42 }

import json

with open('myfile.json') as f:
  obj = json.load(f)

print(obj) # {'foo': 42}

Then obj is a valid python dictionary you can use as normal.

If you can't use double-quoted JSON, you could possibly refer to this question about parsing single-quoted JSON.


问:
Notification of ImportWizard in Eclipse RCP
I am developing an Eclipse RCP application. In this application I am importing the project using an Import Wizard. I want to get notified after the Import wizard is over.

Please help me!

答:
You can use ICommandService to monitor execution of commands in Eclipse Platform.

So you can notified when importing is executed with command id "
org.eclipse.ui.file.import":

```<code>ICommandService service = (ICommandService)
    PlatformUI.getWorkbench().getService(ICommandService.class);
service.addExecutionListener(...)
</code>```

You can describe logic which will executed after importing with extending WorkspaceJob.

```<code>public AfterImportingJob extends WorkspaceJob{
    ...
    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException{
        ... do something
        return Status.OK_STATUS;
    }
    ...
}
</code>```

WorkspaceJob automatically synchronized with Workspace. So After all change is done in Workspace, your Job will run. And it makes sure No other workspace modification is not running during your job is executing.

All you have to do to use this magic is just scheduling:

```<code>AfterImportingJob myJob = new AfterImporingJob();
myJob.schdule();
</code>```

Body:
You can use ICommandService to monitor execution of commands in Eclipse Platform.

So you can notified when importing is executed with command id "
org.eclipse.ui.file.import":

ICommandService service = (ICommandService)
    PlatformUI.getWorkbench().getService(ICommandService.class);
service.addExecutionListener(...)

You can describe logic which will executed after importing with extending WorkspaceJob.

public AfterImportingJob extends WorkspaceJob{
    ...
    public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException{
        ... do something
        return Status.OK_STATUS;
    }
    ...
}

WorkspaceJob automatically synchronized with Workspace. So After all change is done in Workspace, your Job will run. And it makes sure No other workspace modification is not running during your job is executing.

All you have to do to use this magic is just scheduling:

AfterImportingJob myJob = new AfterImporingJob();
myJob.schdule();


问:
Cannot display image in laravel
I've tried displaying an image with laravel using a Query-- The images are stored in the storage directory and a symlink with "public" has already been established.

I have tried using:
src="{{storage_path('app/public/'.$post->post_image)}}"

src="{{ asset('storage/'.$post->post_image) }}"

src="{{$post->post_image}}"

Testing, I discovered I could use a static path in order to succesfully display the imaage like so:

src="{{ asset('storage/images/image_name.jpeg')}}"

However, this is not what I'm looking for.

The query {{$post->post_image}} returns the following:

127.0.0.1:8000/images/image_name.jpeg

EDIT: If I go edit the database and add "storage/" before the url of the image, then I can use src="{{asset($post->post_image)}}" to display it.

As mentioned before, I already tried src="{{asset('storage/' . $post->post_image)}} without altering the database.

答:
Only store the image name in your db.

Don't add the path.

You can have a static method in that model that return the path as a string like (return "images/app";)

You can have another method that return a image_url
Which is going to be the path + image name

Title: Cannot display image in laravel


问:
React Native v5, Android 9 - Touch events not triggered
I created a new react native project using expo bare workflow and installed react native v5.

On iOS it is working fine.

But on Android, no touch events are being triggered.  Swiping is getting through though.

Any ideas why this might be happening ?

答:
It could be because you are importing TouchableOpacity or any touchable elements from another library and not from react-native itself. Most likely you're importing it from react-native-gesture-handler.

I encountered this problem before and it solved it for me.


问:
How to take values from a file, apply an equation to those values, and write them to file in c
How do I take values from a file, apply an equation to those values, and write them to file in c?
It seems simple, what I've tried just writes the same number as many times as I have samples. I would like to write a file with the new values.</p>

```<code>   printf("Enter the number of sample values in the file minus 1.\n");  //11025
   scanf("%d",&n);

   printf("using %d sample values.\n",n);

    //  fseek(filein, "%lg", SEEK_SET);
   for ( c = 0 ; c <= n ; c++ )//     // Convert a reading (which goes from 0 - 65536) to a value (-1 - 1):
                                      // float voltage = sensor * (1 / 65536.0);
   {
      fseek(filein, n, SEEK_SET);
      fscanf(filein, "%lg", var);

      sum = var * (maxy / 65536.0);
//todo?

//todo?
   fprintf(fileout,"%lg\n",sum);
   }
   getchar();
fclose(filein);
fclose(fileout);
   return 0;
}

return 0;
} ```
</code>```

答:
This answer is based on the code posted at Code Review.

The fseek() is part of the problem because it keeps resetting to the beginning of the file.

You could do this without the use of fseek(), the file will open to the beginning and you're reading binary data.

You should probably use fgets() rather than fscanf() to read each line separately and the convert the text using sscanf().

The format you want in the fprintf() and fscanf() is just %g or %G, the %l is for long integers.

Since the code is already using stdlib.h use the macros EXIT_SUCCESS and EXIT_FAILURE rather than 0, 1, SUCCESS or ERROR. Note that in C programming SUCCESS should be 0 and ERROR should be 1.

This program desperately needs functions, you are repeating code in too many places.

The for loop is a bug waiting to happen because it can attempt to read past the end of the file. A while loop that incorporates both the counting of lines and while not end of file would be much better.

Declare variables as needed.

Body:
How do I take values from a file, apply an equation to those values, and write them to file in c?
It seems simple, what I've tried just writes the same number as many times as I have samples. I would like to write a file with the new values.

   printf("Enter the number of sample values in the file minus 1.\n");  //11025
   scanf("%d",&n);

   printf("using %d sample values.\n",n);

    //  fseek(filein, "%lg", SEEK_SET);
   for ( c = 0 ; c <= n ; c++ )//     // Convert a reading (which goes from 0 - 65536) to a value (-1 - 1):
                                      // float voltage = sensor * (1 / 65536.0);
   {
      fseek(filein, n, SEEK_SET);
      fscanf(filein, "%lg", var);

      sum = var * (maxy / 65536.0);
//todo?

//todo?
   fprintf(fileout,"%lg\n",sum);
   }
   getchar();
fclose(filein);
fclose(fileout);
   return 0;
}

return 0;
} ```


问:
zsh sed distinguish "\(" from "("
I'm doing some string editing from a zsh script (on Mac OS Catalina). Some of the strings have a parentheses with a slash before and some don't (usually a space before).

I'm trying to write a command that ignores a left parenthesis unless it has a slash beforehand.

So the command...

```<code>sed 's/"\("/"\\\("/g'
</code>```

...would not be triggered by...

```<code>"foo (bar)"
</code>```

...but would be triggered on...

```<code>"foo \(bar)"
</code>```

答:
You may use

```<code>sed 's/\\*(/\\\\(/g' file > outfile
</code>```

Here, \\*( matches any amount of \ and then ( and the \\\\( replacement actually replaces with two \ chars and then (. It is necessary to use double backslash in the replacement part to represent one backslash because \ is used to encode backreferences (like \1, \2, etc.).

Title: zsh sed distinguish "\(" from "("

Body:
I'm doing some string editing from a zsh script (on Mac OS Catalina). Some of the strings have a parentheses with a slash before and some don't (usually a space before).

I'm trying to write a command that ignores a left parenthesis unless it has a slash beforehand.

So the command...

sed 's/"\("/"\\\("/g'

...would not be triggered by...

"foo (bar)"

...but would be triggered on...

"foo \(bar)"

Body:
You may use

sed 's/\\*(/\\\\(/g' file > outfile

Here, \\*( matches any amount of \ and then ( and the \\\\( replacement actually replaces with two \ chars and then (. It is necessary to use double backslash in the replacement part to represent one backslash because \ is used to encode backreferences (like \1, \2, etc.).


问:
Merging two arrays without using extra space
I have 2 sorted arrays, a1 and a2, of lengths l1 and l2, respectively.  The array a2 has empty space at the end of length l1, so it can hold all of the elements of a1 in addition to its own elements.  Now, I want to merge a1 into a2 so that a2 will contain all the elements of a1 and a2 in sorted order.  Ideally this should use O(1) auxiliary storage space.  I have the following cod,e but something is going wrong:

```<code> public static int[] merge(int []a1,int a2[],int l1, int l2){

         System.out.println("l1 =" +l1 + " l2=" +l2);
         int es = l2-l1;
         int fs = l2-es;

         System.out.println("es= " +es);
         System.out.println("fs = " + fs);
         int j=0;

         for(int i=0;i< l1;i++){

             if(j<fs){
                // System.out.println("i= " + i + "a1[i]=" + a1[i]);
                // System.out.println("j= " + j + "a2[j]=" + a2[j]);
                 if(a1[i]<a2[j]){
                     add(a2,j,a1[i],l2);
                     //i++;
                     fs++;
                 }
             }else{
                 System.out.println("***");
                 a2[j]=a1[i];
             }

             j++;
         }

         return a2;
     }

    public static void add(int []a,int p,int key,int l){

        for(int i=l-1;i>p;i--){
              a[i]= a[i-1];
        }
        a[p]= key;
    }
</code>```

Does anyone have any ideas on how to fix this?  I used following data to run the code:

```<code>int a1[]= new int[]{-1,0,7,8};
int a2[]= new int[7];
a2[0]=1;
a2[1]=3;
a2[2]=9;
</code>```

Output is

```<code>l1 =4 l2=7
es= 3
fs = 4
-1
0
1
3
9
0
0
</code>```

答:
/or simply you can do this->/

```<code>public static int[] merge(int []a1,int a2[],int l1, int l2){
     int j=0;
     for(int i=l2-l1;i<l2;i++)
     {
            a2[i]=a1[j];
              j++;
      }
      Arrays.sort(a2);
      return a2;

 }
</code>```

Body:
I have 2 sorted arrays, a1 and a2, of lengths l1 and l2, respectively.  The array a2 has empty space at the end of length l1, so it can hold all of the elements of a1 in addition to its own elements.  Now, I want to merge a1 into a2 so that a2 will contain all the elements of a1 and a2 in sorted order.  Ideally this should use O(1) auxiliary storage space.  I have the following cod,e but something is going wrong:

 public static int[] merge(int []a1,int a2[],int l1, int l2){

         System.out.println("l1 =" +l1 + " l2=" +l2);
         int es = l2-l1;
         int fs = l2-es;

         System.out.println("es= " +es);
         System.out.println("fs = " + fs);
         int j=0;

         for(int i=0;i< l1;i++){

             if(j<fs){
                // System.out.println("i= " + i + "a1[i]=" + a1[i]);
                // System.out.println("j= " + j + "a2[j]=" + a2[j]);
                 if(a1[i]<a2[j]){
                     add(a2,j,a1[i],l2);
                     //i++;
                     fs++;
                 }
             }else{
                 System.out.println("***");
                 a2[j]=a1[i];
             }

             j++;
         }

         return a2;
     }

    public static void add(int []a,int p,int key,int l){

        for(int i=l-1;i>p;i--){
              a[i]= a[i-1];
        }
        a[p]= key;
    }

Does anyone have any ideas on how to fix this?  I used following data to run the code:

int a1[]= new int[]{-1,0,7,8};
int a2[]= new int[7];
a2[0]=1;
a2[1]=3;
a2[2]=9;

Output is

l1 =4 l2=7
es= 3
fs = 4
-1
0
1
3
9
0
0

Body:
/or simply you can do this->/

public static int[] merge(int []a1,int a2[],int l1, int l2){
     int j=0;
     for(int i=l2-l1;i<l2;i++)
     {
            a2[i]=a1[j];
              j++;
      }
      Arrays.sort(a2);
      return a2;

 }


问:
Creating Binary Matrix in R with uneven dataframe
I have a dataset with microRNAs in 8 different groups. I need to transform this data frame into a binary matrix using R. The number of microRNAs is different in the groups and I would like to make the groups in the row and have the microRNAs on the columns. Here is part of the data:

```<code>Group1    Group2    Group3   Group4
miR-133a  miR-133b  miR-456  miR777
miR-777   miR138    miR-564  miR-878
miR-878             miR-777  miR978
                    miR-878
                    miR-978
</code>```

Output expected:

```<code>Groups  miR-133a  miR-133b  miR-456  miR-777.....
Group1  1             0      0        1
Group2  0             1      0        0
.
.
.
</code>```

I tried to use this code:

```<code>im <- which(arr.ind=T,Dat!='');
u <- unique(Dat[im[order(im[,'row'],im[,'col']),]]);
res <- matrix(0L,nrow(Dat),length(u),dimnames=list(NULL,u));
res[cbind(im[,'row'],match(Dat[im],u))] <- 1L;
res
</code>```

But it is giving me a lot of rows. Can anyone help me with that?

答:
Here is one option with tidyverse.  Reshape to 'long' format, then convert it back to 'wide' format with pivot_wider

```<code>library(dplyr)
library(tidyr)
df1 %>%
    pivot_longer(cols = everything(), names_to = 'Groups',
         values_drop_na = TRUE) %>%
    distinct %>%
    mutate(new =1) %>%
    pivot_wider(names_from =value, values_from = new,
           values_fill = list(new = 0))
#Groups `miR-133a` `miR-133b` `miR-456` miR777 `miR-777` miR138 `miR-564` `miR-878` miR978 `miR-978`
#  <chr>       <dbl>      <dbl>     <dbl>  <dbl>     <dbl>  <dbl>     <dbl>     <dbl>  <dbl>     <dbl>
#1 Group1          1          0         0      0         1      0         0         1      0         0
#2 Group2          0          1         0      0         0      1         0         0      0         0
#3 Group3          0          0         1      0         1      0         1         1      0         1
#4 Group4          0          0         0      1         0      0         0         1      1         0
</code>```

Or in base R with table

```<code>table(names(df1)[col(df1)], unlist(df1))
#           miR-133a miR-133b miR-456 miR-564 miR-777 miR-878 miR-978 miR138 miR777 miR978
#  Group1        1        0       0       0       1       1       0      0      0      0
#  Group2        0        1       0       0       0       0       0      1      0      0
#  Group3        0        0       1       1       1       1       1      0      0      0
#  Group4        0        0       0       0       0       1       0      0      1      1
</code>```

NOTE: Here, we assume the blanks as NA. If it is "", first change it to NA and then use the same code

```<code>df1[df1 == ""] <- NA
</code>```

data

```<code>df1 <- structure(list(Group1 = c("miR-133a", "miR-777", "miR-878", NA,
NA), Group2 = c("miR-133b", "miR138", NA, NA, NA), Group3 = c("miR-456",
"miR-564", "miR-777", "miR-878", "miR-978"), Group4 = c("miR777",
"miR-878", "miR978", NA, NA)), class = "data.frame", row.names = c(NA,
-5L))
</code>```

Body:
I have a dataset with microRNAs in 8 different groups. I need to transform this data frame into a binary matrix using R. The number of microRNAs is different in the groups and I would like to make the groups in the row and have the microRNAs on the columns. Here is part of the data:

Group1    Group2    Group3   Group4
miR-133a  miR-133b  miR-456  miR777
miR-777   miR138    miR-564  miR-878
miR-878             miR-777  miR978
                    miR-878
                    miR-978

Output expected:

Groups  miR-133a  miR-133b  miR-456  miR-777.....
Group1  1             0      0        1
Group2  0             1      0        0
.
.
.

I tried to use this code:

im <- which(arr.ind=T,Dat!='');
u <- unique(Dat[im[order(im[,'row'],im[,'col']),]]);
res <- matrix(0L,nrow(Dat),length(u),dimnames=list(NULL,u));
res[cbind(im[,'row'],match(Dat[im],u))] <- 1L;
res

But it is giving me a lot of rows. Can anyone help me with that?

Body:
Here is one option with tidyverse.  Reshape to 'long' format, then convert it back to 'wide' format with pivot_wider

library(dplyr)
library(tidyr)
df1 %>%
    pivot_longer(cols = everything(), names_to = 'Groups',
         values_drop_na = TRUE) %>%
    distinct %>%
    mutate(new =1) %>%
    pivot_wider(names_from =value, values_from = new,
           values_fill = list(new = 0))
#Groups `miR-133a` `miR-133b` `miR-456` miR777 `miR-777` miR138 `miR-564` `miR-878` miR978 `miR-978`
#  <chr>       <dbl>      <dbl>     <dbl>  <dbl>     <dbl>  <dbl>     <dbl>     <dbl>  <dbl>     <dbl>
#1 Group1          1          0         0      0         1      0         0         1      0         0
#2 Group2          0          1         0      0         0      1         0         0      0         0
#3 Group3          0          0         1      0         1      0         1         1      0         1
#4 Group4          0          0         0      1         0      0         0         1      1         0

Or in base R with table

table(names(df1)[col(df1)], unlist(df1))
#           miR-133a miR-133b miR-456 miR-564 miR-777 miR-878 miR-978 miR138 miR777 miR978
#  Group1        1        0       0       0       1       1       0      0      0      0
#  Group2        0        1       0       0       0       0       0      1      0      0
#  Group3        0        0       1       1       1       1       1      0      0      0
#  Group4        0        0       0       0       0       1       0      0      1      1

NOTE: Here, we assume the blanks as NA. If it is "", first change it to NA and then use the same code

df1[df1 == ""] <- NA

data

df1 <- structure(list(Group1 = c("miR-133a", "miR-777", "miR-878", NA,
NA), Group2 = c("miR-133b", "miR138", NA, NA, NA), Group3 = c("miR-456",
"miR-564", "miR-777", "miR-878", "miR-978"), Group4 = c("miR777",
"miR-878", "miR978", NA, NA)), class = "data.frame", row.names = c(NA,
-5L))


问:
C# gRPC localhost - Error starting gRPC call: No such host is known
I'm trying to get Microsoft's gRPC "Greeter" application to work on my business laptop, but I keep getting the following exception when invoking the gRPC call:

```<code>Grpc.Core.RpcException: 'Status(StatusCode=Internal, Detail="Error starting gRPC call: No such host is known.")'
</code>```

This is the documentation from Microsoft, which I followed.
The exact code I'm running comes from Microsoft's samples and can be found on their github here.

It literally boils down to starting the most basic gRPC server and then invoking the call via

```<code>using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client =  new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });
</code>```

The call to SayHelloAsync is the one that throws the exception.
The exact same code on my home machine works fine.
I've already checked my /etc/hosts file for weird entries, but nothing.
I've also tried changing https://localhost:5001 to https://[::1]:5001 and https://127.0.0.1:5001, same exception, which I find incredibly weird.

I've also already tried http via AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); and calling the http endpoint, same exception.

答:
I figured it out.
As expected it was a problem with the networking setup of my work laptop.

I had the HTTP_PROXY and HTTPS_PROXY environment variables set. These were picked up by the underlying HttpClient and tried routing the requests through the proxy. Removing the HTTP_PROXY and HTTPS_PROXY environment variables fixed the problem.
Alternatively setting the NO_PROXY environment variable to localhost,127.0.0.1,::1 also fixed the problem.

Body:
I'm trying to get Microsoft's gRPC "Greeter" application to work on my business laptop, but I keep getting the following exception when invoking the gRPC call:

Grpc.Core.RpcException: 'Status(StatusCode=Internal, Detail="Error starting gRPC call: No such host is known.")'

This is the documentation from Microsoft, which I followed.
The exact code I'm running comes from Microsoft's samples and can be found on their github here.

It literally boils down to starting the most basic gRPC server and then invoking the call via

using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client =  new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });

The call to SayHelloAsync is the one that throws the exception.
The exact same code on my home machine works fine.
I've already checked my /etc/hosts file for weird entries, but nothing.
I've also tried changing https://localhost:5001 to https://[::1]:5001 and https://127.0.0.1:5001, same exception, which I find incredibly weird.

I've also already tried http via AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); and calling the http endpoint, same exception.


问:
How to select values from a CSV file depending on the value of a specific column
Take this csv as an example:

```<code>Col1, Col2
1,3,
0,5,
1,4
0,7
</code>```

Say that I have a list, and I want to append the values of Col2 to the list only if the value of Col1 in the same row is 1. The resulting list should be [3,4].

How can I do this with pandas without using iterrows()?

答:
I think .loc is the most pythonic and simplest method.

```<code>df.loc[df['Col1'] == '1']['Col2'].to_list()
</code>```

An alternative using np.where:

```<code>import numpy as np
df['Col3'] = np.where(df['Col1'] == 1, df['Col2'], '')
listt = list(filter(None,df['Col3'].to_list()))
</code>```

zip is a loop alternative to iterrows.

```<code>listt = []
for x, y in zip(df['Col1'], df['Col2']):
    if x == 1:
        listt.append(y)
</code>```

Body:
Take this csv as an example:

Col1, Col2
1,3,
0,5,
1,4
0,7

Say that I have a list, and I want to append the values of Col2 to the list only if the value of Col1 in the same row is 1. The resulting list should be [3,4].

How can I do this with pandas without using iterrows()?

Body:
I think .loc is the most pythonic and simplest method.

df.loc[df['Col1'] == '1']['Col2'].to_list()

An alternative using np.where:

import numpy as np
df['Col3'] = np.where(df['Col1'] == 1, df['Col2'], '')
listt = list(filter(None,df['Col3'].to_list()))

zip is a loop alternative to iterrows.

listt = []
for x, y in zip(df['Col1'], df['Col2']):
    if x == 1:
        listt.append(y)


问:
How do I include a custom JS (JQuery) file in a .tpl?
So I have an HTML page that I want to take apart and put into my website in a more developer friendly manner. I was using Iframes but now I decided to integrate it into my .tpl file. For the life of me I can't figure out how to include a custom js file in the .tpl The way other files are included is in a php file but this is just to include the config file. I managed to put the HTML in the .tpl fine, the last part I need is the javascript. I believe the issue is that the JS is uses Jquery so I need to include that library but I can't seem to make it work. Any ideas? I've used literal and that didn't work either....

I can provide code examples on reqeust

答:
Depending on your template engine, you can either directly edit in the code directly into your template file or you can put in a reference point that your template engine can then pick up on.

If the scripts needs to run on all of the pages when that template file is run, you can just put in the javascript code directly into the template file. There are some major unknowns for me here, so you should always check back with your template engine's support; for example, if the code needs to run in the header, your engine likely has a dedicated way to inject the code. The advantage of putting the code directly into the template file is that you will not waste any additional resources 'templating it in', if you will, every time.

If you only want to run the script on specific pages, but more than just those pages uses that template file, you'll need to add an anchor to the template file and then edit your PHP script to place it in/ ignore the anchor according to your needs. Anchors, surprise, surprise, vary strongly with the different template engines. Smarty will, as Darien pointed out allready, accept anchors that are delimited with curly brackets, but that might not work in your case. If the template file is loaded and the page should not use the script, make sure to remove the anchor in your php script. So, your PHP should look similar to this:

```<code>if ($onRightPage) {

    // Call engine function to add in the script

} else {

    // Call engine function to remove the anchor

}
</code>```

Body:
Depending on your template engine, you can either directly edit in the code directly into your template file or you can put in a reference point that your template engine can then pick up on.

If the scripts needs to run on all of the pages when that template file is run, you can just put in the javascript code directly into the template file. There are some major unknowns for me here, so you should always check back with your template engine's support; for example, if the code needs to run in the header, your engine likely has a dedicated way to inject the code. The advantage of putting the code directly into the template file is that you will not waste any additional resources 'templating it in', if you will, every time.

If you only want to run the script on specific pages, but more than just those pages uses that template file, you'll need to add an anchor to the template file and then edit your PHP script to place it in/ ignore the anchor according to your needs. Anchors, surprise, surprise, vary strongly with the different template engines. Smarty will, as Darien pointed out allready, accept anchors that are delimited with curly brackets, but that might not work in your case. If the template file is loaded and the page should not use the script, make sure to remove the anchor in your php script. So, your PHP should look similar to this:

if ($onRightPage) {

    // Call engine function to add in the script

} else {

    // Call engine function to remove the anchor

}


问:
MapStruct utilize Mappings from a method into another method having return type of an inherent class
I have started using MapStruct recently and had this doubt. So is it possible to inherit mappings from one method into another method which is being used for mapping a subclass of the previous method's output.

For eg - If I have a class Car which needs to be mapped into two classes FourWheeler and DetailedFourWheeler(which extends the FourWheeler class) can I use the Mappings defined for the conversion of Car to FourWheeler into my method which converts Car to DetailedFourWheeler?
Here is the example code -

@lombok.Data
public class Car {
    private String color;
    private String brand;
    private String variant;
}

@lombok.Data
public class FourWheeler {
    private String paint;
    private String company;
}

@lombok.Data
public class DetailedFourWheeler extends FourWheeler {
    private String model;
}
```

<p>My Mapper for this looks like - </p>

<pre class="lang-java prettyprint-override"><code>@Mapper
interface FourWheelerMapper {

    public static final FourWheelerMapper INSTANCE = Mappers.getMapper(FourWheelerMapper.class);

    @Mappings({
            @Mapping(source = "color", target = "paint"),
            @Mapping(source = "brand", target = "company")
    })
    FourWheeler mapToFourWheeler(Car car);

    @Mappings({
            @Mapping(source = "color", target = "paint"),
            @Mapping(source = "brand", target = "company"),
            @Mapping(source = "variant", target = "model")
    })
    DetailedFourWheeler mapToDetailedFourWheeler(Car car);
}
</code>```

I want to know if it is possible to change the mapToDetailedFourWheeler like -

@InheritMappingsFromParent
@Mappings({
    @Mapping(source = "variant", target = "model")
})
DetailedFourWheeler mapToDetailedFourWheeler(Car car);
```

Here my InheritMappingsFromParent should bring in the mappings for color and brand from the previous method.

I was not able to find something relevant to this in the documentation.
Thanks

答:
MapStruct has the @InheritConfiguration annotation that will do what you are looking for. Have a look at Mapping configuration inheritance in the documentation for more information.

In any case for you it will not work if DetailedFourWheeler does not extend FourWheeler, since without that there is no way for MapStruct to know that the types are related.

Body:
I have started using MapStruct recently and had this doubt. So is it possible to inherit mappings from one method into another method which is being used for mapping a subclass of the previous method's output.

For eg - If I have a class Car which needs to be mapped into two classes FourWheeler and DetailedFourWheeler(which extends the FourWheeler class) can I use the Mappings defined for the conversion of Car to FourWheeler into my method which converts Car to DetailedFourWheeler?
Here is the example code -

@lombok.Data
public class Car {
    private String color;
    private String brand;
    private String variant;
}

@lombok.Data
public class FourWheeler {
    private String paint;
    private String company;
}

@lombok.Data
public class DetailedFourWheeler extends FourWheeler {
    private String model;
}

My Mapper for this looks like -

@Mapper
interface FourWheelerMapper {

    public static final FourWheelerMapper INSTANCE = Mappers.getMapper(FourWheelerMapper.class);

    @Mappings({
            @Mapping(source = "color", target = "paint"),
            @Mapping(source = "brand", target = "company")
    })
    FourWheeler mapToFourWheeler(Car car);

    @Mappings({
            @Mapping(source = "color", target = "paint"),
            @Mapping(source = "brand", target = "company"),
            @Mapping(source = "variant", target = "model")
    })
    DetailedFourWheeler mapToDetailedFourWheeler(Car car);
}

I want to know if it is possible to change the mapToDetailedFourWheeler like -

@InheritMappingsFromParent
@Mappings({
    @Mapping(source = "variant", target = "model")
})
DetailedFourWheeler mapToDetailedFourWheeler(Car car);

Here my InheritMappingsFromParent should bring in the mappings for color and brand from the previous method.

I was not able to find something relevant to this in the documentation.
Thanks


问:
Return a object from fs.readFile in Nodejs
I am trying to return jsonObj below and it is not returning. Help would be appreciated. Here fileName is the path of the file which I need to read. And again, I need to return jsonObj. So I can access it outside fs.readFile function.``
Here is the code</p>

```<code>return fs.readFile(fileName, 'utf-8', (err, fileContent) => {
  if(err) {
     console.log(err); // Do something to handle the error or just throw it
     throw new Error(err);
  }
  let jsonObj = csvjson.toObject(fileContent);
  console.log(jsonObj)
  return jsonObj
});
</code>```

答:
In Node you don't return from a callback function, that gets discarded and ignored. You must either use Promises, possibly in conjunction with async/await, or you must accept a callback function of your own.

This is the founding principle of asynchronous code:

```<code>// The fs.readFile() function executes immediately
fs.readFile(..., (err, ...) => {
   // This code runs in the distant future, like imagine ten years from now
   // from the perspective of the computer.
});

// JavaScript continues here immediately.
</code>```

The readFile function does not return anything in particular, the inner function has not yet been run. It's also worth noting that throwing exceptions in there is pointless, don't do it.

To chain:

```<code>function getData(fileName, cb) {
  fs.readFileName(fileName, 'utf-8', (err, fileContent) => {
    if (err) {
      // Back-propagate the error
      return cb(err);
    }

    // Engage the callback function with the data
    cb(null, csvjson.toObject(fileContent));
  }
}
</code>```

Note that this code is a lot less convoluted and messy if you use promises instead.

Body:
I am trying to return jsonObj below and it is not returning. Help would be appreciated. Here fileName is the path of the file which I need to read. And again, I need to return jsonObj. So I can access it outside fs.readFile function.``
Here is the code

return fs.readFile(fileName, 'utf-8', (err, fileContent) => {
  if(err) {
     console.log(err); // Do something to handle the error or just throw it
     throw new Error(err);
  }
  let jsonObj = csvjson.toObject(fileContent);
  console.log(jsonObj)
  return jsonObj
});

Body:
In Node you don't return from a callback function, that gets discarded and ignored. You must either use Promises, possibly in conjunction with async/await, or you must accept a callback function of your own.

This is the founding principle of asynchronous code:

// The fs.readFile() function executes immediately
fs.readFile(..., (err, ...) => {
   // This code runs in the distant future, like imagine ten years from now
   // from the perspective of the computer.
});

// JavaScript continues here immediately.

The readFile function does not return anything in particular, the inner function has not yet been run. It's also worth noting that throwing exceptions in there is pointless, don't do it.

To chain:

function getData(fileName, cb) {
  fs.readFileName(fileName, 'utf-8', (err, fileContent) => {
    if (err) {
      // Back-propagate the error
      return cb(err);
    }

    // Engage the callback function with the data
    cb(null, csvjson.toObject(fileContent));
  }
}

Note that this code is a lot less convoluted and messy if you use promises instead.


问:
FlaskWTF same form on every view / page
in my Flask Project i have configured a basepage.html Jinja template every other page inherits from.
In this basepage.html i want to have a Search bar at the top, so that it also appears at every page inheriting from it.

The input from this search form (is a form even the best way to do it?) should be processed
by the routing function search() I defined as follows:

views.py

```<code>@app.route('/')
@app.route('/dashboard')
def dashboard():
    return render_template('Dashboard.html') #Dashboard.html inherits from basepage.html

@app.route('/search', methods=['GET' ,'POST'])
def search():
    search_query = #input from search-bar
    result = #get data matching search_query from database
    return render_template('Search.html', results = results) #Search.html extends basepage.html
</code>```

forms.py excerpt:

```<code>class Search(FlaskForm):
    search_query = StringField('Search for ...')
    submit = SubmitField('Search')
</code>```

Is there a way i can have my Search form on every page, so when i enter my query in the bar at the top of the Dashboard form and press enter the search_query gets processed by the search() view?

答:
Just create your searchbar template code in a partial file located at /templates/includes/my_searchbar.html or whatever you want to name it and then in your base template just place an includes directive wherever you want the search to render in, something like:

```<code>{% include 'includes/my_searchbar.html' %}
</code>```

If the searchbar is included in base and all your other templates inherit from base, then search will be included on all pages.

All of your routes will also need to have the Search() form class included so they have access to the form, so you will need to modify your routes something like:

```<code>from app.forms import Search #if you defined Search in /app/forms.py

@app.route('/dashboard')
def dashboard():
    search_form = Search() #initialize an instance of the form
    return render_template('Dashboard.html', search_form=search_form)
</code>```

Then you can use search_form in your includes/my_searchbar.html partial to render the form. Maybe something like:

```<code><form class="form" method="post" role="form">
    {{ search_form.hidden_tag() }}
    {{ search_form.search_query }}
    {{ search_form.submit }}
</form>
</code>```

Title: FlaskWTF same form on every view / page

Body:
in my Flask Project i have configured a basepage.html Jinja template every other page inherits from.
In this basepage.html i want to have a Search bar at the top, so that it also appears at every page inheriting from it.

The input from this search form (is a form even the best way to do it?) should be processed
by the routing function search() I defined as follows:

views.py

@app.route('/')
@app.route('/dashboard')
def dashboard():
    return render_template('Dashboard.html') #Dashboard.html inherits from basepage.html

@app.route('/search', methods=['GET' ,'POST'])
def search():
    search_query = #input from search-bar
    result = #get data matching search_query from database
    return render_template('Search.html', results = results) #Search.html extends basepage.html

forms.py excerpt:

class Search(FlaskForm):
    search_query = StringField('Search for ...')
    submit = SubmitField('Search')

Is there a way i can have my Search form on every page, so when i enter my query in the bar at the top of the Dashboard form and press enter the search_query gets processed by the search() view?

Body:
Just create your searchbar template code in a partial file located at /templates/includes/my_searchbar.html or whatever you want to name it and then in your base template just place an includes directive wherever you want the search to render in, something like:

{% include 'includes/my_searchbar.html' %}

If the searchbar is included in base and all your other templates inherit from base, then search will be included on all pages.

All of your routes will also need to have the Search() form class included so they have access to the form, so you will need to modify your routes something like:

from app.forms import Search #if you defined Search in /app/forms.py

@app.route('/dashboard')
def dashboard():
    search_form = Search() #initialize an instance of the form
    return render_template('Dashboard.html', search_form=search_form)

Then you can use search_form in your includes/my_searchbar.html partial to render the form. Maybe something like:

<form class="form" method="post" role="form">
    {{ search_form.hidden_tag() }}
    {{ search_form.search_query }}
    {{ search_form.submit }}
</form>


问:
How to import h3-py (uber) on windows after installing it?
I want to ask about h3-py installation on windows

I have tried to install h3 on windows with python
I ran the command pip install h3 and it is installed.

After install, when I try to import it, i get this error:

```<code>    from h3 import h3
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-packages\h3\h3.py", line 39, in <module>
    libh3 = cdll.LoadLibrary('{}/{}'.format(_dirname, libh3_path))
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\ctypes\__init__.py", line 426, in LoadLibrary
    return self._dlltype(name)
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\ctypes\__init__.py", line 348, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found
</code>```

答:
Apprently there was a problem with the package and after fixing it in the release v3.6.1 it works. they fixed install issues.
As mentioned in this issue on github :
https://github.com/uber/h3-py/issues/32</p>

Body:
I want to ask about h3-py installation on windows

I have tried to install h3 on windows with python
I ran the command pip install h3 and it is installed.

After install, when I try to import it, i get this error:

    from h3 import h3
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\site-packages\h3\h3.py", line 39, in <module>
    libh3 = cdll.LoadLibrary('{}/{}'.format(_dirname, libh3_path))
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\ctypes\__init__.py", line 426, in LoadLibrary
    return self._dlltype(name)
  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python36\lib\ctypes\__init__.py", line 348, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found


问:
T-SQL Multiple duplicates check
I'm facing this problem - I have this kind of select result:

```<code>col1 col2           col3
5    95.91.232.198  1
8    95.91.232.198  1
9    95.91.222.206  5
152  95.91.222.206  1
25   95.91.204.108  5
5    95.91.204.108  5
</code>```

column3 can have only 2 values: 1 or 5

I want to select only those rows which have different numbers in column3 with duplicated ip - example (what should be selected):

this should be selected

```<code>127.0.0.1   1
127.0.0.1   5
</code>```

and this not

```<code>127.0.0.1   1
127.0.0.1   1
</code>```

Appreciate any help.

Title: T-SQL Multiple duplicates check

Body:
I'm facing this problem - I have this kind of select result:

col1 col2           col3
5    95.91.232.198  1
8    95.91.232.198  1
9    95.91.222.206  5
152  95.91.222.206  1
25   95.91.204.108  5
5    95.91.204.108  5

column3 can have only 2 values: 1 or 5

I want to select only those rows which have different numbers in column3 with duplicated ip - example (what should be selected):

this should be selected

127.0.0.1   1
127.0.0.1   5

and this not

127.0.0.1   1
127.0.0.1   1

Appreciate any help.

Body:
You can use DISTINCT keyword to select only unique combinations of values.

Starting data:

col1 col2 col3
5   95.91.232.198   1
8   95.91.232.198   1
9   95.91.222.206   5
152 95.91.222.206   1
25  95.91.204.108   5
5   95.91.204.108   5

Example:

SELECT DISTINCT col2, col3
FROM [table]

Output:

col2 col3
95.91.232.198   1
95.91.222.206   5
95.91.222.206   1
95.91.204.108   5


问:
Script to send email based on value in a column - problem with script
New to GAS.  I have a Google Form feeding into a spreadsheet. After watching tutorial videos and reading other posts, I attempted to create a script that will send an email to an address in column 2, and send a different email based on either a yes or no in another column (column 25).  It also includes another column (26) that I want to have the date populated into when the email is sent, ensuring that every time I run this script, there are no duplicates sent.  I have debugged and nothing comes up as an error, but it's not working - I have not received an email.  Help would be greatly appreciated!  Here is an example spreadsheet: https://docs.google.com/spreadsheets/d/1AKaSOk1ZbnfKeadgB_mugnqplKzJJ3bDQ_KsRY0sMvQ/edit?usp=sharing</p>

```<code>function sendEmail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var responses = ss.getSheetByName("Field Trip Requests");

  var data = responses.getRange(2,1,responses.getLastRow()-1,25).getValues();

  data.forEach(function(row,i) {
    // variables
    var recipient = row[1];
    var destination = row[6];
    var approval = row[24];
    var emailSent = row[25];

    if(emailSent == ' ') {

      if(approval == "Y") {
        var body = "Your field trip request for " +
          destination +
            " has been approved! If you requested transportation, Najma will make arrangements and contact you if she requires more information." +
              "<br><br>" +
                "Cheers," +
                  "<br><br>" +
                    "Boaty McBoatface";

      }
      else if(approval == "N") {
        var body = "Your field trip request for " +
          destination +
            " has not been approved.  Please come and see me and we can chat!" +
              "<br><br>" +
                "Cheers," +
                  "<br><br>" +
                    "Boaty McBoatface";

      }

      var subject = "Your Field Trip Request";

      MailApp.sendEmail(recipient, subject, body)

      var d = new Date();

      responses.getRange(i + 1, 25).setValue(d);

    }

  })

}

</code>```

答:
If this var data = responses.getRange(2,1,responses.getLastRow()-1,25).getValues(); is correct then there is no row[25] as shown below:

```<code>data.forEach(function(row,i) {
    // variables
    var recipient = row[1];
    var destination = row[6];
    var approval = row[24];
    var emailSent = row[25];
</code>```

row starts at zero and ends at 24

row is an array

Perhaps this is what you wish:

```<code>function sendEmail() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName("Field Trip Requests");
  var data=sh.getRange(2,1,responses.getLastRow()-1,25).getValues();
  data.forEach(function(row,i) {
    var recipient=row[0];
    var destination=row[5];
    var approval=row[23];
    var emailSent=row[24];
    if(emailSent=='' &&  approval=='Y') {
      var body=Utilities.formatString('Your field trip request for %s has been approved! If you requested transportation, Najma will make arrangements and contact you if she requires more information. <br><br>Cheers<br><br>Boaty McBoatface',destination);
    }else if(emailSent=='' && approval == "N") {
      var body=Utilities.formatString('Your field trip request for %shas not been approved.  Please come and see me and we can chat!<br><br>Cheers,<br><br>Boaty McBoatface',destination);
    }
    var subject="Your Field Trip Request";
    MailApp.sendEmail(recipient, subject, body);
    sh.getRange(i+1,25).setValue(Utilities.formatDate(new Date, Session.getScriptTimeZone(), "MM/dd/yyyy"));
  })
}
</code>```

Body:
New to GAS.  I have a Google Form feeding into a spreadsheet. After watching tutorial videos and reading other posts, I attempted to create a script that will send an email to an address in column 2, and send a different email based on either a yes or no in another column (column 25).  It also includes another column (26) that I want to have the date populated into when the email is sent, ensuring that every time I run this script, there are no duplicates sent.  I have debugged and nothing comes up as an error, but it's not working - I have not received an email.  Help would be greatly appreciated!  Here is an example spreadsheet: https://docs.google.com/spreadsheets/d/1AKaSOk1ZbnfKeadgB_mugnqplKzJJ3bDQ_KsRY0sMvQ/edit?usp=sharing

function sendEmail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var responses = ss.getSheetByName("Field Trip Requests");

  var data = responses.getRange(2,1,responses.getLastRow()-1,25).getValues();

  data.forEach(function(row,i) {
    // variables
    var recipient = row[1];
    var destination = row[6];
    var approval = row[24];
    var emailSent = row[25];

    if(emailSent == ' ') {

      if(approval == "Y") {
        var body = "Your field trip request for " +
          destination +
            " has been approved! If you requested transportation, Najma will make arrangements and contact you if she requires more information." +
              "

" +
                "Cheers," +
                  "

" +
                    "Boaty McBoatface";

      }
      else if(approval == "N") {
        var body = "Your field trip request for " +
          destination +
            " has not been approved.  Please come and see me and we can chat!" +
              "

" +
                "Cheers," +
                  "

" +
                    "Boaty McBoatface";

      }

      var subject = "Your Field Trip Request";

      MailApp.sendEmail(recipient, subject, body)

      var d = new Date();

      responses.getRange(i + 1, 25).setValue(d);

    }

  })

}

Body:
If this var data = responses.getRange(2,1,responses.getLastRow()-1,25).getValues(); is correct then there is no row[25] as shown below:

data.forEach(function(row,i) {
    // variables
    var recipient = row[1];
    var destination = row[6];
    var approval = row[24];
    var emailSent = row[25];

row starts at zero and ends at 24

row is an array

Perhaps this is what you wish:

function sendEmail() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName("Field Trip Requests");
  var data=sh.getRange(2,1,responses.getLastRow()-1,25).getValues();
  data.forEach(function(row,i) {
    var recipient=row[0];
    var destination=row[5];
    var approval=row[23];
    var emailSent=row[24];
    if(emailSent=='' &&  approval=='Y') {
      var body=Utilities.formatString('Your field trip request for %s has been approved! If you requested transportation, Najma will make arrangements and contact you if she requires more information. <br><br>Cheers<br><br>Boaty McBoatface',destination);
    }else if(emailSent=='' && approval == "N") {
      var body=Utilities.formatString('Your field trip request for %shas not been approved.  Please come and see me and we can chat!<br><br>Cheers,<br><br>Boaty McBoatface',destination);
    }
    var subject="Your Field Trip Request";
    MailApp.sendEmail(recipient, subject, body);
    sh.getRange(i+1,25).setValue(Utilities.formatDate(new Date, Session.getScriptTimeZone(), "MM/dd/yyyy"));
  })
}


问:
choice parameter inside parallel stage declarative pipeline
I am not able to echo A or B or C when using condition in parallel block. I have used choice params for it.

It work when I am using global params but I want to use it in under one stage.

Pipeline:

```<code>pipeline {
    agent any
    parameters {
      choice choices: ['Dev', 'QA'], description: 'Make a choice', name: 'CLICK'
    }
    stages {

      stage('Dev') {
        when { expression { params.CLICK == 'DEV' } }
        steps {
          echo "Dev"
        }
      }

      stage('QA') {
        when { expression { params.CLICK == 'QA' } }
        input {
            message "Choose appropriate Test?"
            parameters {
                choice choices: ['MobileAPP', 'FrontEnd', 'BankEnd'], description: 'Make a choice', name: 'CLICK1'
            }
        }
        parallel {
            stage('A') {
                when {
                    expression { params.CLICK == 'MobileAPP' }
                }
                steps {
                  echo "A"
                }
            }
            stage('B') {
                when {
                    expression { params.CLICK == 'FrontEnd' }
                }
                steps {
                  echo "B"
                }
            }
            stage('C') {
                when {
                    expression { params.CLICK == 'BackEnd' }
                }
                steps {
                  echo "C"
                }
            }
        }
      }
    }
}
</code>```

Wrong output:

答:
Well, I could acheive it by make stage level paramters as global and then use them in another stages which worked as expected.</p>

```<code>  stage('QA') {
    when { expression { params.CLICK == 'QA' } }
      steps {
        script {
           CHOICES = ['MobileAPP', 'FrontEnd', 'BankEnd'];
                    env.CLICK1 = input  message: 'Choose appropriate Test?',ok : 'Deploy',id :'tag_id', parameters:[choice(choices: CHOICES, description: 'Make a choice', name: 'Select')]
                }

            }
    }
    parallel {
        stage('A') {
            when {
                expression { env.CLICK == 'MobileAPP' }
            }
            steps {
              echo "A"
            }
        }
        stage('B') {
            when {
                expression { env.CLICK == 'FrontEnd' }
            }
            steps {
              echo "B"
            }
        }
        stage('C') {
            when {
                expression { env.CLICK == 'BackEnd' }
            }
            steps {
              echo "C"
            }
        }
    }
  }
}
</code>```

Body:
I am not able to echo A or B or C when using condition in parallel block. I have used choice params for it.

It work when I am using global params but I want to use it in under one stage.

Pipeline:

pipeline {
    agent any
    parameters {
      choice choices: ['Dev', 'QA'], description: 'Make a choice', name: 'CLICK'
    }
    stages {

      stage('Dev') {
        when { expression { params.CLICK == 'DEV' } }
        steps {
          echo "Dev"
        }
      }

      stage('QA') {
        when { expression { params.CLICK == 'QA' } }
        input {
            message "Choose appropriate Test?"
            parameters {
                choice choices: ['MobileAPP', 'FrontEnd', 'BankEnd'], description: 'Make a choice', name: 'CLICK1'
            }
        }
        parallel {
            stage('A') {
                when {
                    expression { params.CLICK == 'MobileAPP' }
                }
                steps {
                  echo "A"
                }
            }
            stage('B') {
                when {
                    expression { params.CLICK == 'FrontEnd' }
                }
                steps {
                  echo "B"
                }
            }
            stage('C') {
                when {
                    expression { params.CLICK == 'BackEnd' }
                }
                steps {
                  echo "C"
                }
            }
        }
      }
    }
}

Wrong output:

Body:
Well, I could acheive it by make stage level paramters as global and then use them in another stages which worked as expected.

  stage('QA') {
    when { expression { params.CLICK == 'QA' } }
      steps {
        script {
           CHOICES = ['MobileAPP', 'FrontEnd', 'BankEnd'];
                    env.CLICK1 = input  message: 'Choose appropriate Test?',ok : 'Deploy',id :'tag_id', parameters:[choice(choices: CHOICES, description: 'Make a choice', name: 'Select')]
                }

            }
    }
    parallel {
        stage('A') {
            when {
                expression { env.CLICK == 'MobileAPP' }
            }
            steps {
              echo "A"
            }
        }
        stage('B') {
            when {
                expression { env.CLICK == 'FrontEnd' }
            }
            steps {
              echo "B"
            }
        }
        stage('C') {
            when {
                expression { env.CLICK == 'BackEnd' }
            }
            steps {
              echo "C"
            }
        }
    }
  }
}


问:
Powershell sshd commands different
I have OpenSSH installed on Windows Server 2019 https://github.com/PowerShell/Win32-OpenSSH

SSH works great except for an issue with pipe ( | ) commands in Powershell SSH. I have successfully converted some of my | commands to ; example:

```<code>powershell  Mount-VHD -Path D:/VMdir/tester.vhdx -PassThru | Get-Disk | Get-Partition | Get-Volume
</code>```

becomes

```<code>powershell  Mount-VHD -Path D:/VMdir/tester.vhdx -PassThru; Get-Disk; Get-Partition; Get-Volume
</code>```

and it works fine, but I also have:

```<code>powershell (Get-VM tester | select-object MemoryMaximum).memorymaximum/1mb
</code>```

and I can't get this one to work in SSH, works fine in windows though but not via SSH. I have tried a ; and & but it doesn't work. First why would the pipe commands work inside windows but not outside windows via ssh and any idea on how I can replace the pipe in the above command to get it work through ssh? The above command displays only a number (eg. 2048) it doesn't display any other info and that's what I need only a number.

答: Use "|" instead of | works perfectly.</p>

Title: Powershell sshd commands different

Body:
I have OpenSSH installed on Windows Server 2019 https://github.com/PowerShell/Win32-OpenSSH

SSH works great except for an issue with pipe ( | ) commands in Powershell SSH. I have successfully converted some of my | commands to ; example:

powershell  Mount-VHD -Path D:/VMdir/tester.vhdx -PassThru | Get-Disk | Get-Partition | Get-Volume

becomes

powershell  Mount-VHD -Path D:/VMdir/tester.vhdx -PassThru; Get-Disk; Get-Partition; Get-Volume

and it works fine, but I also have:

powershell (Get-VM tester | select-object MemoryMaximum).memorymaximum/1mb

and I can't get this one to work in SSH, works fine in windows though but not via SSH. I have tried a ; and & but it doesn't work. First why would the pipe commands work inside windows but not outside windows via ssh and any idea on how I can replace the pipe in the above command to get it work through ssh? The above command displays only a number (eg. 2048) it doesn't display any other info and that's what I need only a number.

Body: Use "|" instead of | works perfectly.


问:
How to get current authenticated user id using Vuejs and Laravel?
I am using Vuejs as my frontend and I would simply like to get the current logged in user's id from Laravel and display it. How would I do this?</p>

答:
I've needed to pass data to my Header component, so I thought I may share the way I'm doing it

```<code><fronend-header :current-user="{{ json_encode(['isLoggedIn'=>auth()->check() ? true : false, 'user'=>auth()->check() ? auth()->user() : null]) }}" />
</code>```

On the vuejs side

```<code><script>
    export default {
        name: "frontend-header",

        props: {
            currentUser: {
                type: Object,
                required: true
            }
        }
    };
</script>
</code>```

didn't tried it on logged in state yet, but I'll do any needed changes if needed.

Body:
I've needed to pass data to my Header component, so I thought I may share the way I'm doing it

<fronend-header :current-user="{{ json_encode(['isLoggedIn'=>auth()->check() ? true : false, 'user'=>auth()->check() ? auth()->user() : null]) }}" />

On the vuejs side

<script>
    export default {
        name: "frontend-header",

        props: {
            currentUser: {
                type: Object,
                required: true
            }
        }
    };
</script>

didn't tried it on logged in state yet, but I'll do any needed changes if needed.