问:
In Java, how to print divisor numbers?
I want to print the divisors of a user input value between 1 and 10000.

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

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }

        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}
</code>```

I have problem here with command System.out.println("loop);.
  I want to print all the divisors, like if a user inserted 10, then the
  output should show something like:

!

```<code>Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4
</code>```

!
!

But the current output is:

!

```<code>Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4
</code>```

!
!

so how to print loop only when the (Range % loop == 0) is true??

答:
You missed the {}</p>

```<code>for (int loop = 1; loop <= Range; loop++) {
    if (Range % loop == 0) {
       System.out.println(loop);
       Divisor++;
    }

}
</code>```

Title: In Java, how to print divisor numbers?

Body:
I want to print the divisors of a user input value between 1 and 10000.

import java.util.Scanner;

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }

        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}

I have problem here with command System.out.println("loop);.
  I want to print all the divisors, like if a user inserted 10, then the
  output should show something like:

!

Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4

!
!

But the current output is:

!

Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4

!
!

so how to print loop only when the (Range % loop == 0) is true??

Body:
You missed the {}

for (int loop = 1; loop <= Range; loop++) {
    if (Range % loop == 0) {
       System.out.println(loop);
       Divisor++;
    }

}


来源: stackexchange

问:
call different function during page refresh and close javascript
I am creating a web app using web socket, which on user closes the tab I will make an API call to the server to clean the user related info in the server, I used onBeforeUnload listener in javascript, but this method also gets triggered during the page refresh.

I need to trigger a method only during the tab or browser close, but not during the page refresh.

I know this question has been asked several times, some solution suggested using cookies will not be helpful in my case

答:
navigator.sendBeacon() method can be used for sending data from browser to server when a tab is closed.

Here is an example:

```<code>window.addEventListener("unload", function informServer() {
  navigator.sendBeacon("/server-api-to-collect-data", my-data)
})
</code>```

More information:

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

ContentLicense: CC BY-SA 4.0

Body:
navigator.sendBeacon() method can be used for sending data from browser to server when a tab is closed.

Here is an example:

window.addEventListener("unload", function informServer() {
  navigator.sendBeacon("/server-api-to-collect-data", my-data)
})

More information:

https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon


问:
Why is if statement not working in ElementTree parsing?
I'm trying to parse an xml file using ElementTree which looks like this:

<Game>
  <Event timestamp="2016-08-14T14:23:33.634" id="1713385925"
         version="1471181110290" last_modified="2016-08-14T14:25:11" y="11.0"
         x="89.7" outcome="0" team_id="148" player_id="51327" sec="8" min="23"
         period_id="1" type_id="4" event_id="205">

    <Q id="733814222" qualifier_id="265"/>
    <Q id="481660420" qualifier_id="286"/>
    <Q id="813378778" qualifier_id="152"/>
    <Q id="570443899" qualifier_id="56" value="Right"/>
    <Q id="420312891" qualifier_id="233" value="248"/>
    <Q id="1186861264" qualifier_id="13"/>
  </Event>

  <Event timestamp="2016-08-14T14:23:33.634" id="1635888622"
         version="1471181110289" last_modified="2016-08-14T14:25:11" y="89.0"
         x="10.3" outcome="1" team_id="143" player_id="169007" sec="8" min="23"
         period_id="1" type_id="4" event_id="248">

    <Q id="1871787686" qualifier_id="56" value="Back"/>
    <Q id="176295814" qualifier_id="13"/>
    <Q id="69346842" qualifier_id="233" value="205"/>
    <Q id="1588029344" qualifier_id="265"/>
    <Q id="559785299" qualifier_id="285"/>
    <Q id="380723313" qualifier_id="152"/>
  </Event>
</Game>
```

<p>The code I'm using is simple and is working as expected. However, everything changes when I try to add an <code>if condition</code> to the code</p>

```import xml.etree.ElementTree as ET

root = ET.parse(r'C:\Users\ADMIN\Desktop\Abhishek\PSG - Copy\Sample.xml').getroot()

Games = root.getchildren()
for Game in Games:
    Events = Game.getchildren()
    for Event in Events:
        type_id = Event.attrib["type_id"]
        team_id = Event.attrib["team_id"]
        Qualifiers = Event.getchildren()
        for Qualifier in Qualifiers:
            id_ = Qualifier.attrib['id']
            if id_ == 142:
                print ("val")
```

<p>Here's the error it's producing:</p>

```Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 9
    Games = root.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.

Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 11
    Events = Game.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.

Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 15
    Qualifiers = Event.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.
```

I have tried removing the if statement and that works perfectly. However, I do need to set a condition to call all the id_s which are a certain value. I've tried using "142" as well as 142 but the problem persists. Why exactly is this happening?

答:
Its a warning the getchildren() method is depreciated. Here is how to get the children now without the warning</p>

```<code>def goddamnit_what_are_my_kids_called(self, element):
    for child in list(element):
        print(child.tag)
</code>```

Body:
I'm trying to parse an xml file using ElementTree which looks like this:

<Game>
  <Event timestamp="2016-08-14T14:23:33.634" id="1713385925"
         version="1471181110290" last_modified="2016-08-14T14:25:11" y="11.0"
         x="89.7" outcome="0" team_id="148" player_id="51327" sec="8" min="23"
         period_id="1" type_id="4" event_id="205">

    <Q id="733814222" qualifier_id="265"/>
    <Q id="481660420" qualifier_id="286"/>
    <Q id="813378778" qualifier_id="152"/>
    <Q id="570443899" qualifier_id="56" value="Right"/>
    <Q id="420312891" qualifier_id="233" value="248"/>
    <Q id="1186861264" qualifier_id="13"/>
  </Event>

  <Event timestamp="2016-08-14T14:23:33.634" id="1635888622"
         version="1471181110289" last_modified="2016-08-14T14:25:11" y="89.0"
         x="10.3" outcome="1" team_id="143" player_id="169007" sec="8" min="23"
         period_id="1" type_id="4" event_id="248">

    <Q id="1871787686" qualifier_id="56" value="Back"/>
    <Q id="176295814" qualifier_id="13"/>
    <Q id="69346842" qualifier_id="233" value="205"/>
    <Q id="1588029344" qualifier_id="265"/>
    <Q id="559785299" qualifier_id="285"/>
    <Q id="380723313" qualifier_id="152"/>
  </Event>
</Game>

The code I'm using is simple and is working as expected. However, everything changes when I try to add an if condition to the code

import xml.etree.ElementTree as ET

root = ET.parse(r'C:\Users\ADMIN\Desktop\Abhishek\PSG - Copy\Sample.xml').getroot()

Games = root.getchildren()
for Game in Games:
    Events = Game.getchildren()
    for Event in Events:
        type_id = Event.attrib["type_id"]
        team_id = Event.attrib["team_id"]
        Qualifiers = Event.getchildren()
        for Qualifier in Qualifiers:
            id_ = Qualifier.attrib['id']
            if id_ == 142:
                print ("val")

Here's the error it's producing:

Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 9
    Games = root.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.

Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 11
    Events = Game.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.

Warning (from warnings module):
  File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python37\PSGPossessionSequences.py", line 15
    Qualifiers = Event.getchildren()
DeprecationWarning: This method will be removed in future versions.  Use 'list(elem)' or iteration over elem instead.

I have tried removing the if statement and that works perfectly. However, I do need to set a condition to call all the id_s which are a certain value. I've tried using "142" as well as 142 but the problem persists. Why exactly is this happening?

Body:
Its a warning the getchildren() method is depreciated. Here is how to get the children now without the warning

def goddamnit_what_are_my_kids_called(self, element):
    for child in list(element):
        print(child.tag)


问:
Remove 'uploaded' add-in Word Online
I’m preparing some ‘tutorial’ videos and have probably a stupid question that I'm just overlooking the answer.

I’m following the steps on starter:
https://dev.office.com/getting-started/addins?product=word
with the option “Other Tools”

This all works fairly straight forward, ending with adding the generated AddIn to Word Online:

My question is though …. How do you get rid of the just added Show Taskpane again?

I can’t imagine it to be very hard, but I just don’t see the option anywhere in Word Online, to clean up again and remove the add-in to get a clean slate for the next video….

答:
For people coming here from google:
If you tested your javascript add-ins locally you can remove those add-ins in MS Word by going File-Options-Trust Center-Trust Center Settings...-Trusted Add-In Catalogs and click 'Clear'.</p>

ContentLicense: CC BY-SA 3.0

Title: Remove 'uploaded' add-in Word Online


问:
ReferenceError uppy is not defined
Error image

I implement shrine gem with cropperjs and uppy in rails,

I refer to Usage of shrine Image Cropping and Example code

Then I implemented  code, seemingly code is correct,

But I got some errors Module not found: Error: Can't resolve 'cropbox' 2
  and above errors,

I searched similar issues and tried some solutions still I can't use shrine gem,

Would you like to help me?

application.js:

```<code>//= require popper
//= require bootstrap-sprockets
//= require_tree .

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")

function fileUpload(fileInput) {
 var formGroup = fileInput.parentNode
 var hiddenInput = document.querySelector('.upload-data')
 var imagePreview = document.querySelector('.image-preview img')

formGroup.removeChild(fileInput)

 var uppy = Uppy.Core({
    autoProceed: true,
    restrictions: {
     allowedFileTypes: fileInput.accept.split(','),
    }
   })
  .use(Uppy.FileInput, {
    target: formGroup,
    locale: { strings: { chooseFiles: 'Choose file' } },
   })
  .use(Uppy.Informer, {
    target: formGroup,
   })
  .use(Uppy.ProgressBar, {
    target: imagePreview.parentNode,
  })
  .use(Uppy.ThumbnailGenerator, {
    thumbnailWidth: 600,
  })
  .use(Uppy.XHRUpload, {
    endpoint: '/upload',
  })

uppy.on('upload-success', function (file, response) {
  imagePreview.src = response.uploadURL

  var uploadedFileData = JSON.stringify(response.body['data'])

  hiddenInput.value = uploadedFileData

  var copper = new Cropper(imagePreview, {
    aspectRatio: 1,
    viewMode: 1,
    guides: false,
    autoCropArea: 1.0,
    background: false,
    crop: function (event) {
    data = JSON.parse(hiddenInput.value)
    data['metadata']['crop'] = event.detail
    hiddenInput.value = JSON.stringify(data)
     }
    })
  })
}

 document.querySelectorAll('input[type="file"]').forEach(function (fileInput) {
  fileUpload(fileInput)
})
</code>```

cropbox.js:

```<code>import 'cropperjs/dist/cropper.css';

import Cropper from 'cropperjs'

function cropbox(image, url, { onCrop }) {
 image.src = url

   new Cropper(image, {
    aspectRatio: 1,
    viewMode: 1,
    guides: false,
    autoCropArea: 1.0,
    background: false,
    zoomable: false,
    crop: event => onCrop(event.detail)
  })
}

export default cropbox
</code>```

fileUpload.js:

```<code>import cropbox from 'cropbox'

  uppy.on('upload-success', (file, response) => {
   // retrieve uploaded file data
    const uploadedFileData = response.body['data']

    // set hidden field value to the uploaded file data so that it's submitted
    // with the form as the attachment
    hiddenInput.value = JSON.stringify(uploadedFileData)

    cropbox(imagePreview, response.uploadURL, {
      onCrop(detail) {
        let fileData = JSON.parse(hiddenInput.value)
        fileData['metadata']['crop'] = detail
        hiddenInput.value = JSON.stringify(fileData)
      }
    })
  })
</code>```

form.html.erb:

```<code><%= form_with model: @blog_form , url: user_blogs_path ,local: true do |f| %>

 <div class="field">
  <%  f.label :title %>
  <%= f.text_field :title %>
 </div>

<div class="field">
<%  f.label :content %>
<%= f.text_area :content %>
</div>

<div class="field ">
<%  f.label :user_id %>
<%= f.hidden_field :user_id, value: current_user.id %>
</div>

<div class ="field form-group">
<%= f.fields_for  :photos, Photo.new do |photos_fileds|  %>

<%= photos_fileds.label :image , class: "form-control" %>
<%= photos_fileds.hidden_field :image,  class: "upload-data", value:
photos_fileds.object.cached_image_data %>
<%= photos_fileds.file_field  :image , class: "form-control  ", id: "select-files"%><br/>
<div class="image-preview">
<img id="image" src="<%= photos_fileds.object.image_url(:medium) %>" height="300" class="rounded"  >
</div>

<% end %>

</div>

  <%= f.submit "create", class: "btn btn-primary" %>
 <% end %>
</code>```

application.html.erb:

```<code>  <!DOCTYPE html>
 <html>
   <head>
    <title>Prottype2</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

   <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
   <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
   <%= javascript_pack_tag 'application' %>
   <%= javascript_pack_tag 'cropbox' %>
   <%= javascript_pack_tag 'fileUpload'%>

   <script src="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js"></script>

   <link href="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.css" rel="stylesheet" />
   <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css" rel="stylesheet"
 />

  </head>

  <body>

   <p class="notice"><%= notice %></p>
   <p class="alert"><%= alert %></p>

   <%= yield %>

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

I moved code position

application.html.erb:

```<code><script src="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.js">
</script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js">
</script>

<link href="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.css"
rel="stylesheet" />
<link
href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css"
rel="stylesheet" />

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track':
 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track':
'reload' %>
<%= javascript_pack_tag 'application' %>
<%= javascript_pack_tag 'app' %>
<%= javascript_pack_tag 'cropbox' %>
<%= javascript_pack_tag 'fileUpload'%>
</code>```

And also I moved file input application.js to app.js

答:
I solved this error, I refered to Shrine example in Rails
I just forgot the details of code in fileUpload.js</p>

Title: ReferenceError uppy is not defined

Body:
Error image

I implement shrine gem with cropperjs and uppy in rails,

I refer to Usage of shrine Image Cropping and Example code

Then I implemented  code, seemingly code is correct,

But I got some errors Module not found: Error: Can't resolve 'cropbox' 2
  and above errors,

I searched similar issues and tried some solutions still I can't use shrine gem,

Would you like to help me?

application.js:

//= require popper
//= require bootstrap-sprockets
//= require_tree .

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")

function fileUpload(fileInput) {
 var formGroup = fileInput.parentNode
 var hiddenInput = document.querySelector('.upload-data')
 var imagePreview = document.querySelector('.image-preview img')

formGroup.removeChild(fileInput)

 var uppy = Uppy.Core({
    autoProceed: true,
    restrictions: {
     allowedFileTypes: fileInput.accept.split(','),
    }
   })
  .use(Uppy.FileInput, {
    target: formGroup,
    locale: { strings: { chooseFiles: 'Choose file' } },
   })
  .use(Uppy.Informer, {
    target: formGroup,
   })
  .use(Uppy.ProgressBar, {
    target: imagePreview.parentNode,
  })
  .use(Uppy.ThumbnailGenerator, {
    thumbnailWidth: 600,
  })
  .use(Uppy.XHRUpload, {
    endpoint: '/upload',
  })

uppy.on('upload-success', function (file, response) {
  imagePreview.src = response.uploadURL

  var uploadedFileData = JSON.stringify(response.body['data'])

  hiddenInput.value = uploadedFileData

  var copper = new Cropper(imagePreview, {
    aspectRatio: 1,
    viewMode: 1,
    guides: false,
    autoCropArea: 1.0,
    background: false,
    crop: function (event) {
    data = JSON.parse(hiddenInput.value)
    data['metadata']['crop'] = event.detail
    hiddenInput.value = JSON.stringify(data)
     }
    })
  })
}

 document.querySelectorAll('input[type="file"]').forEach(function (fileInput) {
  fileUpload(fileInput)
})

cropbox.js:

import 'cropperjs/dist/cropper.css';

import Cropper from 'cropperjs'

function cropbox(image, url, { onCrop }) {
 image.src = url

   new Cropper(image, {
    aspectRatio: 1,
    viewMode: 1,
    guides: false,
    autoCropArea: 1.0,
    background: false,
    zoomable: false,
    crop: event => onCrop(event.detail)
  })
}

export default cropbox

fileUpload.js:

import cropbox from 'cropbox'

  uppy.on('upload-success', (file, response) => {
   // retrieve uploaded file data
    const uploadedFileData = response.body['data']

    // set hidden field value to the uploaded file data so that it's submitted
    // with the form as the attachment
    hiddenInput.value = JSON.stringify(uploadedFileData)

    cropbox(imagePreview, response.uploadURL, {
      onCrop(detail) {
        let fileData = JSON.parse(hiddenInput.value)
        fileData['metadata']['crop'] = detail
        hiddenInput.value = JSON.stringify(fileData)
      }
    })
  })

form.html.erb:

<%= form_with model: @blog_form , url: user_blogs_path ,local: true do |f| %>

  <%  f.label :title %>
  <%= f.text_field :title %>

<%  f.label :content %>
<%= f.text_area :content %>

<%  f.label :user_id %>
<%= f.hidden_field :user_id, value: current_user.id %>

<%= f.fields_for  :photos, Photo.new do |photos_fileds|  %>

<%= photos_fileds.label :image , class: "form-control" %>
<%= photos_fileds.hidden_field :image,  class: "upload-data", value:
photos_fileds.object.cached_image_data %>
<%= photos_fileds.file_field  :image , class: "form-control  ", id: "select-files"%>

<img id="image" src="<%= photos_fileds.object.image_url(:medium) %>" height="300" class="rounded"  >

<% end %>

  <%= f.submit "create", class: "btn btn-primary" %>
 <% end %>

application.html.erb:

  <!DOCTYPE html>

    <title>Prottype2</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

   <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
   <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
   <%= javascript_pack_tag 'application' %>
   <%= javascript_pack_tag 'cropbox' %>
   <%= javascript_pack_tag 'fileUpload'%>

   <link href="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.css" rel="stylesheet" />
   <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css" rel="stylesheet"
 />

<%= notice %>

<%= alert %>

   <%= yield %>

I moved code position

application.html.erb:

<link href="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.css"
rel="stylesheet" />
<link
href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css"
rel="stylesheet" />

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track':
 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track':
'reload' %>
<%= javascript_pack_tag 'application' %>
<%= javascript_pack_tag 'app' %>
<%= javascript_pack_tag 'cropbox' %>
<%= javascript_pack_tag 'fileUpload'%>

And also I moved file input application.js to app.js


问:
Why is Functor in scala cats required
I have just started to learn Scala cats framework. I am reading Functor. I understood its features but I don't understand it's usage. Why should I use it if there is a map method already available in Functors like List, Option etc.

As an example,

```<code>val list = List(1, 2, 3)
Functor[List].map(list)(x => x * 2)
</code>```

But the same can be achieved with

```<code>list.map(x => x * 2)
</code>```

What do we get when we abstract the method map inside Functor trait.
Can someone please throw some light on it so that I understand its usage.

答:
The question is similar to why in OOP someone needs an interface (trait) while its implementations have the same methods.

Interface is an abstraction. Abstractions are useful. While programming we prefer to focus on significant things and ignore details that are currently not significant. Also programming with interfaces helps to decouple entities creating better architecture.

Interfaces (like Comparable, Iterable, Serializable etc.) is the way to describe behavior in OOP. Type classes (like Functor, Monad, Show, Read etc.) is the way to describe behavior in FP.

If you just want to map (or flatMap) over a list (or an Option) you don't need Functor. If you want to work with all mappable things you need Functor, if you want to work with all flatMappable things you need Monad etc.

Title: Why is Functor in scala cats required

Body:
I have just started to learn Scala cats framework. I am reading Functor. I understood its features but I don't understand it's usage. Why should I use it if there is a map method already available in Functors like List, Option etc.

As an example,

val list = List(1, 2, 3)
Functor[List].map(list)(x => x * 2)

But the same can be achieved with

list.map(x => x * 2)

What do we get when we abstract the method map inside Functor trait.
Can someone please throw some light on it so that I understand its usage.


问:
How make a SELECT between 2 dates( e.g. minutes) without having any datasets
I have no idea how to solve this:

I am struggling a bit - want to have a list in MySql/SQL or MariaDB of every minute (eg. timestamp) between two dates - without having an DB entry.

e.g.

```<code>StartDate 2020-05-30 08:01:00

EndDate 2020-05-30 12:01:00
</code>```

Now i need a listing of every minute between those both stamps

Like

```<code>--> Select Minutes between StartDate and Enddate
</code>```

Listing

```<code>2020-05-30 08:01:00

2020-05-30 08:02:00

2020-05-30 08:03:00

2020-05-30 08:04:00
</code>```

...

Thanks for your help

答:
You can use a recursive CTE:

```<code>with recursive ts as (
      select timestamp('2020-05-30 08:01:00') as ts
      union all
      select ts + interval 1 minute
      from ts
      where ts < '2020-05-30 12:01:00'
     )
select ts.ts
from ts;
</code>```

Here is a db<>fiddle.

Body:
I have no idea how to solve this:

I am struggling a bit - want to have a list in MySql/SQL or MariaDB of every minute (eg. timestamp) between two dates - without having an DB entry.

e.g.

StartDate 2020-05-30 08:01:00

EndDate 2020-05-30 12:01:00

Now i need a listing of every minute between those both stamps

Like

--> Select Minutes between StartDate and Enddate

Listing

2020-05-30 08:01:00

2020-05-30 08:02:00

2020-05-30 08:03:00

2020-05-30 08:04:00

...

Thanks for your help

Body:
You can use a recursive CTE:

with recursive ts as (
      select timestamp('2020-05-30 08:01:00') as ts
      union all
      select ts + interval 1 minute
      from ts
      where ts < '2020-05-30 12:01:00'
     )
select ts.ts
from ts;

Here is a db<>fiddle.


问:
How to use INITIAL_STATE injection token with dependencies?
I have a lazy-loaded module with a ngrx/store for feature StoreModule.forFeature('tasks', tasksReducer). I need to set the initial state for it, but the values that I need to set require a dependency injection to get them (those values are selected from another feature store in a service). I read that it's possible to use INITIAL_STATE injection token for this purpose. I tried the following:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '@realiecho/shared/shared.module';
import { tasksRoutes } from './tasks.routing';
import { TasksComponent } from './tasks/tasks.component';
import { INITIAL_STATE, StoreModule } from '@ngrx/store';
import { tasksReducer } from '@realiecho/main/tasks/store/tasks.reducer';
import { TasksEffects } from '@realiecho/main/tasks/store/tasks.effects';
import { TasksTableViewComponent } from '@realiecho/main/tasks/tasks/tasks-table-view/tasks-table-view.component';
import { EffectsModule } from '@ngrx/effects';

import { InitialStateService } from '@reali/web-core';

export const TASK_EFFECTS = [
    TasksEffects
];

@NgModule({
    imports: [
        CommonModule,
        tasksRoutes,
        SharedModule,
        EffectsModule.forFeature(TASK_EFFECTS),
        StoreModule.forFeature('tasks', tasksReducer),
    ],
    declarations: [
        TasksComponent,
        TasksTableViewComponent
    ],
    providers: [
        {
            provide: INITIAL_STATE,
            useFactory: getInitialState,
            deps: [InitialStateService]
        }
    ]
})
export class TasksModule {
}

export function getInitialState(initService: InitialStateService) {

     return initService.getInitState();

}

</code>```

but when I run it, the initial state is undefined regardless of what I return in initService.getInitState(), even if I return hardcoded constant.

答:
I had the same problem and unfortunately it isn't possible to use the INITIAL_STATE token for a feature module. I got the following answer via github:

The INITIAL_STATE token is only used to set the initial state of the root module.
  You could use the OnInitEffect lifecycle or the @ngrx/store/update-reducers action to dispatch a "set action" to set the state of the feature module in a reducer.

Github Link

Body:
I have a lazy-loaded module with a ngrx/store for feature StoreModule.forFeature('tasks', tasksReducer). I need to set the initial state for it, but the values that I need to set require a dependency injection to get them (those values are selected from another feature store in a service). I read that it's possible to use INITIAL_STATE injection token for this purpose. I tried the following:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '@realiecho/shared/shared.module';
import { tasksRoutes } from './tasks.routing';
import { TasksComponent } from './tasks/tasks.component';
import { INITIAL_STATE, StoreModule } from '@ngrx/store';
import { tasksReducer } from '@realiecho/main/tasks/store/tasks.reducer';
import { TasksEffects } from '@realiecho/main/tasks/store/tasks.effects';
import { TasksTableViewComponent } from '@realiecho/main/tasks/tasks/tasks-table-view/tasks-table-view.component';
import { EffectsModule } from '@ngrx/effects';

import { InitialStateService } from '@reali/web-core';

export const TASK_EFFECTS = [
    TasksEffects
];

@NgModule({
    imports: [
        CommonModule,
        tasksRoutes,
        SharedModule,
        EffectsModule.forFeature(TASK_EFFECTS),
        StoreModule.forFeature('tasks', tasksReducer),
    ],
    declarations: [
        TasksComponent,
        TasksTableViewComponent
    ],
    providers: [
        {
            provide: INITIAL_STATE,
            useFactory: getInitialState,
            deps: [InitialStateService]
        }
    ]
})
export class TasksModule {
}

export function getInitialState(initService: InitialStateService) {

     return initService.getInitState();

}

but when I run it, the initial state is undefined regardless of what I return in initService.getInitState(), even if I return hardcoded constant.


问:
Android Studio, how to see "tips(quick documentation)"?
I've been coding in Android Studio for a while now, be as in Kotlin and currently in Flutter. Whenever I am watching tutorials or lectures I see some-how they make a small window pop up that kinda shows some info. Here is a quick screenshot what I'm talking about:

I'm just bit curious about that because I know in Flutter you can press alt+enter to wrap certain widgets in other widgets. How do I get that window up?

Kind regards,

Mike

答: What you are looking for is called Quick Documentation. Access it via View -> Quick Documentation.


问:
node fetch nginx proxy 400 Bad Request
I was using request with a nginx proxy to send requests to an api.

This is the way I was sending the requests

```<code>const request = require('request');

request({
    url: 'https://google.com',
    proxy: 'https://my-proxy.com',
    strictSSL: false,
    tunnel: false,
}, (err, response, body) => {
    console.log(body)
});
</code>```

Everything was working great

Now, as request is deprecated I moved to node-fetch and https-proxy-agent

```<code>const fetch = require('node-fetch');
const HttpsProxyAgent = require('https-proxy-agent');

fetch('https://google.com', {
    agent: new HttpsProxyAgent('https://my-proxy.com'),
    method: 'GET'
})
.then(response => {
    console.log(response)
    return response.text()
})
.then(text => {
    console.log(text)
})
</code>```

And in this case the result is

```<code><html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.14.0 (Ubuntu)</center>
</body>
</html>
</code>```

On nginx logs side I have

```<code>client sent invalid request while reading client request line, client: xx.xx.xx.xx, server: my-proxy.com, request: "CONNECT google.com:443 HTTP/1.1"
</code>```

In case of I can resolve it updating my nginx config

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

  include       mime.types;
  default_type  application/octet-stream;

  sendfile        on;
  keepalive_timeout  65;

  gzip  on;

  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

  ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS;

  ssl_prefer_server_ciphers on;

  add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";

  ssl_dhparam dhparams.pem;

  server {
    listen 80;
    server_name my-proxy.com;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }
  }

  server {
    listen 443 ssl;
    server_name my-proxy.com;

    ssl_protocols TLSv1.1 TLSv1.2;
    # for ssl https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04

    location / {
        resolver 8.8.8.8;
        proxy_pass https://$http_host$uri$is_args$args;
    }
  }

  server {
    listen 80 default;
    server_name _;

    location / {
      return 403;
    }
  }

}
</code>```

I am using certbot for ssl

Pretty sure the problem comes from strictSSL but I can not found how to do it with node-fetch

答:
I installed squid proxy.

Really better than nginx for this type of work

Title: node fetch nginx proxy 400 Bad Request

Body:
I was using request with a nginx proxy to send requests to an api.

This is the way I was sending the requests

const request = require('request');

request({
    url: 'https://google.com',
    proxy: 'https://my-proxy.com',
    strictSSL: false,
    tunnel: false,
}, (err, response, body) => {
    console.log(body)
});

Everything was working great

Now, as request is deprecated I moved to node-fetch and https-proxy-agent

const fetch = require('node-fetch');
const HttpsProxyAgent = require('https-proxy-agent');

fetch('https://google.com', {
    agent: new HttpsProxyAgent('https://my-proxy.com'),
    method: 'GET'
})
.then(response => {
    console.log(response)
    return response.text()
})
.then(text => {
    console.log(text)
})

And in this case the result is

<title>400 Bad Request</title>

400 Bad Request

nginx/1.14.0 (Ubuntu)

On nginx logs side I have

client sent invalid request while reading client request line, client: xx.xx.xx.xx, server: my-proxy.com, request: "CONNECT google.com:443 HTTP/1.1"

In case of I can resolve it updating my nginx config

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

  include       mime.types;
  default_type  application/octet-stream;

  sendfile        on;
  keepalive_timeout  65;

  gzip  on;

  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

  ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS;

  ssl_prefer_server_ciphers on;

  add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";

  ssl_dhparam dhparams.pem;

  server {
    listen 80;
    server_name my-proxy.com;

    location / {
        resolver 8.8.8.8;
        proxy_pass http://$http_host$uri$is_args$args;
    }
  }

  server {
    listen 443 ssl;
    server_name my-proxy.com;

    ssl_protocols TLSv1.1 TLSv1.2;
    # for ssl https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04

    location / {
        resolver 8.8.8.8;
        proxy_pass https://$http_host$uri$is_args$args;
    }
  }

  server {
    listen 80 default;
    server_name _;

    location / {
      return 403;
    }
  }

}

I am using certbot for ssl

Pretty sure the problem comes from strictSSL but I can not found how to do it with node-fetch


问:
Accessing array elements within a vectorized function
I am trying to write a function which computes the Simpson integral for given inputs. Parts of these inputs can be in the form of a float or np.array.

Currently, my function is as follows:

```<code>s = np.array([0.2,0.3,0.4])

@np.vectorize
def recovery(s,R0,n):

    x = np.linspace(s,1,n)
    y = 1/(x*R0(x))
    ans = simp(y,x)

    return ans
</code>```

This works fine and returns:

```<code>array([a, b, c]) ## Where a, b and c are the correct answers
</code>```

However if I only want to access the first element in the array within the function, by:

```<code>return ans[0]
</code>```

I get the error message:

```<code>IndexError: invalid index to scalar variable
</code>```

I also get all different kinds of errors when trying to play around with the output "ans", e.g.:

```<code>return type(ans)
ValueError: invalid __array_struct__

return len(ans)
TypeError: object of type 'numpy.float64' has no len()
</code>```

The aim of the function is to return a float if the input s is a float, or an array if the s input is an np.ndarray.

I'm a complete python beginner so any help would be greatly appreciated.

答:
To access only the first element of the return array, you need to do so outside the function, not inside, because inside the function ans is still a scalar.

So while

```<code>return ans[0]
</code>```

doesn't work,

```<code>recovery(s,R0,n)[0]
</code>```

or

```<code>ans = recovery(s,R0,n)
ans[0]
</code>```

will work.

The confusing thing here is that the decorator @np.vectorize changes the function from one that maps scalars to scalars to one that maps vectors to vectors. But this manipulation is being done "outside" the function recovery; inside the original source code of the function, everything is as if it's still a function on scalars.

That's why when you wrote return ans[0], Python complained that you were trying to index a scalar; inside the function, ans is a scalar.

Body:
I am trying to write a function which computes the Simpson integral for given inputs. Parts of these inputs can be in the form of a float or np.array.

Currently, my function is as follows:

s = np.array([0.2,0.3,0.4])

@np.vectorize
def recovery(s,R0,n):

    x = np.linspace(s,1,n)
    y = 1/(x*R0(x))
    ans = simp(y,x)

    return ans

This works fine and returns:

array([a, b, c]) ## Where a, b and c are the correct answers

However if I only want to access the first element in the array within the function, by:

return ans[0]

I get the error message:

IndexError: invalid index to scalar variable

I also get all different kinds of errors when trying to play around with the output "ans", e.g.:

return type(ans)
ValueError: invalid __array_struct__

return len(ans)
TypeError: object of type 'numpy.float64' has no len()

The aim of the function is to return a float if the input s is a float, or an array if the s input is an np.ndarray.

I'm a complete python beginner so any help would be greatly appreciated.

Body:
To access only the first element of the return array, you need to do so outside the function, not inside, because inside the function ans is still a scalar.

So while

return ans[0]

doesn't work,

recovery(s,R0,n)[0]

or

ans = recovery(s,R0,n)
ans[0]

will work.

The confusing thing here is that the decorator @np.vectorize changes the function from one that maps scalars to scalars to one that maps vectors to vectors. But this manipulation is being done "outside" the function recovery; inside the original source code of the function, everything is as if it's still a function on scalars.

That's why when you wrote return ans[0], Python complained that you were trying to index a scalar; inside the function, ans is a scalar.


问:
How can I speed up the code that contains the sql query?
My dataframe contains about 650 thousand unique rows. For each row, I need to get a value from the database. I use a for loop, but the execution time is catastrophically long, about 25 hours. How can I speed up code execution? I assume that you need to parallelize the execution using joblib or numba. But the presence of an sql query inside the loop body is confusing.

```<code>for x in tqdm_notebook(range(len(table))):
    good = table.iloc[x, 0]
    store = table.iloc[x, 1]
    start = table.iloc[x, 6]

    query = f"""
    SELECT
            good_id,
            store_id,
            AVG(sale) AS avg_sale,
            SUM(sale) AS sum_sale,
            MAX(sale) AS max_sale,
            MIN(sale) AS min_sale
    FROM my_table
    WHERE good_id = {good}
    AND store_id = {store}
    AND date_id BETWEEN DATEADD(MONTH, -2, '{start}') AND DATEADD(MONTH, -1, '{start}')
    GROUP BY good_id, store_id
    """
    temp = pd.read_sql(query, connection)
    if not temp.empty:
        table.iloc[x, 13] = temp['avg_sale'].values
        table.iloc[x, 14] = temp['sum_sale'].values
        table.iloc[x, 15] = temp['max_sale'].values
        table.iloc[x, 16] = temp['min_sale'].values
</code>```

答:
For this you might just widen out your query and get all the (store,good,day) tuples, fetch partial aggregations for those, and and perform final filtering and aggregation in pandas.  Note you change AVG to COUNT(*) and calculate AVG in the final aggregate.

And a handy way to pass a list of parameters to SQL Server is with OPENJSON.  Just send a string parameter with a JSON array of scalars like

```<code>'[123,324,445,23,1322]'
</code>```

or

```<code>'["abd","def","d"]'
</code>```

So something like

```<code>SELECT
        good_id,
        store_id,
        date_id,
        count(*)  AS count_sale.
        SUM(sale) AS sum_sale,
        MAX(sale) AS max_sale,
        MIN(sale) AS min_sale
FROM my_table
WHERE good_id in (select cast(value as int) from openjson(?))
AND store_id in (select cast(value as int) from openjson(?))
AND date_id BETWEEN ? and ?
GROUP BY good_id, store_id, date_id
ORDER BY good_id, store_id, date_id
</code>```

Body:
My dataframe contains about 650 thousand unique rows. For each row, I need to get a value from the database. I use a for loop, but the execution time is catastrophically long, about 25 hours. How can I speed up code execution? I assume that you need to parallelize the execution using joblib or numba. But the presence of an sql query inside the loop body is confusing.

for x in tqdm_notebook(range(len(table))):
    good = table.iloc[x, 0]
    store = table.iloc[x, 1]
    start = table.iloc[x, 6]

    query = f"""
    SELECT
            good_id,
            store_id,
            AVG(sale) AS avg_sale,
            SUM(sale) AS sum_sale,
            MAX(sale) AS max_sale,
            MIN(sale) AS min_sale
    FROM my_table
    WHERE good_id = {good}
    AND store_id = {store}
    AND date_id BETWEEN DATEADD(MONTH, -2, '{start}') AND DATEADD(MONTH, -1, '{start}')
    GROUP BY good_id, store_id
    """
    temp = pd.read_sql(query, connection)
    if not temp.empty:
        table.iloc[x, 13] = temp['avg_sale'].values
        table.iloc[x, 14] = temp['sum_sale'].values
        table.iloc[x, 15] = temp['max_sale'].values
        table.iloc[x, 16] = temp['min_sale'].values

Body:
For this you might just widen out your query and get all the (store,good,day) tuples, fetch partial aggregations for those, and and perform final filtering and aggregation in pandas.  Note you change AVG to COUNT(*) and calculate AVG in the final aggregate.

And a handy way to pass a list of parameters to SQL Server is with OPENJSON.  Just send a string parameter with a JSON array of scalars like

'[123,324,445,23,1322]'

or

'["abd","def","d"]'

So something like

SELECT
        good_id,
        store_id,
        date_id,
        count(*)  AS count_sale.
        SUM(sale) AS sum_sale,
        MAX(sale) AS max_sale,
        MIN(sale) AS min_sale
FROM my_table
WHERE good_id in (select cast(value as int) from openjson(?))
AND store_id in (select cast(value as int) from openjson(?))
AND date_id BETWEEN ? and ?
GROUP BY good_id, store_id, date_id
ORDER BY good_id, store_id, date_id


问:
Automatic printing in C# with ProcessStartInfo cutting off bottom and top
I am using ProcessStartInfo to print my pdf file in my C# project in background. But the file that I printed is cutting off my top and bottom of the pdf file when printed. But when I print the same file by right clicking the pdf file it prints correctly.

Here is my code:

```<code>        System.Diagnostics.Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = filename; // use default app to execute verb

         //assert: can only go to local default printer
       startInfo.Verb = "Print"; //prints to default printer
        //try to keep Window hidden - work in background
        startInfo.UseShellExecute = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.CreateNoWindow = true;
        // set process to startInfo and execute start
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit(10000);
        process.CloseMainWindow();
        process.Close();
</code>```

答:
this is in milliseconds. so it's only going to wait 10 seconds. Is that long enough?

```<code>process.WaitForExit(10000);
</code>```

consider

```<code>process.WaitForExit();
</code>```

Body:
I am using ProcessStartInfo to print my pdf file in my C# project in background. But the file that I printed is cutting off my top and bottom of the pdf file when printed. But when I print the same file by right clicking the pdf file it prints correctly.

Here is my code:

        System.Diagnostics.Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = filename; // use default app to execute verb

         //assert: can only go to local default printer
       startInfo.Verb = "Print"; //prints to default printer
        //try to keep Window hidden - work in background
        startInfo.UseShellExecute = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.CreateNoWindow = true;
        // set process to startInfo and execute start
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit(10000);
        process.CloseMainWindow();
        process.Close();

Body:
this is in milliseconds. so it's only going to wait 10 seconds. Is that long enough?

process.WaitForExit(10000);

consider

process.WaitForExit();


问:
Vectorize code in function where loops use range in Python/NumPy
I have a function which is called many times in other functions. To improve computation I am trying to vectorize the code though I did not manage to do so in this particular case in which there are complex ranges involved. Does any of you see how it can be done in this specific case?

```<code>def growdh_no_bloom(mx, mn, daylen, baset):

    if mn == 0:
        mn = 0.01
    if mx == mn:
        mx += 0.01
    dt = mx - mn

    idl = int(np.floor(daylen))

    # calculate day time hourly temperatures
    t = np.zeros(24)
    t[0] = mn

    for hour in range(1, idl+1):
        t[hour] = dt * np.sin(np.pi/(daylen+4)*(hour)) + mn

    # calculate sunset time and temperature
    ts1 = dt*np.sin(np.pi/(daylen+4)*daylen) + mn
    if ts1 <= 0:
        ts1 = 0.01

    # calculate hourly temperatures (nighttime)
    count = 0
    for hour in range(idl + 1, 24):
        count += 1
        t[hour] = ts1-(ts1-mn)/(np.log(24-daylen))*np.log(count)

    # growing degree hours
    gdhour = 0
    for hour in range(0, 24):
        if t[hour] - baset > 0:
            gdhour += (t[hour] - baset)
    return gdhour
</code>```

Thanks in advance!

答:
```<code>from numba import jit
sig = np.random.randn(44100)
import numpy as np

vectorized = jit(growdh_no_bloom)
</code>```

Or simply put

```<code>import numba
import random

@numba.njit()
def growdh_no_bloom:
    for i in range(): #your for loop with range
</code>```

Numba is an open-source JIT compiler that translates a subset of
  Python and NumPy into fast machine code using LLVM, via the llvmlite
  Python package. It offers a range of options for parallelising Python
  code for CPUs and GPUs, often with only minor code changes.

Numba

In the case of this exception:

```<code>NumbaWarning: Compilation is falling back to object mode WITHOUT looplifting enabled because Function 'growdh_no_bloom' failed type inference due to: cannot determine Numba type of <class 'numba.dispatcher.LiftedLoop'>
</code>```

Get:

```<code>numba.__version__
</code>```

if it is 0.44.0 or later

```<code>pip install --upgrade numba==0.43.1
</code>```

Body:
I have a function which is called many times in other functions. To improve computation I am trying to vectorize the code though I did not manage to do so in this particular case in which there are complex ranges involved. Does any of you see how it can be done in this specific case?

def growdh_no_bloom(mx, mn, daylen, baset):

    if mn == 0:
        mn = 0.01
    if mx == mn:
        mx += 0.01
    dt = mx - mn

    idl = int(np.floor(daylen))

    # calculate day time hourly temperatures
    t = np.zeros(24)
    t[0] = mn

    for hour in range(1, idl+1):
        t[hour] = dt * np.sin(np.pi/(daylen+4)*(hour)) + mn

    # calculate sunset time and temperature
    ts1 = dt*np.sin(np.pi/(daylen+4)*daylen) + mn
    if ts1 <= 0:
        ts1 = 0.01

    # calculate hourly temperatures (nighttime)
    count = 0
    for hour in range(idl + 1, 24):
        count += 1
        t[hour] = ts1-(ts1-mn)/(np.log(24-daylen))*np.log(count)

    # growing degree hours
    gdhour = 0
    for hour in range(0, 24):
        if t[hour] - baset > 0:
            gdhour += (t[hour] - baset)
    return gdhour

Thanks in advance!

Body:
from numba import jit
sig = np.random.randn(44100)
import numpy as np

vectorized = jit(growdh_no_bloom)

Or simply put

import numba
import random

@numba.njit()
def growdh_no_bloom:
    for i in range(): #your for loop with range

Numba is an open-source JIT compiler that translates a subset of
  Python and NumPy into fast machine code using LLVM, via the llvmlite
  Python package. It offers a range of options for parallelising Python
  code for CPUs and GPUs, often with only minor code changes.

Numba

In the case of this exception:

NumbaWarning: Compilation is falling back to object mode WITHOUT looplifting enabled because Function 'growdh_no_bloom' failed type inference due to: cannot determine Numba type of <class 'numba.dispatcher.LiftedLoop'>

Get:

numba.__version__

if it is 0.44.0 or later

pip install --upgrade numba==0.43.1


问:
Entity Framework sum time grouped by a date
I have the following code and I get the error

Cannot implicitly convert type 'string' to 'long'

The error is coming from (i => i.TotalHours).

What am I doing wrong? Or what do I have to change?

Table

ViewModel

```<code>private void CalculateTime()
{
    var result = context.TimeSheets.GroupBy(o => o.StartDate)
                        .Select(g => new { StartDate = g.Key, total = g.Sum(i => i.TotalHours) });

    foreach (var group in result)
    {
        Console.WriteLine("StartDate = {0} TotalHours={1}", group.StartDate, group.total);
    }
}
</code>```

Class:

```<code>public class TimeSheet
{
    [Key]
    public int ID { get; set; }

    [StringLength(255)]
    public string MachineID { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime StartTime { get; set; }

    public DateTime EndDate { get; set; }

    public DateTime EndTime { get; set; }

    [StringLength(225)]
    public string WorkDescription { get; set; }

    [StringLength(225)]
    public string ClientName { get; set; }

    [StringLength(225)]
    public string UserName { get; set; }

    public string TotalHours { get; set; }
}
</code>```

答:
According to your error I believe you need either to change your TotalHours type to long or to make a type conversion, try:
(long)Convert.ToDouble(i.TotalHours)

```<code>var result = context.TimeSheets.GroupBy(o => o.StartDate)
                    .Select(g => new { StartDate = g.Key, total = g.Sum(i => (long)Convert.ToDouble(i.TotalHours)) });
</code>```

Body:
I have the following code and I get the error

Cannot implicitly convert type 'string' to 'long'

The error is coming from (i => i.TotalHours).

What am I doing wrong? Or what do I have to change?

Table

ViewModel

private void CalculateTime()
{
    var result = context.TimeSheets.GroupBy(o => o.StartDate)
                        .Select(g => new { StartDate = g.Key, total = g.Sum(i => i.TotalHours) });

    foreach (var group in result)
    {
        Console.WriteLine("StartDate = {0} TotalHours={1}", group.StartDate, group.total);
    }
}

Class:

public class TimeSheet
{
    [Key]
    public int ID { get; set; }

    [StringLength(255)]
    public string MachineID { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime StartTime { get; set; }

    public DateTime EndDate { get; set; }

    public DateTime EndTime { get; set; }

    [StringLength(225)]
    public string WorkDescription { get; set; }

    [StringLength(225)]
    public string ClientName { get; set; }

    [StringLength(225)]
    public string UserName { get; set; }

    public string TotalHours { get; set; }
}

Body:
According to your error I believe you need either to change your TotalHours type to long or to make a type conversion, try:
(long)Convert.ToDouble(i.TotalHours)

var result = context.TimeSheets.GroupBy(o => o.StartDate)
                    .Select(g => new { StartDate = g.Key, total = g.Sum(i => (long)Convert.ToDouble(i.TotalHours)) });


问:
Not all the props that get passed down is rendered anyone have an idea as to why
After I recieved the data from firebase and store it into the post state and I try to pass each data to another component one one data is been sent to the prop anyone have.

Any idea as to why?

```<code>import React, { Component } from 'react';
import BlogPost from './BlogPost'
import firebase from '../../config/fbConfig'

class BlogList extends Component {
    state = {
        posts: []
    }
    componentDidMount() {

        const db = firebase.firestore()
        db.collection('posts').get().then(snapshot => {
            snapshot.docs.forEach(post => {
                let id = post.id
                let postData = post.data()
                postData['id'] = id
                this.setState({
                    posts: [...this.state.posts, postData]
                })
            })

        })

    }

    render() {
        console.log(this.state.posts)

        return (
            <>
                {this.state.posts ?
                    this.state.posts.map(post =>
                        <BlogPost post={post} key={post.id} />
                    )
                    : <h1>loading</h1>}

            </>
        );
    }
}

export default BlogList;
</code>```

答:
The issue is in how you update the state, you must either use functional setState since you call setState within a loop and use this.state.data to update state, but state updates are not performed immediately but happen asynchronously

```<code>componentDidMount() {

    const db = firebase.firestore()
    db.collection('posts').get().then(snapshot => {
        snapshot.docs.forEach(post => {
            let id = post.id
            let postData = post.data()
            postData['id'] = id
            this.setState(prev => ({
                posts: [...prev.posts, postData]
            }))
        })

    })

}
</code>```

or even better update once all the data is available

```<code>componentDidMount() {

    const db = firebase.firestore()
    db.collection('posts').get().then(async snapshot => {
        const data = snapshot.docs.map(post => {
            let id = post.id
            let postData = post.data()
            postData['id'] = id
            return postData;
        });
        this.setState(prev => ({
            posts: [...prev.posts, ...data]
        }));

    })

}
</code>```

Body:
After I recieved the data from firebase and store it into the post state and I try to pass each data to another component one one data is been sent to the prop anyone have.

Any idea as to why?

import React, { Component } from 'react';
import BlogPost from './BlogPost'
import firebase from '../../config/fbConfig'

class BlogList extends Component {
    state = {
        posts: []
    }
    componentDidMount() {

        const db = firebase.firestore()
        db.collection('posts').get().then(snapshot => {
            snapshot.docs.forEach(post => {
                let id = post.id
                let postData = post.data()
                postData['id'] = id
                this.setState({
                    posts: [...this.state.posts, postData]
                })
            })

        })

    }

    render() {
        console.log(this.state.posts)

        return (
            <>
                {this.state.posts ?
                    this.state.posts.map(post =>
                        <BlogPost post={post} key={post.id} />
                    )
                    :
loading
}

            </>
        );
    }
}

export default BlogList;

Body:
The issue is in how you update the state, you must either use functional setState since you call setState within a loop and use this.state.data to update state, but state updates are not performed immediately but happen asynchronously

componentDidMount() {

    const db = firebase.firestore()
    db.collection('posts').get().then(snapshot => {
        snapshot.docs.forEach(post => {
            let id = post.id
            let postData = post.data()
            postData['id'] = id
            this.setState(prev => ({
                posts: [...prev.posts, postData]
            }))
        })

    })

}

or even better update once all the data is available

componentDidMount() {

    const db = firebase.firestore()
    db.collection('posts').get().then(async snapshot => {
        const data = snapshot.docs.map(post => {
            let id = post.id
            let postData = post.data()
            postData['id'] = id
            return postData;
        });
        this.setState(prev => ({
            posts: [...prev.posts, ...data]
        }));

    })

}


问:
getKey(alias, keyPassword) returns null value for secret key when calling from separate method
I am trying to retrieve a stored key in java key store. I have written the following code.    </p>

```<code>public class clientEncryptionUtility
{

    public static void generateKeyAndStoreOnKeyStore(String _keyStorePassword, String _keyStorePath, String _keyPassword, String keyAlias) throws Exception // take the keystore path, alias, password
    {
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        char[] keyStorePassword = _keyStorePassword.toCharArray();
        String path = _keyStorePath;
        FileInputStream fis = new FileInputStream(path);
        //load keystore
        keyStore.load(fis, keyStorePassword);
        //Loading the KeyStore object
        KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(keyStorePassword);

        //Generate the symmetric key for encryption
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();

        int keyBitSize = 128;

        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();   //Secret encryption key is genereated

        //setting the password for the key stored in keystore
        System.out.println("Algorithm used to generate key : "+secretKey.getAlgorithm());

        char[] keyPassword = _keyPassword.toCharArray();

        KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(keyPassword);

        KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);

        keyStore.setEntry(keyAlias, secretKeyEntry, entryPassword);
        SecretKey newSecretKey = (SecretKey) keyStore.getKey(keyAlias, keyPassword);
        String stringKey = newSecretKey.toString();
        System.out.println("The encryption key at the alias is: " + stringKey);
    }
    public static void getKeyFromKeyStore(String _keyStorePassword, String _keyStorePath, String keyAlias, String _keyPassword) throws Exception
    {
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        char[] keyStorePassword = _keyStorePassword.toCharArray();
        String path = _keyStorePath;
        FileInputStream fis = new FileInputStream(path);

        //load keystore
        keyStore.load(fis, keyStorePassword);
        char[] keyPassword = _keyPassword.toCharArray();
        SecretKey secretKey = (SecretKey) keyStore.getKey(keyAlias, keyPassword);
        // Key key = keyStore.getKey(keyAlias, keyPassword);
        String stringKey = secretKey.toString();
        System.out.println("The encryption key at the alias is: " + stringKey);

    }
}
</code>```

<p>-If I call the generateKeyAndStoreOnKeyStore() method, and store the key and retrieve the key in the same function, the key is retrieved. </p>

<p>-However if I do the same from another method getKeyFromKeyStore() wherein I am just trying to retrieve the key at the alias from the keystone, I get a nullPointerException. </p>

<p>-Where am I going wrong?</p>

答:
Unfortunately it's not clear from the javadocs that you must call the KeyStore.store(...) method to persist changes to the keystore. Once generateKeyAndStoreOnKeyStore() exits, the KeyStore instance created there goes out of scope and any unsaved changes made to the keystore disappear.

Call the KeyStore.store(...) method after making changes.

Body:
I am trying to retrieve a stored key in java key store. I have written the following code.

public class clientEncryptionUtility
{

    public static void generateKeyAndStoreOnKeyStore(String _keyStorePassword, String _keyStorePath, String _keyPassword, String keyAlias) throws Exception // take the keystore path, alias, password
    {
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        char[] keyStorePassword = _keyStorePassword.toCharArray();
        String path = _keyStorePath;
        FileInputStream fis = new FileInputStream(path);
        //load keystore
        keyStore.load(fis, keyStorePassword);
        //Loading the KeyStore object
        KeyStore.ProtectionParameter protectionParam = new KeyStore.PasswordProtection(keyStorePassword);

        //Generate the symmetric key for encryption
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();

        int keyBitSize = 128;

        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();   //Secret encryption key is genereated

        //setting the password for the key stored in keystore
        System.out.println("Algorithm used to generate key : "+secretKey.getAlgorithm());

        char[] keyPassword = _keyPassword.toCharArray();

        KeyStore.ProtectionParameter entryPassword = new KeyStore.PasswordProtection(keyPassword);

        KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);

        keyStore.setEntry(keyAlias, secretKeyEntry, entryPassword);
        SecretKey newSecretKey = (SecretKey) keyStore.getKey(keyAlias, keyPassword);
        String stringKey = newSecretKey.toString();
        System.out.println("The encryption key at the alias is: " + stringKey);
    }
    public static void getKeyFromKeyStore(String _keyStorePassword, String _keyStorePath, String keyAlias, String _keyPassword) throws Exception
    {
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        char[] keyStorePassword = _keyStorePassword.toCharArray();
        String path = _keyStorePath;
        FileInputStream fis = new FileInputStream(path);

        //load keystore
        keyStore.load(fis, keyStorePassword);
        char[] keyPassword = _keyPassword.toCharArray();
        SecretKey secretKey = (SecretKey) keyStore.getKey(keyAlias, keyPassword);
        // Key key = keyStore.getKey(keyAlias, keyPassword);
        String stringKey = secretKey.toString();
        System.out.println("The encryption key at the alias is: " + stringKey);

    }
}

-If I call the generateKeyAndStoreOnKeyStore() method, and store the key and retrieve the key in the same function, the key is retrieved.

-However if I do the same from another method getKeyFromKeyStore() wherein I am just trying to retrieve the key at the alias from the keystone, I get a nullPointerException.

-Where am I going wrong?


问:
Getting cover from flac in iOS with AVFoundation and AudioToolbox
With the help of this SO, I successfully read metadata from my flac file. It seems however that the metadata is in one block, and the cover image is in a different. With the help of metaflac --list my.flac, I've located that there is at least one block with an image. I can't seem to figure out how to extract these.

答:
I ended up doing some very low level metadata block reading by hand, instead of relying on any libs.

My less than pretty solution can be found here: https://github.com/Human-Entertainment/Listen-in-Place/blob/db7dde9195b162dedd976b22f295a9bbd5ab3b14/Listen%20in%20Place/Player.swift#L24-L77, i'm contemplating making a SwiftPM library, for the sole purpose of reading the metadata blocks, but for now, this'll suffice.


问:
result of selecting field names from table with group by
Say you're given the following table called Customers:

```<code>+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Hardik   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Ramesh   |  25 | Ahmedabad |  6500.00 |
|  5 | Hardik   |  27 | Delhi     |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Ramesh   |  24 | Ahmedabad | 10000.00 |
+----+----------+-----+-----------+----------+
</code>```

A lot of resources explaining group by statements would use an example like:
SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME; where the thing being 'selected' other than the field being 'grouped by' is a function like count or sum. But what happens if you did something like SELECT NAME, ADDRESS FROM CUSTOMERS GROUP BY NAME; - how exactly would the addresses be grouped together in a single record with the name. I know I can run this and find out the answer, but I want to understand the general logic - if anyone could assist that would be very much appreciated.

EDIT ANOTHER QUESTION:
In the new table above, if I did SELECT NAME, ADDRESS, group_concat(salary) FROM CUSTOMERS GROUP BY NAME; would this be ok, seeing as how the addresses are the same for each name?

答:
If you say SELECT NAME, ADDRESS FROM CUSTOMERS GROUP BY NAME, you will get an error asking you to put an aggregation function around the ADDRESS column. For instance, you could write

```<code>SELECT NAME, MAX(ADDRESS) FROM CUSTOMERS GROUP BY NAME
</code>```

Body:
Say you're given the following table called Customers:

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Hardik   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Ramesh   |  25 | Ahmedabad |  6500.00 |
|  5 | Hardik   |  27 | Delhi     |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Ramesh   |  24 | Ahmedabad | 10000.00 |
+----+----------+-----+-----------+----------+

A lot of resources explaining group by statements would use an example like:
SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY NAME; where the thing being 'selected' other than the field being 'grouped by' is a function like count or sum. But what happens if you did something like SELECT NAME, ADDRESS FROM CUSTOMERS GROUP BY NAME; - how exactly would the addresses be grouped together in a single record with the name. I know I can run this and find out the answer, but I want to understand the general logic - if anyone could assist that would be very much appreciated.

EDIT ANOTHER QUESTION:
In the new table above, if I did SELECT NAME, ADDRESS, group_concat(salary) FROM CUSTOMERS GROUP BY NAME; would this be ok, seeing as how the addresses are the same for each name?

Body:
If you say SELECT NAME, ADDRESS FROM CUSTOMERS GROUP BY NAME, you will get an error asking you to put an aggregation function around the ADDRESS column. For instance, you could write

SELECT NAME, MAX(ADDRESS) FROM CUSTOMERS GROUP BY NAME


问:
How to close a WCF service cleanly without cluttering your code?
Reading the accepted answer to this question, apparently the right way to use a WCF service is like this (copied with some modification)

```<code>// create your client
CustomerClient channel = CreateCustomerClient();

try
{
   // use it
   channel.GetCustomerDetails() ....

   (more calls)

   // close it
   channel.Close();
}
catch(CommunicationException commEx)
{
   // a CommunicationException probably indicates something went wrong
   // when closing the channel --> abort it
   channel.Abort();
}
</code>```

However, if my program use the service many times, this will clutter my code a lot. What is the clean way to do this without cluttering my code? Some ideas using lambda expression come to my mind, but so far they don't feel quite clean.

答:
The post you referenced has an Answer which references a post by Marc Gravell which uses an extension method so your WCF calls can be made to look something like this:</p>

```<code>using (var client = new Proxy().Wrap()) {
    client.BaseObject.SomeMethod();
}
</code>```

Body:
Reading the accepted answer to this question, apparently the right way to use a WCF service is like this (copied with some modification)

// create your client
CustomerClient channel = CreateCustomerClient();

try
{
   // use it
   channel.GetCustomerDetails() ....

   (more calls)

   // close it
   channel.Close();
}
catch(CommunicationException commEx)
{
   // a CommunicationException probably indicates something went wrong
   // when closing the channel --> abort it
   channel.Abort();
}

However, if my program use the service many times, this will clutter my code a lot. What is the clean way to do this without cluttering my code? Some ideas using lambda expression come to my mind, but so far they don't feel quite clean.

Body:
The post you referenced has an Answer which references a post by Marc Gravell which uses an extension method so your WCF calls can be made to look something like this:

using (var client = new Proxy().Wrap()) {
    client.BaseObject.SomeMethod();
}


问:
How would I go about setting up this modal to toggle?
I'm trying to get an editModal and a detailsModal to open on click. I set up actions and reducers for the modal so it can be stored in the global state and it works, but currently the modals are set to open automatically and I cannot close them. I believe it's something wrong with my logic, but it seems like it would be rather straightforward. Does anyone have any tips on how to complete this?

modalReducer.js

```<code>import { OPEN_MODAL } from "../actions/types";

const initialState = {
  modal: false,
};

export default function (state = initialState, action) {
  switch (action.type) {
    case OPEN_MODAL:
      return {
        ...state,
        modal: false,
      };
    default:
      return state;
  }
}
</code>```

ClientEditModal.js

```<code>import React, { Component } from "react";
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input,
} from "reactstrap";
import { connect } from "react-redux";
import { editClient } from "../actions/clientActions";
import { openModal } from "../actions/modalActions";
import PropTypes from "prop-types";

class ClientEditModal extends Component {
  componentDidMount() {
    this.props.editClient();
    this.props.openModal();
  }

  toggle = () => {
    this.setState({
      modal: !this.props.modal,
    });
  };

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onSubmit = (e) => {
    e.preventDefault();

    // Close modal
    this.toggle();
  };

  displayClient = (clients, _id) => {
    return (
      <FormGroup key={_id} timeout={500} classNames="fade">
        <Label for="name"> Name </Label>
        <Input
          type="text"
          name="name"
          id="client"
          value={clients.name}
          onChange={this.onChange}
        ></Input>

        <Label for="email"> Email </Label>
        <Input
          type="text"
          name="email"
          id="client"
          value={clients.email}
          onChange={this.onChange}
        ></Input>

        <Label for="number"> Number </Label>
        <Input
          type="text"
          name="number"
          id="number"
          value={clients.number}
          onChange={this.onChange}
        ></Input>

        <Button color="dark" style={{ marginTop: "2rem" }} block>
          Submit Client Edit
        </Button>
      </FormGroup>
    );
  };

  render() {
    const { clients } = this.props.client;
    return (
      // Split button into separate component
      <div>
        <Button
          color="dark"
          style={{ marginBottom: "2rem", marginLeft: "1rem" }}
          onClick={this.toggle}
        >
          Edit
        </Button>

        <Modal
          isOpen={this.props.modal}
          toggle={this.toggle}
          style={{ padding: "50px" }}
        >
          <ModalHeader toggle={this.toggle}> Edit</ModalHeader>
          <ModalBody>
            <Form onSubmit={this.onSubmit}>
              {clients.map(this.displayClient)}
            </Form>
          </ModalBody>
        </Modal>
      </div>
    );
  }
}

ClientEditModal.propTypes = {
  editClient: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
  modal: state.modal,
});

export default connect(mapStateToProps, { editClient, openModal })(
  ClientEditModal
);

</code>```

modalActions.js

```<code>import { OPEN_MODAL } from "./types";

export const openModal = () => {
  return {
    type: OPEN_MODAL,
  };
};
</code>```

答:
The main issue is - your toggle function, !this.props.modal will invert the value of modal and the component always holds the value of true.

So, one option is to maintain another action for closing modal.

See the updated code snippets below.

Reducer

import { OPEN_MODAL } from "../actions/types";

const initialState = {
  modal: false,
};

export default function (state = initialState, action) {
  switch (action.type) {
    case OPEN_MODAL:
      return {
        ...state,
        modal: false,
      };
    case CLOSE_MODAL:
      return {
        ...state,
        modal: true,
      };
    default:
      return state;
  }
}
```

<p><strong>Actions</strong></p>

<pre class="lang-js prettyprint-override"><code>import { OPEN_MODAL } from "./types";

export const openModal = () => {
  return {
    type: OPEN_MODAL,
  };
};
export const closeModal = () => {
  return {
    type: CLOSE_MODAL,
  };
};
</code>```

ClientModal.js

import React, { Component } from "react";
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input,
} from "reactstrap";
import { connect } from "react-redux";
import { editClient } from "../actions/clientActions";
import { openModal } from "../actions/modalActions";
import PropTypes from "prop-types";

class ClientEditModal extends Component {
  componentDidMount() {
    this.props.editClient();
    this.props.openModal();
  }

  toggle = () => {
    // this.setState({ //<---- setstate is not required as once the state in the store is updated, then the component is re-rendered automatically
    //   modal: !this.props.modal, //<---- once toggle is executed - it is always true
    //});
   this.props.closeModal()
  };

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onSubmit = (e) => {
    e.preventDefault();

    // Close modal
    this.toggle();
  };

  displayClient = (clients, _id) => {
    return (
      <FormGroup key={_id} timeout={500} classNames="fade">
         Name
        <Input
          type="text"
          name="name"
          id="client"
          value={clients.name}
          onChange={this.onChange}
        ></Input>

         Email
        <Input
          type="text"
          name="email"
          id="client"
          value={clients.email}
          onChange={this.onChange}
        ></Input>

         Number
        <Input
          type="text"
          name="number"
          id="number"
          value={clients.number}
          onChange={this.onChange}
        ></Input>

        <Button color="dark" style={{ marginTop: "2rem" }} block>
          Submit Client Edit
        </Button>
      </FormGroup>
    );
  };

  render() {
    const { clients } = this.props.client;
    return (
      // Split button into separate component

        <Button
          color="dark"
          style={{ marginBottom: "2rem", marginLeft: "1rem" }}
          onClick={this.toggle}
        >
          Edit
        </Button>

        <Modal
          isOpen={this.props.modal}
          toggle={this.toggle}
          style={{ padding: "50px" }}
        >
          <ModalHeader toggle={this.toggle}> Edit</ModalHeader>
          <ModalBody>
            <Form onSubmit={this.onSubmit}>
              {clients.map(this.displayClient)}
            </Form>
          </ModalBody>
        </Modal>

    );
  }
}

ClientEditModal.propTypes = {
  editClient: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
  modal: state.modal,
});

export default connect(mapStateToProps, { editClient, openModal, closeModal })(
  ClientEditModal
);
```

Body:
I'm trying to get an editModal and a detailsModal to open on click. I set up actions and reducers for the modal so it can be stored in the global state and it works, but currently the modals are set to open automatically and I cannot close them. I believe it's something wrong with my logic, but it seems like it would be rather straightforward. Does anyone have any tips on how to complete this?

modalReducer.js

import { OPEN_MODAL } from "../actions/types";

const initialState = {
  modal: false,
};

export default function (state = initialState, action) {
  switch (action.type) {
    case OPEN_MODAL:
      return {
        ...state,
        modal: false,
      };
    default:
      return state;
  }
}

ClientEditModal.js

import React, { Component } from "react";
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input,
} from "reactstrap";
import { connect } from "react-redux";
import { editClient } from "../actions/clientActions";
import { openModal } from "../actions/modalActions";
import PropTypes from "prop-types";

class ClientEditModal extends Component {
  componentDidMount() {
    this.props.editClient();
    this.props.openModal();
  }

  toggle = () => {
    this.setState({
      modal: !this.props.modal,
    });
  };

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onSubmit = (e) => {
    e.preventDefault();

    // Close modal
    this.toggle();
  };

  displayClient = (clients, _id) => {
    return (
      <FormGroup key={_id} timeout={500} classNames="fade">
         Name
        <Input
          type="text"
          name="name"
          id="client"
          value={clients.name}
          onChange={this.onChange}
        ></Input>

         Email
        <Input
          type="text"
          name="email"
          id="client"
          value={clients.email}
          onChange={this.onChange}
        ></Input>

         Number
        <Input
          type="text"
          name="number"
          id="number"
          value={clients.number}
          onChange={this.onChange}
        ></Input>

        <Button color="dark" style={{ marginTop: "2rem" }} block>
          Submit Client Edit
        </Button>
      </FormGroup>
    );
  };

  render() {
    const { clients } = this.props.client;
    return (
      // Split button into separate component

        <Button
          color="dark"
          style={{ marginBottom: "2rem", marginLeft: "1rem" }}
          onClick={this.toggle}
        >
          Edit
        </Button>

        <Modal
          isOpen={this.props.modal}
          toggle={this.toggle}
          style={{ padding: "50px" }}
        >
          <ModalHeader toggle={this.toggle}> Edit</ModalHeader>
          <ModalBody>
            <Form onSubmit={this.onSubmit}>
              {clients.map(this.displayClient)}
            </Form>
          </ModalBody>
        </Modal>

    );
  }
}

ClientEditModal.propTypes = {
  editClient: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
  modal: state.modal,
});

export default connect(mapStateToProps, { editClient, openModal })(
  ClientEditModal
);

modalActions.js

import { OPEN_MODAL } from "./types";

export const openModal = () => {
  return {
    type: OPEN_MODAL,
  };
};

Body:
The main issue is - your toggle function, !this.props.modal will invert the value of modal and the component always holds the value of true.

So, one option is to maintain another action for closing modal.

See the updated code snippets below.

Reducer

import { OPEN_MODAL } from "../actions/types";

const initialState = {
  modal: false,
};

export default function (state = initialState, action) {
  switch (action.type) {
    case OPEN_MODAL:
      return {
        ...state,
        modal: false,
      };
    case CLOSE_MODAL:
      return {
        ...state,
        modal: true,
      };
    default:
      return state;
  }
}

Actions

import { OPEN_MODAL } from "./types";

export const openModal = () => {
  return {
    type: OPEN_MODAL,
  };
};
export const closeModal = () => {
  return {
    type: CLOSE_MODAL,
  };
};

ClientModal.js

import React, { Component } from "react";
import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input,
} from "reactstrap";
import { connect } from "react-redux";
import { editClient } from "../actions/clientActions";
import { openModal } from "../actions/modalActions";
import PropTypes from "prop-types";

class ClientEditModal extends Component {
  componentDidMount() {
    this.props.editClient();
    this.props.openModal();
  }

  toggle = () => {
    // this.setState({ //<---- setstate is not required as once the state in the store is updated, then the component is re-rendered automatically
    //   modal: !this.props.modal, //<---- once toggle is executed - it is always true
    //});
   this.props.closeModal()
  };

  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onSubmit = (e) => {
    e.preventDefault();

    // Close modal
    this.toggle();
  };

  displayClient = (clients, _id) => {
    return (
      <FormGroup key={_id} timeout={500} classNames="fade">
        <Label for="name"> Name </Label>
        <Input
          type="text"
          name="name"
          id="client"
          value={clients.name}
          onChange={this.onChange}
        ></Input>

        <Label for="email"> Email </Label>
        <Input
          type="text"
          name="email"
          id="client"
          value={clients.email}
          onChange={this.onChange}
        ></Input>

        <Label for="number"> Number </Label>
        <Input
          type="text"
          name="number"
          id="number"
          value={clients.number}
          onChange={this.onChange}
        ></Input>

        <Button color="dark" style={{ marginTop: "2rem" }} block>
          Submit Client Edit
        </Button>
      </FormGroup>
    );
  };

  render() {
    const { clients } = this.props.client;
    return (
      // Split button into separate component
      <div>
        <Button
          color="dark"
          style={{ marginBottom: "2rem", marginLeft: "1rem" }}
          onClick={this.toggle}
        >
          Edit
        </Button>

        <Modal
          isOpen={this.props.modal}
          toggle={this.toggle}
          style={{ padding: "50px" }}
        >
          <ModalHeader toggle={this.toggle}> Edit</ModalHeader>
          <ModalBody>
            <Form onSubmit={this.onSubmit}>
              {clients.map(this.displayClient)}
            </Form>
          </ModalBody>
        </Modal>
      </div>
    );
  }
}

ClientEditModal.propTypes = {
  editClient: PropTypes.func.isRequired,
  client: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  client: state.client,
  modal: state.modal,
});

export default connect(mapStateToProps, { editClient, openModal, closeModal })(
  ClientEditModal
);


问:
How to distributed unequal width items to fulfill the container with flexbox
I am having a requirement that displaying the dynamic unequal width items in a container but it needs to fulfill the parent container. The item is dynamic so we can not know how long it is. If there is no room in the row, we need to display that item in the next row but the existing rows must be distributed equally to fulfill the container's width. Something like this:

My expectation:

What I did is create a container with display: flex and put child items inside with their's width fit the content inside. The items can be displayed in the next row if there is no room for it but I have no clue how to distributed existing items to fulfill the whole row?

Code:

.container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  width: 350px;
  border-style: dotted;
}
.item {
  background-color: coral;
  padding: 10px 1em;
  margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item">Lorem ipsum</div>
  <div class="item">Lorem ipsum dolor</div>
  <div class="item">adipiscing</div>
  <div class="item">consectetur adipiscing elit</div>
  <div class="item">Lorem ipsum dolor sit amet</div>
  <div class="item">Lorem ipsum dolor</div>
</div></code>```

I just wonder is there any flexbox's CSS property to solve this problem?

答:
some extra CSS for the behavior of the content and the children could be used :

```<code>  flex:1 0 auto;/* make it stretch as much as possible*/
  max-width:calc(100% - 10px);/* do not let it be bigger than container width minus margin */
  white-space: pre-wrap;/* keep on a single line as much as possible */
</code>```

Possible demo

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  gap: 10px;/*NOTICE: understood by Firefox at the moment */
  flex-wrap: wrap;
  width: 350px;
  border-style: dotted;
}
.item {
  background-color: coral;
  padding: 10px 1em;
  margin: 5px;
  /* update a few behaviors */
  flex:1 0 auto;
  max-width:calc(100% - 10px);/* 10px is right + left margin */
  white-space: pre-wrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item">Lorem ipsum</div>
  <div class="item">Lorem ipsum dolor</div>
  <div class="item">adipiscing</div>
  <div class="item">consectetur adipiscing elit</div>
  <div class="item">Lorem ipsum dolor sit amet</div>
  <div class="item">Lorem ipsum dolor</div>
  <div class="item">Lorem ipsum dolor</div>
  <p class="item">Pellentesque habitant morbi tristique senectus et netus et  netus et malesuada  ac turpis egestas.</p>
</div></code>```

Body:
I am having a requirement that displaying the dynamic unequal width items in a container but it needs to fulfill the parent container. The item is dynamic so we can not know how long it is. If there is no room in the row, we need to display that item in the next row but the existing rows must be distributed equally to fulfill the container's width. Something like this:

My expectation:

What I did is create a container with display: flex and put child items inside with their's width fit the content inside. The items can be displayed in the next row if there is no room for it but I have no clue how to distributed existing items to fulfill the whole row?

Code:

.container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  width: 350px;
  border-style: dotted;
}
.item {
  background-color: coral;
  padding: 10px 1em;
  margin: 5px;
}

Lorem ipsum

Lorem ipsum dolor

adipiscing

consectetur adipiscing elit

Lorem ipsum dolor sit amet

Lorem ipsum dolor

I just wonder is there any flexbox's CSS property to solve this problem?

Body:
some extra CSS for the behavior of the content and the children could be used :

  flex:1 0 auto;/* make it stretch as much as possible*/
  max-width:calc(100% - 10px);/* do not let it be bigger than container width minus margin */
  white-space: pre-wrap;/* keep on a single line as much as possible */

Possible demo

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  gap: 10px;/*NOTICE: understood by Firefox at the moment */
  flex-wrap: wrap;
  width: 350px;
  border-style: dotted;
}
.item {
  background-color: coral;
  padding: 10px 1em;
  margin: 5px;
  /* update a few behaviors */
  flex:1 0 auto;
  max-width:calc(100% - 10px);/* 10px is right + left margin */
  white-space: pre-wrap;
}

<div class="container">
  <div class="item">Lorem ipsum</div>
  <div class="item">Lorem ipsum dolor</div>
  <div class="item">adipiscing</div>
  <div class="item">consectetur adipiscing elit</div>
  <div class="item">Lorem ipsum dolor sit amet</div>
  <div class="item">Lorem ipsum dolor</div>
  <div class="item">Lorem ipsum dolor</div>
  <p class="item">Pellentesque habitant morbi tristique senectus et netus et  netus et malesuada  ac turpis egestas.</p>
</div>


问:
In Java, how to print divisor numbers?
I want to print the divisors of a user input value between 1 and 10000.

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

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }

        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}
</code>```

I have problem here with command System.out.println("loop);.
  I want to print all the divisors, like if a user inserted 10, then the
  output should show something like:

!

```<code>Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4
</code>```

!
!

But the current output is:

!

```<code>Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4
</code>```

!
!

so how to print loop only when the (Range % loop == 0) is true??

答:
just add brackets to if condition the  code can be as follows</p>

```<code>  for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0){
                Divisor++;
                System.out.println("loop);
               }
            }
</code>```

Title: In Java, how to print divisor numbers?

Body:
I want to print the divisors of a user input value between 1 and 10000.

import java.util.Scanner;

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }

        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}

I have problem here with command System.out.println("loop);.
  I want to print all the divisors, like if a user inserted 10, then the
  output should show something like:

!

Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4

!
!

But the current output is:

!

Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4

!
!

so how to print loop only when the (Range % loop == 0) is true??

Body:
just add brackets to if condition the  code can be as follows

  for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0){
                Divisor++;
                System.out.println("loop);
               }
            }


问:
Should one table reference every other table
I'm working on an application that routinely gathers information from a large number of websites and saves it to a mysql database with a table for each site. The idea is to create a sort of customizable news feed.

stackoverflow_table(id, url, title, date)

reddit_table(id, title, url, author, date)

github_commit_table(id,
commit_message, author, repository,
branch, date)

twitter_table(id, tweet, author, url, date)

etc...

I want the ability to request any number of news items and filter out certain sites too. As an example:

Show newest 100 items but exclude items from Twitter and GitHub.

It seems like the best way to handle this is to create a table that just has foreign keys and website names.

master_table(id, website, date, foreign_key)

and I can just query the foreign ids I need from this table.

Am I going about this horribly wrong?

答:
I've actually been working on a similar site.  Not for other sites, but a kind of Facebook-like site for a niche community with newsfeeds from various sources.  I've been pondering this question very heavily the past couple of weeks.

One issue, probably not gamebreaking, but still an issue for me, is that since your foreign_key column isn't literally a foreign key due to referencing multiple tables, so it can't get the benefits from things such as referential integrity enforcement.

What I'm considering is making a GUID table that serves as the source of ids for all of the other tables, and having a table specifically dedicated to the news feed.  It might be defined as something like:

```<code>CREATE TABLE sources (
  id INTEGER AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(20),
  url VARCHAR(50) );

INSERT INTO sources (name, url) VALUES ('Stack Overflow', 'http://stackoverflow.com');
INSERT INTO sources (name, url) VALUES ('Reddit', 'http://www.reddit.com');
INSERT INTO sources (name, url) VALUES ('Github', 'http://github.com');
INSERT INTO sources (name, url) VALUES ('Twitter', 'http://twitter.com');
/* And so on... */

CREATE TABLE newsfeed (
  guid INTEGER PRIMARY KEY,  -- Note: NOT auto_increment!
  source_id INTEGER NOT NULL,
  timestamp DATETIME NOT NULL,
  text VARCHAR(256),
  ref_id INTEGER NOT NULL,
  FOREIGN KEY (source_id) references sources (id) );
</code>```

You could still store information about site postings in their own tables, but now you're just referencing the one newsfeed table for what to actually display on the page, with the ref_id being a pointer to individual source tables if someone wants to deep-dive into the information.  It's still not ideal because ref_id still isn't a true foreign key, but it's arguably a little better.

You might even want to do something like this instead of ref_id:

```<code>data TEXT,
</code>```

with the contents of that column for any given entry a source-specific data payload.  For example, for Github posts, it could contain a JSON string such as:

```<code>{"commit_message":"Updated global variable namespace.",
  "author":"King Skippus","repository":"Ibuware"}
</code>```

Body:
I've actually been working on a similar site.  Not for other sites, but a kind of Facebook-like site for a niche community with newsfeeds from various sources.  I've been pondering this question very heavily the past couple of weeks.

One issue, probably not gamebreaking, but still an issue for me, is that since your foreign_key column isn't literally a foreign key due to referencing multiple tables, so it can't get the benefits from things such as referential integrity enforcement.

What I'm considering is making a GUID table that serves as the source of ids for all of the other tables, and having a table specifically dedicated to the news feed.  It might be defined as something like:

CREATE TABLE sources (
  id INTEGER AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(20),
  url VARCHAR(50) );

INSERT INTO sources (name, url) VALUES ('Stack Overflow', 'http://stackoverflow.com');
INSERT INTO sources (name, url) VALUES ('Reddit', 'http://www.reddit.com');
INSERT INTO sources (name, url) VALUES ('Github', 'http://github.com');
INSERT INTO sources (name, url) VALUES ('Twitter', 'http://twitter.com');
/* And so on... */

CREATE TABLE newsfeed (
  guid INTEGER PRIMARY KEY,  -- Note: NOT auto_increment!
  source_id INTEGER NOT NULL,
  timestamp DATETIME NOT NULL,
  text VARCHAR(256),
  ref_id INTEGER NOT NULL,
  FOREIGN KEY (source_id) references sources (id) );

You could still store information about site postings in their own tables, but now you're just referencing the one newsfeed table for what to actually display on the page, with the ref_id being a pointer to individual source tables if someone wants to deep-dive into the information.  It's still not ideal because ref_id still isn't a true foreign key, but it's arguably a little better.

You might even want to do something like this instead of ref_id:

data TEXT,

with the contents of that column for any given entry a source-specific data payload.  For example, for Github posts, it could contain a JSON string such as:

{"commit_message":"Updated global variable namespace.",
  "author":"King Skippus","repository":"Ibuware"}