问:
Finding biggest binary gap
I have to find the binary gap for an integer number.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example: N = 1041
binary:10000010001
Result: 5 (5 zeros surrounded by ones)

Below is my code, although bin_no[22] is 1 but it never goes inside if statement.

```<code>def solution(N):
    bin_no = f'{N:32b}'
    print(len(bin_no))
    count = []

    for i in range(len(bin_no)):
        if bin_no[i] == 1:
            count[i] = 0
            j=i
            while(bin_no[j+1] != 1):
                count[i] +=1
                j +=1
            print (count[i])

print(solution(529))
</code>```

答:
You can split zeroes with '1' and get groups of zeroes as a list. Find the longest and it's done!

```<code>def solution(N):
    bin = f'{N:b}'  # for 32-bit representation with leading zeroes use f'{N:#032b}'
    splitted = bin.split('1')
    m = max(splitted, key=len)
    return len(m)
</code>```

So it goes like this:

```<code>1041 -> '10000010001' -> ['', '00000', '000', ''] -> '00000' -> 5
</code>```

The code can be easily changed to ignore leading and trailing group of zeroes if that's your case.

Title: Finding biggest binary gap

Body:
I have to find the binary gap for an integer number.

A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example: N = 1041
binary:10000010001
Result: 5 (5 zeros surrounded by ones)

Below is my code, although bin_no[22] is 1 but it never goes inside if statement.

def solution(N):
    bin_no = f'{N:32b}'
    print(len(bin_no))
    count = []

    for i in range(len(bin_no)):
        if bin_no[i] == 1:
            count[i] = 0
            j=i
            while(bin_no[j+1] != 1):
                count[i] +=1
                j +=1
            print (count[i])

print(solution(529))

Body:
You can split zeroes with '1' and get groups of zeroes as a list. Find the longest and it's done!

def solution(N):
    bin = f'{N:b}'  # for 32-bit representation with leading zeroes use f'{N:#032b}'
    splitted = bin.split('1')
    m = max(splitted, key=len)
    return len(m)

So it goes like this:

1041 -> '10000010001' -> ['', '00000', '000', ''] -> '00000' -> 5

The code can be easily changed to ignore leading and trailing group of zeroes if that's your case.


来源: stackexchange

问:
Clearing the memory or files after opening using a macro
I have a VBA macro that open files in a folder, download data from an add-in, save and close.
This runs fine, but after 10 or 15 files, it gets quite slow. I think it is because Excel still keep previously opened files in the memory. I knew this because I saw the already-opened-and-closed files on the left panel as in the photo below. (the photo is to show where the panel is, I know there is only one file opened with the sheets, but you know what I mean).

My question is: is there a line of code that refresh or clear this temporary memory?

Here is my code:

```<code>'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim filename As String
Dim path_to_save As String
Dim FldrPicker As FileDialog
Dim w As Long
Dim StartTime As Double
Dim SecondsElapsed As Double
Dim oFile       As Object
Dim oFSO        As Object
Dim oFolder     As Object
Dim oFiles      As Object

Application.ScreenUpdating = False
StartTime = Timer

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Assign the folder to oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(myPath)
    Set oFiles = oFolder.Files
    If oFiles.Count = 0 Then GoTo ResetSettings

For Each oFile In oFolder.Files
    'Set variable equal to opened workbook
    myFile = oFile.Name
    Set wb = Workbooks.Open(filename:=myPath & myFile)
    Set cmd = Application.CommandBars("Cell").Controls("Refresh All")
    cmd.Execute
    DoEvents

    'Ensure Workbook has opened before moving on to next line of code

    wb.Close savechanges:=True

    'Ensure Workbook has closed before moving on to next line of code
    DoEvents
Next 'oFile

SecondsElapsed = Timer - StartTime
MsgBox "This code ran successfully in " & SecondsElapsed
    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

ResetSettings:
  'Reset Macro Optimization Settings
    Application.ScreenUpdating = True
End Sub
</code>```

答:
What about add:

```<code>set cmd = nothing
</code>```

before

```<code>wb.Close savechanges:=True
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a VBA macro that open files in a folder, download data from an add-in, save and close.
This runs fine, but after 10 or 15 files, it gets quite slow. I think it is because Excel still keep previously opened files in the memory. I knew this because I saw the already-opened-and-closed files on the left panel as in the photo below. (the photo is to show where the panel is, I know there is only one file opened with the sheets, but you know what I mean).

My question is: is there a line of code that refresh or clear this temporary memory?

Here is my code:

'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim filename As String
Dim path_to_save As String
Dim FldrPicker As FileDialog
Dim w As Long
Dim StartTime As Double
Dim SecondsElapsed As Double
Dim oFile       As Object
Dim oFSO        As Object
Dim oFolder     As Object
Dim oFiles      As Object

Application.ScreenUpdating = False
StartTime = Timer

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Assign the folder to oFSO
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(myPath)
    Set oFiles = oFolder.Files
    If oFiles.Count = 0 Then GoTo ResetSettings

For Each oFile In oFolder.Files
    'Set variable equal to opened workbook
    myFile = oFile.Name
    Set wb = Workbooks.Open(filename:=myPath & myFile)
    Set cmd = Application.CommandBars("Cell").Controls("Refresh All")
    cmd.Execute
    DoEvents

    'Ensure Workbook has opened before moving on to next line of code

    wb.Close savechanges:=True

    'Ensure Workbook has closed before moving on to next line of code
    DoEvents
Next 'oFile

SecondsElapsed = Timer - StartTime
MsgBox "This code ran successfully in " & SecondsElapsed
    Set oFile = Nothing
    Set oFolder = Nothing
    Set oFSO = Nothing

ResetSettings:
  'Reset Macro Optimization Settings
    Application.ScreenUpdating = True
End Sub

Body:
What about add:

set cmd = nothing

before

wb.Close savechanges:=True


问:
How to update file data in azure data lake
i uploaded a file in azure data lake.I want to upload same file again with updated data and want to update existing file. So what is the process?</p>

答:
Azure Data Lake store is not recommended for overwrite existing files(i.e. random writes).

Note: If you want to use the same filename and location, you can replace a file by overwriting it or delete the existing file and then upload.

Here are the steps how to upload file data in Azure data lake store:

Make sure to select "Allow overwrite existing files".


问:
C++ Localization best practices?
We are localizing a cross-platform C++-based client-side application. The first localization pass was done in a big rush for a big partner on a short deadline, and now it's time to refactor it.

We currently have an XML strings file per locale, with a common key and a localized value for each resource. However, sending our not-necessarily-technical localizers an xml file isn't ideal -- they don't know about encoding special characters, etc etc.  I'd like to use an easy, well-known format like Excel/csv with the localizers (also nice because we have server-side localization as well, which could be in a different tab of the same file), and then code-gen the strings files from there.  It seems that Excel doesn't like to output UTF-8 CSV files, which is annoying, and is preventing me from throwing together a few quick scripts to automate the Excel --> strings file conversion.

This problem has been solved hundreds of times.  What workflows have people found best, especially for cases where the localizers will be external to the company? I'm looking for something easy for non-technical users and also easy for the development team to then use to generate the strings file in some simple format like XML.

答:
I would be wary of any format with an ambiguous character encoding. Consider using XLIFF (though check with your translation vendors to see what tools/processes they're familiar with).

XML in localisation: A practical analysis

OwnerDisplayName: Kevin Weil

ContentLicense: CC BY-SA 3.0

Title: C++ Localization best practices?

OwnerDisplayName: McDowell

ContentLicense: CC BY-SA 2.5


问:
Rails 3 serialized form attribute
I have the following model:

```<code>class Deck < ActiveRecord::Base
  has_many :cards
  serialize :stats
  attr_accessible :name, :description, :stats
end
</code>```

In this, stats should be an array of strings.  I want to be able to add an arbitrary number of stats to the row (using javascript to add additional "stat" input boxes, but that is outside the scope if the question.)

My question is how do I reflect this structure in the view?  If I was building the form manually then it would look like:

```<code><input type="text" name="deck[stats][]">
</code>```

My view currently looks like:

```<code><%= f.fields_for :stats, @deck.stats do |p| %>
  <%= p.label :p, "Stats: " %>
  <%= p.text_field :p %>
<% end %>
</code>```

But this outputs:

```<code><input type="text" name="deck[stats][p]">
</code>```

I also want a counter so I can display the label as "Stat 1:", "Stat 2:", etc.

Any help is appreciated.

答:
I don't know if there's a clean way of doing it, but this should work:</p>

```<code><% @deck.stats.each do |value|
  <%= f.fields_for :stats do |fields| %>
    <%= fields.text_field "", :value => value %>
  <% end %>
<% end %>
</code>```

Title: Rails 3 serialized form attribute

Body:
I have the following model:

class Deck < ActiveRecord::Base
  has_many :cards
  serialize :stats
  attr_accessible :name, :description, :stats
end

In this, stats should be an array of strings.  I want to be able to add an arbitrary number of stats to the row (using javascript to add additional "stat" input boxes, but that is outside the scope if the question.)

My question is how do I reflect this structure in the view?  If I was building the form manually then it would look like:

<input type="text" name="deck[stats][]">

My view currently looks like:

<%= f.fields_for :stats, @deck.stats do |p| %>
  <%= p.label :p, "Stats: " %>
  <%= p.text_field :p %>
<% end %>

But this outputs:

<input type="text" name="deck[stats][p]">

I also want a counter so I can display the label as "Stat 1:", "Stat 2:", etc.

Any help is appreciated.

Body:
I don't know if there's a clean way of doing it, but this should work:

<% @deck.stats.each do |value|
  <%= f.fields_for :stats do |fields| %>
    <%= fields.text_field "", :value => value %>
  <% end %>
<% end %>


问:
Ember Quickstart tutorial: Parsing error: Unexpected character '@' in '@action'
I just started using Ember and I have some trouble with the Ember Quickstart tutorial. Currently, I get Parsing error: Unexpected character '@' in line 5 of people-list.js:

```<code>import Component from '@glimmer/component';
import { action } from '@ember/object';

export default class PeopleListComponent extends Component {
  @action
  showPerson(person) {
    alert(`The person's name is ${person}!`);
  }
}
</code>```

What's wrong here? The code is copied from the tutorial.

This is the output of ember -v:

```<code>ember-cli: 3.18.0
node: 11.13.0
os: darwin x64
</code>```

This is my package.json. I can run npm install, but yarn install gives me The engine "node" is incompatible with this module. Expected version "10.* || >= 12". Got "11.13.0".

```<code>{
  "name": "ember-quickstart",
  "version": "0.0.0",
  "private": true,
  "description": "Small description for ember-quickstart goes here",
  "repository": "",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "lint:hbs": "ember-template-lint .",
    "lint:js": "eslint .",
    "start": "ember serve",
    "test": "ember test"
  },
  "devDependencies": {
    "@ember/jquery": "^0.5.2",
    "@ember/optional-features": "^0.6.3",
    "broccoli-asset-rev": "^2.7.0",
    "ember-ajax": "^5.0.0",
    "ember-cli-app-version": "^3.2.0",
    "ember-cli-babel": "^7.1.2",
    "ember-cli-dependency-checker": "^3.1.0",
    "ember-cli-eslint": "^4.2.3",
    "ember-cli-htmlbars": "^3.0.0",
    "ember-cli-htmlbars-inline-precompile": "^1.0.3",
    "ember-cli-inject-live-reload": "^1.8.2",
    "ember-cli-sri": "^2.1.1",
    "ember-cli-template-lint": "^1.0.0-beta.1",
    "ember-cli-uglify": "^2.1.0",
    "ember-data": "~3.9.0",
    "ember-export-application-global": "^2.0.0",
    "ember-load-initializers": "^1.1.0",
    "ember-maybe-import-regenerator": "^0.1.6",
    "ember-qunit": "^3.4.1",
    "ember-resolver": "^5.0.1",
    "ember-source": "~3.9.0",
    "ember-welcome-page": "^3.2.0",
    "eslint-plugin-ember": "^5.2.0",
    "loader.js": "^4.7.0",
    "qunit-dom": "^0.8.0"
  },
  "engines": {
    "node": "10.* || >= 12"
  },
  "dependencies": {
    "ember-cli": "^3.18.0",
    "@glimmer/component": "^1.0.0"
  }
}
</code>```

Adding some text here as SO won't let me post the question otherwise.

答:
The output says you currently have ember-cli 3.18, but your app seems to have been generated by an older ember-cli 3.9 as indicated by devDependencies.

As mentioned in the comments, 3.9 does not have access to some of the current features unless you install some polyfills.

If regenerating the app is a possibility, I would suggest doing it.

Run ember --version to make sure 3.18 is being called

Run ember new my-app-name and check that package.json has 3.18 for ember-source.

Go through the quickstart!

Alternatively, you can run npx ember-cli new my-app-name and it should generate an app using the latest ember-cli version available in npm.

If you don't want to lose some work you might have done, you can check out ember-cli-update by running something like npx ember-cli-update. Check the README for more info.

Body:
I just started using Ember and I have some trouble with the Ember Quickstart tutorial. Currently, I get Parsing error: Unexpected character '@' in line 5 of people-list.js:

import Component from '@glimmer/component';
import { action } from '@ember/object';

export default class PeopleListComponent extends Component {
  @action
  showPerson(person) {
    alert(`The person's name is ${person}!`);
  }
}

What's wrong here? The code is copied from the tutorial.

This is the output of ember -v:

ember-cli: 3.18.0
node: 11.13.0
os: darwin x64

This is my package.json. I can run npm install, but yarn install gives me The engine "node" is incompatible with this module. Expected version "10.* || >= 12". Got "11.13.0".

{
  "name": "ember-quickstart",
  "version": "0.0.0",
  "private": true,
  "description": "Small description for ember-quickstart goes here",
  "repository": "",
  "license": "MIT",
  "author": "",
  "directories": {
    "doc": "doc",
    "test": "tests"
  },
  "scripts": {
    "build": "ember build",
    "lint:hbs": "ember-template-lint .",
    "lint:js": "eslint .",
    "start": "ember serve",
    "test": "ember test"
  },
  "devDependencies": {
    "@ember/jquery": "^0.5.2",
    "@ember/optional-features": "^0.6.3",
    "broccoli-asset-rev": "^2.7.0",
    "ember-ajax": "^5.0.0",
    "ember-cli-app-version": "^3.2.0",
    "ember-cli-babel": "^7.1.2",
    "ember-cli-dependency-checker": "^3.1.0",
    "ember-cli-eslint": "^4.2.3",
    "ember-cli-htmlbars": "^3.0.0",
    "ember-cli-htmlbars-inline-precompile": "^1.0.3",
    "ember-cli-inject-live-reload": "^1.8.2",
    "ember-cli-sri": "^2.1.1",
    "ember-cli-template-lint": "^1.0.0-beta.1",
    "ember-cli-uglify": "^2.1.0",
    "ember-data": "~3.9.0",
    "ember-export-application-global": "^2.0.0",
    "ember-load-initializers": "^1.1.0",
    "ember-maybe-import-regenerator": "^0.1.6",
    "ember-qunit": "^3.4.1",
    "ember-resolver": "^5.0.1",
    "ember-source": "~3.9.0",
    "ember-welcome-page": "^3.2.0",
    "eslint-plugin-ember": "^5.2.0",
    "loader.js": "^4.7.0",
    "qunit-dom": "^0.8.0"
  },
  "engines": {
    "node": "10.* || >= 12"
  },
  "dependencies": {
    "ember-cli": "^3.18.0",
    "@glimmer/component": "^1.0.0"
  }
}

Adding some text here as SO won't let me post the question otherwise.


问:
Tkinter Dynamically Create and Delete Buttons
I'm trying to dynamically delete the last button and create a new button on the next row via the command function shared by all the "+" button. However, with my current code, I've got nothing but one button staying at the very first row, and it never disappear as I wish and no new buttons appear below it either.</p>

```<code>import tkinter as tk
root = tk.Tk()
root.title('test1')
root.geometry('300x300')

def num_add():

    prev_row = int(btn_list[-1].grid_info()['row'])
    add_btn = tk.Button(root,text='+',command=num_add)
    btn_list.append(add_btn)
    r1 = prev_row +1
    btn_list[-1].grid(row=r1,column=0)

    btn_list[-2].grid_forget()

btn_list = []
add_btn = tk.Button(root,text='+',command=num_add)
add_btn.grid(row=0,column=0)
btn_list.append(add_btn)

root.mainloop()
</code>```

答: Your code is actually working as expected. If you look at the .grid_info() for the button after you click it, you will see that it says the button is on row 1, column 0. The reason it doesn't look as you'd expect is, that there is nothing in row 0 anymore so the row effectively has a height of 0.

Body:
I'm trying to dynamically delete the last button and create a new button on the next row via the command function shared by all the "+" button. However, with my current code, I've got nothing but one button staying at the very first row, and it never disappear as I wish and no new buttons appear below it either.

import tkinter as tk
root = tk.Tk()
root.title('test1')
root.geometry('300x300')

def num_add():

    prev_row = int(btn_list[-1].grid_info()['row'])
    add_btn = tk.Button(root,text='+',command=num_add)
    btn_list.append(add_btn)
    r1 = prev_row +1
    btn_list[-1].grid(row=r1,column=0)

    btn_list[-2].grid_forget()

btn_list = []
add_btn = tk.Button(root,text='+',command=num_add)
add_btn.grid(row=0,column=0)
btn_list.append(add_btn)

root.mainloop()


问:
How to pull url file extension out of url string using javascript
How do I find the file extension of a URL using javascript?
example URL:

```<code>http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294
</code>```

I just want the 'swf' of the entire URL.
I need it to find the extension if the url was also in the following format

```<code>http://www.adobe.com/products/flashplayer/include/marquee/design.swf
</code>```

Obviously this URL does not have the parameters behind it.

Anybody know?

Thanks in advance

答:
```<code>function ext(url){
    var ext = url.substr(url.lastIndexOf('/') + 1),
        ext = ext.split('?')[0],
        ext = ext.split('#')[0],
        dot = ext.lastIndexOf('.');

    return dot > -1 ? ext.substring(dot + 1) : '';
}
</code>```

Body:
How do I find the file extension of a URL using javascript?
example URL:

http://www.adobe.com/products/flashplayer/include/marquee/design.swf?width=792&height=294

I just want the 'swf' of the entire URL.
I need it to find the extension if the url was also in the following format

http://www.adobe.com/products/flashplayer/include/marquee/design.swf

Obviously this URL does not have the parameters behind it.

Anybody know?

Thanks in advance


问:
Passing images from one page to another in Xamarin Forms
In  my app I need to pass images from one page to another page image view to display. I am taking a photo from camera and do some stuffs, then I want to send that images to the second page.

```<code>            if (await isCamAvailable())
            {

                 MediaFile photo1 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions() { Directory = "NewBusiness", Name = "image1.jpg", PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 1024, CompressionQuality = 95 });

                if (photo1 != null)
                {
                    PhotoImage1.Source = ImageSource.FromStream(() => { return photo1.GetStream(); });
                    countList.Remove("a");
                    countList.Add("a");
                }

            }
</code>```

Then I am added it to a string array by doing

```<code>        private List<string> sendImgList = new List<string>();

        sendImgList.Add(createImgByteString(photo1.GetStream()));

        private string createImgByteString(Stream data)
        {
            var bytes = new byte[data.Length];
            return Convert.ToBase64String(bytes);
        }
</code>```

Then from second page (for testing i just added only one image)

```<code>        foreach (string ss in imgList) {

            byte[] Base64Stream = Convert.FromBase64String(ss);
            imgView.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));

        }
</code>```

I followed this example. But image not showing.

https://forums.xamarin.com/discussion/139360/how-to-transfer-images-from-one-page-to-another

Also getting this in logcat..

```<code>[0:] ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource05-29 14:22:43.758 W/monodroid-assembly( 8737): typemap: unable to find mapping to a Java type from managed type 'System.Byte, mscorlib'
</code>```

答:
It seems that you used the Media.Plugin . Why don't you pass the ImageSource directly?
If you do want to convert it to byte array , check the following code

```<code>public byte[] GetImageStreamAsBytes(Stream input)
{
  var buffer = new byte[16*1024];
  using (MemoryStream ms = new MemoryStream())
  {
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
                ms.Write(buffer, 0, read);
    }
      return ms.ToArray();
   }
}
</code>```

```<code>var imgDate = GetImageStreamAsBytes(photo1.GetStream());
</code>```

It would be better to pass the byte array directly .

Body:
In  my app I need to pass images from one page to another page image view to display. I am taking a photo from camera and do some stuffs, then I want to send that images to the second page.

            if (await isCamAvailable())
            {

                 MediaFile photo1 = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions() { Directory = "NewBusiness", Name = "image1.jpg", PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 1024, CompressionQuality = 95 });

                if (photo1 != null)
                {
                    PhotoImage1.Source = ImageSource.FromStream(() => { return photo1.GetStream(); });
                    countList.Remove("a");
                    countList.Add("a");
                }

            }

Then I am added it to a string array by doing

        private List<string> sendImgList = new List<string>();

        sendImgList.Add(createImgByteString(photo1.GetStream()));

        private string createImgByteString(Stream data)
        {
            var bytes = new byte[data.Length];
            return Convert.ToBase64String(bytes);
        }

Then from second page (for testing i just added only one image)

        foreach (string ss in imgList) {

            byte[] Base64Stream = Convert.FromBase64String(ss);
            imgView.Source = ImageSource.FromStream(() => new MemoryStream(Base64Stream));

        }

I followed this example. But image not showing.

https://forums.xamarin.com/discussion/139360/how-to-transfer-images-from-one-page-to-another

Also getting this in logcat..

[0:] ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource05-29 14:22:43.758 W/monodroid-assembly( 8737): typemap: unable to find mapping to a Java type from managed type 'System.Byte, mscorlib'

Body:
It seems that you used the Media.Plugin . Why don't you pass the ImageSource directly?
If you do want to convert it to byte array , check the following code

public byte[] GetImageStreamAsBytes(Stream input)
{
  var buffer = new byte[16*1024];
  using (MemoryStream ms = new MemoryStream())
  {
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
                ms.Write(buffer, 0, read);
    }
      return ms.ToArray();
   }
}

var imgDate = GetImageStreamAsBytes(photo1.GetStream());

It would be better to pass the byte array directly .


问:
Why is exception in Spring Batch AsycItemProcessor caught by SkipListener's onSkipInWrite method?
I'm writing a Spring Boot application that starts up, gathers and converts millions of database entries into a new streamlined JSON format, and then sends them all to a GCP PubSub topic. I'm attempting to use Spring Batch for this, but I'm running into trouble implementing fault tolerance for my process. The database is rife with data quality issues, and sometimes my conversions to JSON will fail. When failures occur, I don't want the job to immediately quit, I want it to continue processing as many records as it can and, before completion, to report which exact records failed so that I, and or my team, can examine these problematic database entries.

To achieve this, I've attempted to use Spring Batch's SkipListener interface. But I'm also using an AsyncItemProcessor and an AsyncItemWriter in my process, and even though the exceptions are occurring during the processing, the SkipListener's onSkipInWrite() method is catching them - rather than the onSkipInProcess() method. And unfortunately, the onSkipInWrite() method doesn't have access to the original database entity, so I can't store its ID in my list of problematic DB entries.

Have I misconfigured something? Is there any other way to gain access to the objects from the reader that failed the processing step of an AsynItemProcessor?

Here's what I've tried...

I have a singleton Spring Component where I store how many DB entries I've successfully processed along with up to 20 problematic database entries.

@Component
@Getter //lombok
public class ProcessStatus {
    private int processed;
    private int failureCount;
    private final List<UnexpectedFailure> unexpectedFailures = new ArrayList<>();

    public void incrementProgress { processed++; }
    public void logUnexpectedFailure(UnexpectedFailure failure) {
        failureCount++;
        unexpectedFailure.add(failure);
    }

    @Getter
    @AllArgsConstructor
    public static class UnexpectedFailure {
        private Throwable error;
        private DBProjection dbData;
    }
}
```

<p>I have a Spring batch Skip Listener that's supposed to catch failures and update my status component accordingly:</p>

<pre class="lang-java prettyprint-override"><code>@AllArgsConstructor
public class ConversionSkipListener implements SkipListener<DBProjection, Future<JsonMessage>> {
    private ProcessStatus processStatus;

    @Override
    public void onSkipInRead(Throwable error) {}

    @Override
    public void onSkipInProcess(DBProjection dbData, Throwable error) {
        processStatus.logUnexpectedFailure(new ProcessStatus.UnexpectedFailure(error, dbData));
    }

    @Override
    public void onSkipInWrite(Future<JsonMessage> messageFuture, Throwable error) {
        //This is getting called instead!! Even though the exception happened during processing :(
        //But I have no access to the original DBProjection data here, and messageFuture.get() gives me null.
    }
}
</code>```

And then I've configured my job like this:

@Configuration
public class ConversionBatchJobConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private TaskExecutor processThreadPool;

    @Bean
    public SimpleCompletionPolicy processChunkSize(@Value("${commit.chunk.size:100}") Integer chunkSize) {
        return new SimpleCompletionPolicy(chunkSize);
    }

    @Bean
    @StepScope
    public ItemStreamReader<DbProjection> dbReader(
            MyDomainRepository myDomainRepository,
            @Value("#{jobParameters[pageSize]}") Integer pageSize,
            @Value("#{jobParameters[limit]}") Integer limit) {
        RepositoryItemReader<DbProjection> myDomainRepositoryReader = new RepositoryItemReader<>();
        myDomainRepositoryReader.setRepository(myDomainRepository);
        myDomainRepositoryReader.setMethodName("findActiveDbDomains"); //A native query
        myDomainRepositoryReader.setArguments(new ArrayList<Object>() {{
            add("ACTIVE");
        }});
        myDomainRepositoryReader.setSort(new HashMap<String, Sort.Direction>() {{
            put("update_date", Sort.Direction.ASC);
        }});
        myDomainRepositoryReader.setPageSize(pageSize);
        myDomainRepositoryReader.setMaxItemCount(limit);
        // myDomainRepositoryReader.setSaveState(false); <== haven't figured out what this does yet
        return myDomainRepositoryReader;
    }

    @Bean
    @StepScope
    public ItemProcessor<DbProjection, JsonMessage> dataConverter(DataRetrievalSerivice dataRetrievalService) {
        //Sometimes throws exceptions when DB data is exceptionally weird, bad, or missing
        return new DbProjectionToJsonMessageConverter(dataRetrievalService);
    }

    @Bean
    @StepScope
    public AsyncItemProcessor<DbProjection, JsonMessage> asyncDataConverter(
            ItemProcessor<DbProjection, JsonMessage> dataConverter) throws Exception {
        AsyncItemProcessor<DbProjection, JsonMessage> asyncDataConverter = new AsyncItemProcessor<>();
        asyncDataConverter.setDelegate(dataConverter);
        asyncDataConverter.setTaskExecutor(processThreadPool);
        asyncDataConverter.afterPropertiesSet();
        return asyncDataConverter;
    }

    @Bean
    @StepScope
    public ItemWriter<JsonMessage> jsonPublisher(GcpPubsubPublisherService publisherService) {
        return new JsonMessageWriter(publisherService);
    }

    @Bean
    @StepScope
    public AsyncItemWriter<JsonMessage> asyncJsonPublisher(ItemWriter<JsonMessage> jsonPublisher) throws Exception {
        AsyncItemWriter<JsonMessage> asyncJsonPublisher = new AsyncItemWriter<>();
        asyncJsonPublisher.setDelegate(jsonPublisher);
        asyncJsonPublisher.afterPropertiesSet();
        return asyncJsonPublisher;
    }

    @Bean
    public Step conversionProcess(SimpleCompletionPolicy processChunkSize,
                                  ItemStreamReader<DbProjection> dbReader,
                                  AsyncItemProcessor<DbProjection, JsonMessage> asyncDataConverter,
                                  AsyncItemWriter<JsonMessage> asyncJsonPublisher,
                                  ProcessStatus processStatus,
                                  @Value("${conversion.failure.limit:20}") int maximumFailures) {
        return stepBuilderFactory.get("conversionProcess")
                .<DbProjection, Future<JsonMessage>>chunk(processChunkSize)
                .reader(dbReader)
                .processor(asyncDataConverter)
                .writer(asyncJsonPublisher)
                .faultTolerant()
                .skipPolicy(new MyCustomConversionSkipPolicy(maximumFailures))
                            //  ^ for now this returns true for everything until 20 failures
                    .listener(new ConversionSkipListener(processStatus))
                .build();
    }

    @Bean
    public Job conversionJob(Step conversionProcess) {
        return jobBuilderFactory.get("conversionJob")
                .start(conversionProcess)
                .build();
    }
}
```

答:
This is because the future wrapped by the AsyncItemProcessor is only unwrapped in the AsyncItemWriter, so any exception that might occur at that time is seen as a write exception instead of a processing exception. That's why onSkipInWrite is called instead of onSkipInProcess.

This is actually a known limitation of this pattern which is documented in the Javadoc of the AsyncItemProcessor, here is an excerpt:

```<code>Because the Future is typically unwrapped in the ItemWriter,
there are lifecycle and stats limitations (since the framework doesn't know
what the result of the processor is).

While not an exhaustive list, things like StepExecution.filterCount will not
reflect the number of filtered items and
itemProcessListener.onProcessError(Object, Exception) will not be called.
</code>```

The Javadoc states that the list is not exhaustive, and the side-effect regarding the SkipListener that you are experiencing is one these limitations.

Body:
I'm writing a Spring Boot application that starts up, gathers and converts millions of database entries into a new streamlined JSON format, and then sends them all to a GCP PubSub topic. I'm attempting to use Spring Batch for this, but I'm running into trouble implementing fault tolerance for my process. The database is rife with data quality issues, and sometimes my conversions to JSON will fail. When failures occur, I don't want the job to immediately quit, I want it to continue processing as many records as it can and, before completion, to report which exact records failed so that I, and or my team, can examine these problematic database entries.

To achieve this, I've attempted to use Spring Batch's SkipListener interface. But I'm also using an AsyncItemProcessor and an AsyncItemWriter in my process, and even though the exceptions are occurring during the processing, the SkipListener's onSkipInWrite() method is catching them - rather than the onSkipInProcess() method. And unfortunately, the onSkipInWrite() method doesn't have access to the original database entity, so I can't store its ID in my list of problematic DB entries.

Have I misconfigured something? Is there any other way to gain access to the objects from the reader that failed the processing step of an AsynItemProcessor?

Here's what I've tried...

I have a singleton Spring Component where I store how many DB entries I've successfully processed along with up to 20 problematic database entries.

@Component
@Getter //lombok
public class ProcessStatus {
    private int processed;
    private int failureCount;
    private final List<UnexpectedFailure> unexpectedFailures = new ArrayList<>();

    public void incrementProgress { processed++; }
    public void logUnexpectedFailure(UnexpectedFailure failure) {
        failureCount++;
        unexpectedFailure.add(failure);
    }

    @Getter
    @AllArgsConstructor
    public static class UnexpectedFailure {
        private Throwable error;
        private DBProjection dbData;
    }
}

I have a Spring batch Skip Listener that's supposed to catch failures and update my status component accordingly:

@AllArgsConstructor
public class ConversionSkipListener implements SkipListener<DBProjection, Future<JsonMessage>> {
    private ProcessStatus processStatus;

    @Override
    public void onSkipInRead(Throwable error) {}

    @Override
    public void onSkipInProcess(DBProjection dbData, Throwable error) {
        processStatus.logUnexpectedFailure(new ProcessStatus.UnexpectedFailure(error, dbData));
    }

    @Override
    public void onSkipInWrite(Future<JsonMessage> messageFuture, Throwable error) {
        //This is getting called instead!! Even though the exception happened during processing :(
        //But I have no access to the original DBProjection data here, and messageFuture.get() gives me null.
    }
}

And then I've configured my job like this:

@Configuration
public class ConversionBatchJobConfig {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private TaskExecutor processThreadPool;

    @Bean
    public SimpleCompletionPolicy processChunkSize(@Value("${commit.chunk.size:100}") Integer chunkSize) {
        return new SimpleCompletionPolicy(chunkSize);
    }

    @Bean
    @StepScope
    public ItemStreamReader<DbProjection> dbReader(
            MyDomainRepository myDomainRepository,
            @Value("#{jobParameters[pageSize]}") Integer pageSize,
            @Value("#{jobParameters[limit]}") Integer limit) {
        RepositoryItemReader<DbProjection> myDomainRepositoryReader = new RepositoryItemReader<>();
        myDomainRepositoryReader.setRepository(myDomainRepository);
        myDomainRepositoryReader.setMethodName("findActiveDbDomains"); //A native query
        myDomainRepositoryReader.setArguments(new ArrayList<Object>() {{
            add("ACTIVE");
        }});
        myDomainRepositoryReader.setSort(new HashMap<String, Sort.Direction>() {{
            put("update_date", Sort.Direction.ASC);
        }});
        myDomainRepositoryReader.setPageSize(pageSize);
        myDomainRepositoryReader.setMaxItemCount(limit);
        // myDomainRepositoryReader.setSaveState(false); <== haven't figured out what this does yet
        return myDomainRepositoryReader;
    }

    @Bean
    @StepScope
    public ItemProcessor<DbProjection, JsonMessage> dataConverter(DataRetrievalSerivice dataRetrievalService) {
        //Sometimes throws exceptions when DB data is exceptionally weird, bad, or missing
        return new DbProjectionToJsonMessageConverter(dataRetrievalService);
    }

    @Bean
    @StepScope
    public AsyncItemProcessor<DbProjection, JsonMessage> asyncDataConverter(
            ItemProcessor<DbProjection, JsonMessage> dataConverter) throws Exception {
        AsyncItemProcessor<DbProjection, JsonMessage> asyncDataConverter = new AsyncItemProcessor<>();
        asyncDataConverter.setDelegate(dataConverter);
        asyncDataConverter.setTaskExecutor(processThreadPool);
        asyncDataConverter.afterPropertiesSet();
        return asyncDataConverter;
    }

    @Bean
    @StepScope
    public ItemWriter<JsonMessage> jsonPublisher(GcpPubsubPublisherService publisherService) {
        return new JsonMessageWriter(publisherService);
    }

    @Bean
    @StepScope
    public AsyncItemWriter<JsonMessage> asyncJsonPublisher(ItemWriter<JsonMessage> jsonPublisher) throws Exception {
        AsyncItemWriter<JsonMessage> asyncJsonPublisher = new AsyncItemWriter<>();
        asyncJsonPublisher.setDelegate(jsonPublisher);
        asyncJsonPublisher.afterPropertiesSet();
        return asyncJsonPublisher;
    }

    @Bean
    public Step conversionProcess(SimpleCompletionPolicy processChunkSize,
                                  ItemStreamReader<DbProjection> dbReader,
                                  AsyncItemProcessor<DbProjection, JsonMessage> asyncDataConverter,
                                  AsyncItemWriter<JsonMessage> asyncJsonPublisher,
                                  ProcessStatus processStatus,
                                  @Value("${conversion.failure.limit:20}") int maximumFailures) {
        return stepBuilderFactory.get("conversionProcess")
                .<DbProjection, Future<JsonMessage>>chunk(processChunkSize)
                .reader(dbReader)
                .processor(asyncDataConverter)
                .writer(asyncJsonPublisher)
                .faultTolerant()
                .skipPolicy(new MyCustomConversionSkipPolicy(maximumFailures))
                            //  ^ for now this returns true for everything until 20 failures
                    .listener(new ConversionSkipListener(processStatus))
                .build();
    }

    @Bean
    public Job conversionJob(Step conversionProcess) {
        return jobBuilderFactory.get("conversionJob")
                .start(conversionProcess)
                .build();
    }
}

Body:
This is because the future wrapped by the AsyncItemProcessor is only unwrapped in the AsyncItemWriter, so any exception that might occur at that time is seen as a write exception instead of a processing exception. That's why onSkipInWrite is called instead of onSkipInProcess.

This is actually a known limitation of this pattern which is documented in the Javadoc of the AsyncItemProcessor, here is an excerpt:

Because the Future is typically unwrapped in the ItemWriter,
there are lifecycle and stats limitations (since the framework doesn't know
what the result of the processor is).

While not an exhaustive list, things like StepExecution.filterCount will not
reflect the number of filtered items and
itemProcessListener.onProcessError(Object, Exception) will not be called.

The Javadoc states that the list is not exhaustive, and the side-effect regarding the SkipListener that you are experiencing is one these limitations.


问:
How to reverse order of keys in python dict?
This is my code :

```<code>a = {0:'000000',1:'11111',3:'333333',4:'444444'}

for i in a:
    print i
</code>```

it shows:

```<code>0
1
3
4
</code>```

but I want it to show:

```<code>4
3
1
0
</code>```

so, what can I do?

答:
If you want to preserve the insertion order and not the alphabetical ordering, then you can use:

dict(list(your_dict.keys())[::-1])

Or for the whole dictionary:

dict(list(your_dict.items())[::-1])

Body:
This is my code :

a = {0:'000000',1:'11111',3:'333333',4:'444444'}

for i in a:
    print i

it shows:

0
1
3
4

but I want it to show:

4
3
1
0

so, what can I do?


问:
How to send automated reminder emails in specific intervals in Python flask
I am quite new in Flask. I am stuck with a specific issue.

I have a requirement where I need to send automated reminder emails at specific intervals. Let's say, every 10 days an automated reminder will be sent to the users who did not fill up a survey form.

How can I achieve this in python flask?

Any help will be appreciable.

答:
You can use flask mail a flask extension that does exactly what you need.
You can send an email every X seconds and when he verified it it would stop sending the email. I'd suggest a simple boolean. If you want you can use BackgroundScheduler(). In order to send it every x seconds.</p>


问:
What is Querydsl PathBuilder String parameter 'variable' used for
I'm working with Querydsl in my Spring Boot API for making some complex data filtering and when i declare the PathBuilder variable i've seen that first you have to pass statically your class  like YourClass.class and then a string variable for the constructor as shown below:

```<code>    PathBuilder<Plan> entityPath = new PathBuilder<>(Plan.class, "plan");
</code>```

So i was wondering why is necessary this string parameter and also why its name has to be the same as my class name, because when i delete it or modified it, the entityPath doesn't work.

答:
A PathExpression (which PathBuilder) is by definition represents a path variable. In your case, the path ending up in your query would be plan. Consecutively, you can build on to this path and create various path types. For example property retrieval: entityPath.get("someProperty") will return a path expression that represents plan.somePropety. So you can't create PathExpressions without an alias, because it would be essentially meaningless.

Then why this alias is not always inferred from the Path types, well simply put: because it is not related. The underlying entities used may have different naming strategies, you may want to mix up different path variables of the same type, you might reference a node that has a particular alias by itself.

The alias doesn't have to be equivalent to the simple classname, it has to be equivalent to the alias it references from any of the from/join clauses in the query.

Body:
I'm working with Querydsl in my Spring Boot API for making some complex data filtering and when i declare the PathBuilder variable i've seen that first you have to pass statically your class  like YourClass.class and then a string variable for the constructor as shown below:

    PathBuilder<Plan> entityPath = new PathBuilder<>(Plan.class, "plan");

So i was wondering why is necessary this string parameter and also why its name has to be the same as my class name, because when i delete it or modified it, the entityPath doesn't work.


问:
C++11 Cereal Serialization - versioning
I have successfully serialized two members of my class.

    archive(
        cereal::make_nvp("width", m_width),
        cereal::make_nvp("height", m_height),
    );
```

<p>Now, in a later version my code contains more members and I would like to archive them as well:</p>

<pre class="lang-cpp prettyprint-override"><code>    archive(
        cereal::make_nvp("width", m_width),
        cereal::make_nvp("height", m_height),
        cereal::make_nvp("lambda0", m_lambda0),
        cereal::make_nvp("phi1", m_phi1)
    );
</code>```

However, this crashes as the new members are not present in old archives. As far as I know there is no way of having default values defined for these variables in make_nvp.

But there for sure has to be some kind of versioning so that this default circumstance can be solved? Could someone point me to the documentation of this or even better to some sample code? I can't find anything on there official website. ( But most likely I am just blind .. )

答:
For future reference - here it is documented how to version:

https://uscilab.github.io/cereal/serialization_functions.html#versioning

Title: C++11 Cereal Serialization - versioning

Body:
I have successfully serialized two members of my class.

    archive(
        cereal::make_nvp("width", m_width),
        cereal::make_nvp("height", m_height),
    );

Now, in a later version my code contains more members and I would like to archive them as well:

    archive(
        cereal::make_nvp("width", m_width),
        cereal::make_nvp("height", m_height),
        cereal::make_nvp("lambda0", m_lambda0),
        cereal::make_nvp("phi1", m_phi1)
    );

However, this crashes as the new members are not present in old archives. As far as I know there is no way of having default values defined for these variables in make_nvp.

But there for sure has to be some kind of versioning so that this default circumstance can be solved? Could someone point me to the documentation of this or even better to some sample code? I can't find anything on there official website. ( But most likely I am just blind .. )


问:
Why am I getting "undefined symbol" when I link my static library in my C program?
I'm trying to create a static library to allow me to use a C++ API in my C program. To get started, I'm trying to call an API function called APIName::Api_init(); So far, I have created a "wrapper" library which has the following:

c_api.h:

```<code>#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
EXTERNC int apiname_api_init(char const * user_app_name);
EXTERNC void apiname_api_shutdown();

#undef EXTERNC
</code>```

c_api.cpp:

```<code>#include "c_api.h"
#include "../include/apiname/api.h"   // Link to header files from API provider
int apiname_api_init(char const * user_app_name) {
        return to_return_code(APIName::Api_init(user_app_name));
}

void apiname_api_shutdown() {
        return APIName::api_shutdown();
}
</code>```

I then compile this into an object file called apiwrapper.o using the following command:

```<code>g++  -L../include/libs -lapinameapi  -shared -fPIC -c -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -I../include -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX  c_api.cpp -o lapiwrapper.o -lrt
</code>```

where apinameapi is the shared library from the API provider.  This works fine.  I then generate the library file using:

```<code>ar rc libapiwrapper.a apiwrapper.o
</code>```

Again, this is fine.

Now I create my C file (mycode.c), which contains:

```<code>#include "mycode.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int connectToApi() {

  // Init API
  rc = apiname_api_init("programname");

}
</code>```

The header file mycode.h contains:

```<code>#include <stdbool.h>
#include <stdint.h>
#include "c_api.h"
</code>```

(obviously there's other stuff as well, but I've left it out for brevity).

So, I compile my main program using:

```<code>gcc  -Linclude/libs -lapiwrapper  -shared -DKXVER=3 -fPIC -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -Iinclude -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX  src/mycode.c -o lib/mycode.so -lrt -Wno-discarded-qualifiers -Wno-incompatible-pointer-types
</code>```

which is also fine. Then, I run the program (this particular file gets loaded by another piece of code), and I get

undefined symbol: apiname_api_init

It seems that it's not finding the function in the library file.  Where am I going wrong? This is my first time building a library, so it's probably something fairly basic.

EDIT: I think the issue may be coming from the fact that the final compilation (which creates mycode.so) is producing a shared object file, and I need that to run on its own (without needing my generated library file to be present as well).  I have to run the final object from another program, so it needs to be standalone. Is there a way I can link it to "bundle" everything together into one final so file?

答:
The command ar rc libapiwrapper.a apiwrapper.o creates a static library. If you link with that you will also need to link in its dependancies.
What you need is to create a shared library (.so file).
You'll probably need someting like this (I have split the compile and link steps in idividual commands):

```<code>g++ -lapinameapi -c -D_LINUX_X86_64 -I../include -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX c_api.cpp -o lapiwrapper.o
g++ -shared -fPIC -o libapiwrapper.so lapiwrapper.o -L../include/libs -lpthread -lz -lm -lcrypto -lbz2 -lrt
</code>```

Finally it's just a matter of linking the executable with this shared library instead of the static library.

Body:
I'm trying to create a static library to allow me to use a C++ API in my C program. To get started, I'm trying to call an API function called APIName::Api_init(); So far, I have created a "wrapper" library which has the following:

c_api.h:

#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
EXTERNC int apiname_api_init(char const * user_app_name);
EXTERNC void apiname_api_shutdown();

#undef EXTERNC

c_api.cpp:

#include "c_api.h"
#include "../include/apiname/api.h"   // Link to header files from API provider
int apiname_api_init(char const * user_app_name) {
        return to_return_code(APIName::Api_init(user_app_name));
}

void apiname_api_shutdown() {
        return APIName::api_shutdown();
}

I then compile this into an object file called apiwrapper.o using the following command:

g++  -L../include/libs -lapinameapi  -shared -fPIC -c -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -I../include -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX  c_api.cpp -o lapiwrapper.o -lrt

where apinameapi is the shared library from the API provider.  This works fine.  I then generate the library file using:

ar rc libapiwrapper.a apiwrapper.o

Again, this is fine.

Now I create my C file (mycode.c), which contains:

#include "mycode.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int connectToApi() {

  // Init API
  rc = apiname_api_init("programname");

}

The header file mycode.h contains:

#include <stdbool.h>
#include <stdint.h>
#include "c_api.h"

(obviously there's other stuff as well, but I've left it out for brevity).

So, I compile my main program using:

gcc  -Linclude/libs -lapiwrapper  -shared -DKXVER=3 -fPIC -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -Iinclude -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX  src/mycode.c -o lib/mycode.so -lrt -Wno-discarded-qualifiers -Wno-incompatible-pointer-types

which is also fine. Then, I run the program (this particular file gets loaded by another piece of code), and I get

undefined symbol: apiname_api_init

It seems that it's not finding the function in the library file.  Where am I going wrong? This is my first time building a library, so it's probably something fairly basic.

EDIT: I think the issue may be coming from the fact that the final compilation (which creates mycode.so) is producing a shared object file, and I need that to run on its own (without needing my generated library file to be present as well).  I have to run the final object from another program, so it needs to be standalone. Is there a way I can link it to "bundle" everything together into one final so file?

Body:
The command ar rc libapiwrapper.a apiwrapper.o creates a static library. If you link with that you will also need to link in its dependancies.
What you need is to create a shared library (.so file).
You'll probably need someting like this (I have split the compile and link steps in idividual commands):

g++ -lapinameapi -c -D_LINUX_X86_64 -I../include -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX c_api.cpp -o lapiwrapper.o
g++ -shared -fPIC -o libapiwrapper.so lapiwrapper.o -L../include/libs -lpthread -lz -lm -lcrypto -lbz2 -lrt

Finally it's just a matter of linking the executable with this shared library instead of the static library.


问:
Custom sentence segmentation in Spacy
I want spaCy to use the sentence segmentation boundaries as I provide instead of its own processing.

For example:

```<code>get_sentences("Bob meets Alice. @SentBoundary@ They play together.")
# => ["Bob meets Alice.", "They play together."]  # two sents

get_sentences("Bob meets Alice. They play together.")
# => ["Bob meets Alice. They play together."]  # ONE sent

get_sentences("Bob meets Alice, @SentBoundary@ they play together.")
# => ["Bob meets Alice,", "they play together."] # two sents
</code>```

This is what I have so far (borrowing things from documentation here):

```<code>import spacy
nlp = spacy.load('en_core_web_sm')

def mark_sentence_boundaries(doc):
    for i, token in enumerate(doc):
        if token.text == '@SentBoundary@':
            doc[i+1].sent_start = True
    return doc

nlp.add_pipe(mark_sentence_boundaries, before='parser')

def get_sentences(text):
    doc = nlp(text)
    return (list(doc.sents))
</code>```

But the results I get are as follows:

```<code># Ex1
get_sentences("Bob meets Alice. @SentBoundary@ They play together.")
#=> ["Bob meets Alice.", "@SentBoundary@", "They play together."]

# Ex2
get_sentences("Bob meets Alice. They play together.")
#=> ["Bob meets Alice.", "They play together."]

# Ex3
get_sentences("Bob meets Alice, @SentBoundary@ they play together.")
#=> ["Bob meets Alice, @SentBoundary@", "they play together."]
</code>```

Following are main problems I am facing:

When sentence break is found, how to get rid of @SentBoundary@ token.

How to disallow spaCy from splitting if @SentBoundary@ is not present.

答:
```<code>import spacy
from spacy.attrs import LOWER, POS, ENT_TYPE, IS_ALPHA
from spacy.tokens import Doc
import numpy
nlp = spacy.load('en_core_web_sm')

def mark_sentence_boundaries(doc):
    indexes = []
    for i, token in enumerate(doc):
        if token.text == '@SentBoundary@':
            doc[i+1].sent_start = True
            indexes.append(token.i)

    np_array = doc.to_array([LOWER, POS, ENT_TYPE, IS_ALPHA])
    np_array = numpy.delete(np_array, indexes, axis=0)
    doc2 = Doc(doc.vocab, words=[t.text for i, t in enumerate(doc) if i not in indexes])
    doc2.from_array([LOWER, POS, ENT_TYPE, IS_ALPHA], np_array)
    return doc2

nlp.add_pipe(mark_sentence_boundaries, before='parser')

def get_sentences(text):
    doc = nlp(text)
    return (list(doc.sents))

print(get_sentences("Bob meets Alice. @SentBoundary@ They play together."))
# => ["Bob meets Alice.", "They play together."]  # two sents

print(get_sentences("Bob meets Alice. They play together."))
# => ["Bob meets Alice. They play together."]  # ONE sent

print(get_sentences("Bob meets Alice, @SentBoundary@ they play together."))
# => ["Bob meets Alice,", "they play together."] # two sents
</code>```

Title: Custom sentence segmentation in Spacy

Body:
I want spaCy to use the sentence segmentation boundaries as I provide instead of its own processing.

For example:

get_sentences("Bob meets Alice. @SentBoundary@ They play together.")
# => ["Bob meets Alice.", "They play together."]  # two sents

get_sentences("Bob meets Alice. They play together.")
# => ["Bob meets Alice. They play together."]  # ONE sent

get_sentences("Bob meets Alice, @SentBoundary@ they play together.")
# => ["Bob meets Alice,", "they play together."] # two sents

This is what I have so far (borrowing things from documentation here):

import spacy
nlp = spacy.load('en_core_web_sm')

def mark_sentence_boundaries(doc):
    for i, token in enumerate(doc):
        if token.text == '@SentBoundary@':
            doc[i+1].sent_start = True
    return doc

nlp.add_pipe(mark_sentence_boundaries, before='parser')

def get_sentences(text):
    doc = nlp(text)
    return (list(doc.sents))

But the results I get are as follows:

# Ex1
get_sentences("Bob meets Alice. @SentBoundary@ They play together.")
#=> ["Bob meets Alice.", "@SentBoundary@", "They play together."]

# Ex2
get_sentences("Bob meets Alice. They play together.")
#=> ["Bob meets Alice.", "They play together."]

# Ex3
get_sentences("Bob meets Alice, @SentBoundary@ they play together.")
#=> ["Bob meets Alice, @SentBoundary@", "they play together."]

Following are main problems I am facing:

When sentence break is found, how to get rid of @SentBoundary@ token.

How to disallow spaCy from splitting if @SentBoundary@ is not present.


问:
RxSwift Error: Property 'text' requires that 'UITextField' inherit from 'UILabel'
```<code>func bindSearchTextField() {
        searchTextField.rx.text.asObservable().skip(3)
            .debounce(0.3, scheduler: MainScheduler.instance)
            .subscribe(onNext: { [weak self] searchText in
                guard let strongSelf = self else {
                    return
                }
                if let text = searchText {
                    if text == "" {
                        self?.hideLoader()
                        self?.clearButton.isHidden = true
                    } else {
                        self?.clearButton.isHidden = false
                    }
                    strongSelf.presenter?.getAreaCodeList(text: text)
                }
            }).disposed(by: disposeBag)
    }
</code>```

I'm getting this error after i updated my RxSwift to latest version (from 4.4.0 to 5.1.1).
Can anyone help me here?

答:
Use: .debounce(.milliseconds(300), scheduler: MainScheduler.instance) instead. The debounce(_:scheduler:) that takes a Double has been removed.

Also, you are doing too much in your subscribe. You are better off if you break the subscribe up into independent units:

```<code>let searchText = searchTextField.rx.text.asObservable().skip(3)
    .debounce(.milliseconds(300), scheduler: MainScheduler.instance)
    .compactMap { $0 }

searchText
    .map { $0.isEmpty }
    .bind(to: clearButton.rx.isHidden)
    .disposed(by: disposeBag)

searchText
    .bind { [presenter] in
        presenter?.getAreaCodeList(text: $0)
    }
    .disposed(by: disposeBag)
</code>```

Body:
func bindSearchTextField() {
        searchTextField.rx.text.asObservable().skip(3)
            .debounce(0.3, scheduler: MainScheduler.instance)
            .subscribe(onNext: { [weak self] searchText in
                guard let strongSelf = self else {
                    return
                }
                if let text = searchText {
                    if text == "" {
                        self?.hideLoader()
                        self?.clearButton.isHidden = true
                    } else {
                        self?.clearButton.isHidden = false
                    }
                    strongSelf.presenter?.getAreaCodeList(text: text)
                }
            }).disposed(by: disposeBag)
    }

I'm getting this error after i updated my RxSwift to latest version (from 4.4.0 to 5.1.1).
Can anyone help me here?

Body:
Use: .debounce(.milliseconds(300), scheduler: MainScheduler.instance) instead. The debounce(_:scheduler:) that takes a Double has been removed.

Also, you are doing too much in your subscribe. You are better off if you break the subscribe up into independent units:

let searchText = searchTextField.rx.text.asObservable().skip(3)
    .debounce(.milliseconds(300), scheduler: MainScheduler.instance)
    .compactMap { $0 }

searchText
    .map { $0.isEmpty }
    .bind(to: clearButton.rx.isHidden)
    .disposed(by: disposeBag)

searchText
    .bind { [presenter] in
        presenter?.getAreaCodeList(text: $0)
    }
    .disposed(by: disposeBag)


问:
What exactly is Field Injection and how to avoid it?
I read in some posts about Spring MVC and Portlets that field injection is not recommended. As I understand it, field injection is when you inject a Bean with @Autowired like this:

```<code>@Component
public class MyComponent {
    @Autowired
    private Cart cart;
}
</code>```

During my research I also read about constructor injection:

```<code>@Component
public class MyComponent {
    private final Cart cart;

    @Autowired
    public MyComponent(Cart cart){
       this.cart = cart;
    }
}
</code>```

What are the advantages and the disadvantages of both of these types of injections?

EDIT 1: As this question is marked as duplicate of this question i checked it. Cause there aren't any code examples neither in the question nor in the answers it's not clear to me if i'm correct with my guess which injection type i'm using.

答:
One more comment - Vojtech Ruzicka stated that Spring injects beans in such three ways (the answer with the biggest numbers of points) :

Through a constructor

Through setters or other methods

Through reflection, directly into fields

This answer is WRONG - because FOR EVERY KIND OF INJECTION SPRING USES REFLECTION!
Use IDE, set breakpoint on setter / constructor, and check.

This can be a matter of taste but it can also be a matter of a CASE.
@dieter provided an excellent case when field injection is better. If You're using field injection in integration tests that are setting up Spring context - the argument with testability of the class is also invalid - unless You want to write later on tests to Your integration tests ;)

Body:
I read in some posts about Spring MVC and Portlets that field injection is not recommended. As I understand it, field injection is when you inject a Bean with @Autowired like this:

@Component
public class MyComponent {
    @Autowired
    private Cart cart;
}

During my research I also read about constructor injection:

@Component
public class MyComponent {
    private final Cart cart;

    @Autowired
    public MyComponent(Cart cart){
       this.cart = cart;
    }
}

What are the advantages and the disadvantages of both of these types of injections?

EDIT 1: As this question is marked as duplicate of this question i checked it. Cause there aren't any code examples neither in the question nor in the answers it's not clear to me if i'm correct with my guess which injection type i'm using.


问:
Can a PDA with two stacks accept RE Language?
So, I was having a bit of difficulty figuring what exactly is meant by a String on which Turing Machine does not halt. I read somewhere that a Turing Machine is equivalent to a deterministic automata with 2 stacks. But how will a deterministic automata with 2 stacks accept a string that doesn't halt when for any finite string it is determined to halt... Am I missing something??</p>

答:
A PDA with two stacks is equivalent to a Turing machine. To show a TM is at least as powerful as a two-stack PDA, we can use the fact that a TM is exactly as powerful as a two-tape TM. In a two-tape TM, we can restrict usage of the tapes to simulate their being stacks. So, certainly a TM can do whatever a two-stack PDA can do.

To show a PDA with two stacks is at least as powerful as a two-stack TM is a little trickier, but basically the idea is that you can simulate a single tape using the two stacks as follows:

Call one stack L and the other R

The contents of L represent everything to the left of the tape head (including the current symbol)

The contents of R represent everything to the right of the tape head

To overwrite the current symbol: pop from L and push to L

To move left in the tape: pop from L and push to R

To move right in the tape: pop from R and push to L

So, we can move left and right and overwrite symbols. This lets us simulate a tape, which is all a TM can do anyway.


问:
Trying to save API values into variables gives errors
So I am trying to save sellprice and buyprice from items in an API. The API consists of 190+ products, and it has a "sell_summary" and a "buy_summary", inside every "sell_summary" and "buy_summary" there is a "pricePerUnit", and that is what I am trying to access, to save into a variable. The values are float, and I have this to access them and save them in variables (productNames is a array with all product names):

```<code>for x in productNames:
        sell_Price = f["products"][x]["sell_summary"]
</code>```

This doesn't work as it gives me:

```<code>{'amount': 62, 'pricePerUnit': 1280.2, 'orders': 1}
</code>```

And I am only interested in "pricePerUnit", I also tried to have a ["pricePerUnit] after "sell_summary", but that gives me error TypeError: list indices must be integers or slices, not str. I then tried to add a [0] in between, but that gave me error IndexError: list index out of range.

I tried to attack this using arrays instead, and append the values like this:

```<code>sell_Price = []
    for x in productNames:
        sell_Price.append(f["products"][x]["sell_summary"][:1])
</code>```

(obs: I have to do [:1] as the API can consist of multiple "sections" with pricePerUnit, can be seen in this pastebin: https://pastebin.com/XwW4aQVR | only the top "pricePerUnit is interesting as that is latest updated).

But it gave me the same issue with displaying "amount", "pricePerUnit" and "orders". Tried doing [0]["pricePerUnit], but got same errors as before!

```<code>[0]["pricePerUnit"] = IndexError: list index out of range
[sell_summary][pricePerUnit] = TypeError: list indices must be integers or slices, not str
</code>```

I need to save these "pricePerUnit" values to run it through a script I have, that is supposed to calculate (depending on user input) how much they can buy of each product, and how much they can make by buying then selling it!

API link:
https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2

Body:
So I am trying to save sellprice and buyprice from items in an API. The API consists of 190+ products, and it has a "sell_summary" and a "buy_summary", inside every "sell_summary" and "buy_summary" there is a "pricePerUnit", and that is what I am trying to access, to save into a variable. The values are float, and I have this to access them and save them in variables (productNames is a array with all product names):

for x in productNames:
        sell_Price = f["products"][x]["sell_summary"]

This doesn't work as it gives me:

{'amount': 62, 'pricePerUnit': 1280.2, 'orders': 1}

And I am only interested in "pricePerUnit", I also tried to have a ["pricePerUnit] after "sell_summary", but that gives me error TypeError: list indices must be integers or slices, not str. I then tried to add a [0] in between, but that gave me error IndexError: list index out of range.

I tried to attack this using arrays instead, and append the values like this:

sell_Price = []
    for x in productNames:
        sell_Price.append(f["products"][x]["sell_summary"][:1])

(obs: I have to do [:1] as the API can consist of multiple "sections" with pricePerUnit, can be seen in this pastebin: https://pastebin.com/XwW4aQVR | only the top "pricePerUnit is interesting as that is latest updated).

But it gave me the same issue with displaying "amount", "pricePerUnit" and "orders". Tried doing [0]["pricePerUnit], but got same errors as before!

[0]["pricePerUnit"] = IndexError: list index out of range
[sell_summary][pricePerUnit] = TypeError: list indices must be integers or slices, not str

I need to save these "pricePerUnit" values to run it through a script I have, that is supposed to calculate (depending on user input) how much they can buy of each product, and how much they can make by buying then selling it!

API link:
https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2

Body:
Try this:

import requests

data = requests.get('https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2').json()
res = [product['sell_summary'][0]['pricePerUnit'] for product in data['products'].values() if product['sell_summary']]
print(res)

Output

[4.6, 13.3, 3.1, 66.7, 5.2, 652.6, 1039.6, 2638.9, 105560.6, 9641.0, 1130.5, 2428.0, 345.3, 838.4, 4.3, 476128.5, 4000.6, 3.8, 2005.7, 3.4, 1579.8, 8530.1, 3.9, 2510.4, 932.3, 1903.2, 15.0, 16.6, 23000.3, 7.3, 4422.7, 4.9, 26.7, 10.6, 2356.7, 3.5, 3550.5, 927.4, 22144.9, 11.0, 10.3, 1.7, 3.8, 29.4, 3.0, 595.5, 3.9, 84493.3, 19.1, 1.9, 1266.9, 62904.3, 2226.3, 111750.6, 1753.7, 881.9, 15275.3, 5.9, 667.2, 1.4, 1242.4, 8.7, 8.2, 511.2, 99.3, 785.8, 0.5, 8822.6, 7003.0, 38.2, 13.6, 225.7, 190.7, 1086.1, 1479.1, 236269.6, 1914.4, 63817.0, 207238.8, 1067.1, 421.3, 79499.2, 1.9, 2.8, 81384.8, 360458.7, 13.1, 386.3, 176250.8, 47973.2, 9.1, 17.6, 8.6, 21.1, 1339.3, 98003.3, 2.1, 0.7, 195.8, 22.7, 669.0, 14586.9, 3165.9, 1805.2, 640.1, 47433.5, 5.4, 25891.6, 6.0, 5.4, 591.9, 19435.8, 213667.3, 141335.7, 252100.5, 49.0, 5.0, 20.5, 6776.4, 194.2, 9103.6, 127661.0, 189429.9, 1380.1, 2651.8, 5.7, 152892.4, 473.1, 12.6, 10.4, 35312.0, 95945.5, 1873.9, 497131.4, 232073.2, 1106.2, 6700.7, 5960.9, 369.5, 1689.1, 205200.0, 236353.8, 5.7, 3580.4, 102838.4, 491.9, 4.9, 2639.7, 5108.3, 23.3, 275.1, 2.9, 19293.3, 3704.1, 1100.0, 9.7, 1571.7, 7.8, 175352.9, 391.6, 292445.9, 12.8, 4521.1, 18.6, 24818.1, 6.9, 4498.7, 5.7, 7.4, 37421.6, 642.8, 171720.1, 471.9, 1014.4, 13.9, 3070.3, 14.0, 16.7, 9.8, 785.3, 633.6, 8.1, 718454.0, 22.0, 1270.5, 164062.4, 16.8, 232260.1, 550.2, 57.8, 1750.4, 2800.7, 541161.8, 9.6, 100743.6, 6004.7, 1253.1]


问:
How to avoid Image Area showing Blue before Loading App
I am loading a rectangle logo saved as a .jpg into a CircleAvatar in my App.

When I am restarting my App, the area where the logo is loading appears blue for a few seconds. Then the real logo appears.

This Widget is found within a Stack.

This is how I transform my 1080x1073 image into a round logo within Flutter.

```<code> Container(
                width: size.width * 0.5,
                height: size.width * 0.5,
                child: CircleAvatar(
                  backgroundImage: AssetImage('assets/images/logo.jpg'),
                ),
              ),
</code>```

Does this happen because my image is too big? How should I handle this problem?

P.S. I am testing this on Visual Studio Code.

答:
By default the background color is set to blue, you can modify the property and it will show whatever color you assign to it.</p>

```<code>              Container(
                width: size.width * 0.5,
                height: size.width * 0.5,
                child: CircleAvatar(
                  backgroundColor: Colors.red, //here
                  backgroundImage: AssetImage('assets/images/logo.jpg'),
                ),
              ),
</code>```

Body:
I am loading a rectangle logo saved as a .jpg into a CircleAvatar in my App.

When I am restarting my App, the area where the logo is loading appears blue for a few seconds. Then the real logo appears.

This Widget is found within a Stack.

This is how I transform my 1080x1073 image into a round logo within Flutter.

 Container(
                width: size.width * 0.5,
                height: size.width * 0.5,
                child: CircleAvatar(
                  backgroundImage: AssetImage('assets/images/logo.jpg'),
                ),
              ),

Does this happen because my image is too big? How should I handle this problem?

P.S. I am testing this on Visual Studio Code.

Body:
By default the background color is set to blue, you can modify the property and it will show whatever color you assign to it.

              Container(
                width: size.width * 0.5,
                height: size.width * 0.5,
                child: CircleAvatar(
                  backgroundColor: Colors.red, //here
                  backgroundImage: AssetImage('assets/images/logo.jpg'),
                ),
              ),


答:
Ok so i git this for you:

you have to check if the sell_status is empty first:

for item in products:
    if products[item]["sell_summary"]:
        print(f'{item} sells for: {products[item]["sell_summary"][-1]["pricePerUnit"]}')
```

Title: Trying to save API values into variables gives errors


问:
How to RoundUp a decimal value with a base distinct from degree of 10?
A regular RoundUp function with a base of 10 looks as below:

```<code>public static decimal RoundUp(this decimal value, int decimals)
        {
            var k = (decimal)Math.Pow(10, decimals);
            return Math.Ceiling((value * k)) / k;
        }
</code>```

so it works like this:

```<code>decimal number = 10.12345m;
number.RoundUp(3) => 10.124
number.RoundUp(2) => 10.13
number.RoundUp(1) => 10.2
etc.
</code>```

I would like to have a function that rounds up to the nearest value as the following:

```<code>decimal number = 10.12345m;
number.RoundUp(0.1) => 10.2
number.RoundUp(0.25) => 10.25
number.RoundUp(2.0) => 12
number.RoundUp(5.0) => 15
number.RoundUp(10) => 20
</code>```

Note RoundUp by @basis means the result is dividable on the @basis without the rest:

```<code>RoundUp(10.12345m, 0.15) => 10.2   check 10.2 / 0.15 = 68
</code>```

neighbors are 10.05 and 10.35, so the correct rounding of 10.12345 is 10.2

```<code>RoundUp(5, 2.25) => 6.75   check 6.75 / 2.25 = 3
</code>```

i.e. 2.25x2 =4.50 is less than 5. so 5 round up by 2.25 will be 6.75

```<code>RoundUp(5, 2.50) => 5.0   check 5 / 2.5 = 2
</code>```

答:
You need to multiply the rounding factor by the ceiling of the division, as such:

```<code>public static decimal RoundUp(this decimal value, decimal round)
{
    return Math.Ceiling(value / round) * round;
}
</code>```

Dotnetfiddle doesn't support extension methods, but here's a proof of concept: https://dotnetfiddle.net/BIkLC3

If you want to round to the next decimal, you need to round the whole and the decimal separately:

```<code>public static decimal RoundUp(decimal number, decimal round)
{
    decimal numberDecimal = number - Math.Truncate(number);
    decimal roundDecimal = round - Math.Truncate(round);
    decimal numberWhole = number - numberDecimal;
    decimal roundWhole = round - roundDecimal;
    if (roundWhole > 0)
        numberWhole = Math.Ceiling(number / roundWhole) * roundWhole;
    if (roundDecimal > 0)
        roundDecimal = Math.Ceiling(numberDecimal / roundDecimal) * roundDecimal;
    return numberWhole + roundDecimal;
}
</code>```

Working fiddle: https://dotnetfiddle.net/vqf0jB

Body:
A regular RoundUp function with a base of 10 looks as below:

public static decimal RoundUp(this decimal value, int decimals)
        {
            var k = (decimal)Math.Pow(10, decimals);
            return Math.Ceiling((value * k)) / k;
        }

so it works like this:

decimal number = 10.12345m;
number.RoundUp(3) => 10.124
number.RoundUp(2) => 10.13
number.RoundUp(1) => 10.2
etc.

I would like to have a function that rounds up to the nearest value as the following:

decimal number = 10.12345m;
number.RoundUp(0.1) => 10.2
number.RoundUp(0.25) => 10.25
number.RoundUp(2.0) => 12
number.RoundUp(5.0) => 15
number.RoundUp(10) => 20

Note RoundUp by @basis means the result is dividable on the @basis without the rest:

RoundUp(10.12345m, 0.15) => 10.2   check 10.2 / 0.15 = 68

neighbors are 10.05 and 10.35, so the correct rounding of 10.12345 is 10.2

RoundUp(5, 2.25) => 6.75   check 6.75 / 2.25 = 3

i.e. 2.25x2 =4.50 is less than 5. so 5 round up by 2.25 will be 6.75

RoundUp(5, 2.50) => 5.0   check 5 / 2.5 = 2

Body:
You need to multiply the rounding factor by the ceiling of the division, as such:

public static decimal RoundUp(this decimal value, decimal round)
{
    return Math.Ceiling(value / round) * round;
}

Dotnetfiddle doesn't support extension methods, but here's a proof of concept: https://dotnetfiddle.net/BIkLC3

If you want to round to the next decimal, you need to round the whole and the decimal separately:

public static decimal RoundUp(decimal number, decimal round)
{
    decimal numberDecimal = number - Math.Truncate(number);
    decimal roundDecimal = round - Math.Truncate(round);
    decimal numberWhole = number - numberDecimal;
    decimal roundWhole = round - roundDecimal;
    if (roundWhole > 0)
        numberWhole = Math.Ceiling(number / roundWhole) * roundWhole;
    if (roundDecimal > 0)
        roundDecimal = Math.Ceiling(numberDecimal / roundDecimal) * roundDecimal;
    return numberWhole + roundDecimal;
}

Working fiddle: https://dotnetfiddle.net/vqf0jB


问:
List devices by IPs?
How could I list the devices by IP instead of name ?

I am aware that I can get the device name and description but since I have many devices installed it would be rather easier if I could get it by IP to select one, but I couldnt find any option related so I am wondering if there is an approach to it ?

```<code>foreach (var dev in CaptureDeviceList.Instance)
{
    var str = String.Format("{0} {1}", dev.Name, dev.Description);
    iDeviceDropDown.Items.Add(str);
}
</code>```

答: I see there is a ICaptureDevice.MacAddress property of type System.Net.NetworkInformation.PhysicalAddress. I don't think there is a direct way to get IP address from MAC Address but you can look it up using NetworkInterface.GetAllNetworkInterfaces();

Title: List devices by IPs?

Body:
How could I list the devices by IP instead of name ?

I am aware that I can get the device name and description but since I have many devices installed it would be rather easier if I could get it by IP to select one, but I couldnt find any option related so I am wondering if there is an approach to it ?

foreach (var dev in CaptureDeviceList.Instance)
{
    var str = String.Format("{0} {1}", dev.Name, dev.Description);
    iDeviceDropDown.Items.Add(str);
}


问:
How can I show specific texts inside a div by the click of a button?
I have a small text translated in 3 languages. I am looking to show the first text in English, and above the text to show two buttons, one that says French and one that says Italian. And I want once you click on French, to display the text in French, and the same with Italian. This means that I will have three separate divs, one for English, one for French and one for Italian. I only want to show one of them on the page, depending on which button I click. How can I do that? Thanks</p>

答:
$(function() {
  $('[data-lang="en"]').addClass('active');
  $('.flag').on('click', function() {
    $('[data-lang]').removeClass('active');
    $('[data-lang="' + $(this).data('lang') + '"]').addClass('active');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.flag.active {
  background-color: yellow;
}

.text {
  display: none;
}

.text.active {
  display: block;
}</code>```

<button data-lang="en" class="flag">English</button>
<button data-lang="fr" class="flag">Français</button>
<button data-lang="it" class="flag">Italiano</button>

My text in English

Mon texte en français

Il mio testo in italiano
```

Body:
$(function() {
  $('[data-lang="en"]').addClass('active');
  $('.flag').on('click', function() {
    $('[data-lang]').removeClass('active');
    $('[data-lang="' + $(this).data('lang') + '"]').addClass('active');
  });
});

.flag.active {
  background-color: yellow;
}

.text {
  display: none;
}

.text.active {
  display: block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-lang="en" class="flag">English</button>
<button data-lang="fr" class="flag">Français</button>
<button data-lang="it" class="flag">Italiano</button>
<div data-lang="en" class="text">My text in English</div>
<div data-lang="fr" class="text">Mon texte en français</div>
<div data-lang="it" class="text">Il mio testo in italiano</div>


问:
Solr vs Hibernate Search - Which to choose and When?
We are building an ecommerce application. We are using JAVA stack with Hibernate and Spring Framework. As with all ecommerce application, we need to build search capability into ours.

So, we came across Hibernate Search and Apache Solr . Can someone list out the pros and cons of both of them so that we can select the ideal solution for Enterprise Search?

答:
Hibernate search is a "bridge" between Hibernate and Lucene. In other words, it makes persisted Hibernate entities automagically searchable in Lucene index.

Solr is a framework built on top of Lucene (both projects are supposed to be merged one day, but it's a long way to go). Differences between Solr and Lucene are explained in another SO post.


问:
Update single value by point at it, without mutation and reconstructing object's initial structure JS
I'm looking for a way to better organize my actions/reducers, now it looks like this:

```<code>[SOME_ACTION]: state => ({
    ...state,
    isModified: true,
    orders: {
        ...state.orders
        // or maybe change something here
    },
    documentation: {
        ... state.documentation
       // or maybe change something here
    }
})
</code>```

The problem is that the object has deep nesting, and I have to keep track  of every level of it and add it everywhere accordingly. And I have to write all of that just to update a single value.

What are my options? For now I just want to be able to update one/several values on some level of nesting by just point on what I want to change.

答:
You only have to copy the object that changes and its parent objects, not its child objects. For instance, in your example I assume the change is isModified: true. You don't need to copy orders or documentation, you can reuse them because they haven't changed:

```<code>[SOME_ACTION]: state => ({
    ...state,
    isModified: true
})
</code>```

You can give yourself a utility function to do changes if you like. For instance:

```<code>function newState(state, path, value) {
    const result = {...state};
    const lastKey = path[path.length - 1];
    let obj = state;
    for (const key of path.slice(0, path.length - 1)) {
        obj = obj[key];
    }
    obj[lastKey] = value;
    return result;
}
</code>```

...or similar (that's off the cuff).

In that specific case it's not all that useful since the change is shallow:

```<code>[SOME_ACTION]: state => newState(state, ["isModified"], true)
</code>```

But if you had a change to make deeper in the structure:

```<code>[SOME_ACTION]: state => newState(state, ["orders", someOrderId, "fulfilled"], true)
</code>```

...it's a bit less of a pain to write than the equivalent:

```<code>[SOME_ACTION]: state => ({
    ..state,
    orders: {
        ...state.orders,
        [someOrderId]: {
            ...state.orders[someOrderId],
            fulfilled: true
        }
    }
})
</code>```

Example:

const state = {
    isModified: false,
    orders: {
        "order1": {
            customer: "Joe Bloggs",
            fulfilled: false
        },
        "order2": {
            customer: "Jane Doe",
            fulfilled: false
        }
    },
    documentation: {
        foo: {},
        bar: {}
    }
};

const someOrderId = Math.random() < 0.5 ? "order1" : "order2";
const updated = newState(state, ["orders", someOrderId, "fulfilled"], true);
console.log(`Updated order '${someOrderId}':`);
console.log(updated);

function newState(state, path, value) {
    const result = {...state};
    const lastKey = path[path.length - 1];
    let obj = state;
    for (const key of path.slice(0, path.length - 1)) {
        obj = obj[key];
    }
    obj[lastKey] = value;
    return result;
}```

Body:
I'm looking for a way to better organize my actions/reducers, now it looks like this:

[SOME_ACTION]: state => ({
    ...state,
    isModified: true,
    orders: {
        ...state.orders
        // or maybe change something here
    },
    documentation: {
        ... state.documentation
       // or maybe change something here
    }
})

The problem is that the object has deep nesting, and I have to keep track  of every level of it and add it everywhere accordingly. And I have to write all of that just to update a single value.

What are my options? For now I just want to be able to update one/several values on some level of nesting by just point on what I want to change.

Body:
You only have to copy the object that changes and its parent objects, not its child objects. For instance, in your example I assume the change is isModified: true. You don't need to copy orders or documentation, you can reuse them because they haven't changed:

[SOME_ACTION]: state => ({
    ...state,
    isModified: true
})

You can give yourself a utility function to do changes if you like. For instance:

function newState(state, path, value) {
    const result = {...state};
    const lastKey = path[path.length - 1];
    let obj = state;
    for (const key of path.slice(0, path.length - 1)) {
        obj = obj[key];
    }
    obj[lastKey] = value;
    return result;
}

...or similar (that's off the cuff).

In that specific case it's not all that useful since the change is shallow:

[SOME_ACTION]: state => newState(state, ["isModified"], true)

But if you had a change to make deeper in the structure:

[SOME_ACTION]: state => newState(state, ["orders", someOrderId, "fulfilled"], true)

...it's a bit less of a pain to write than the equivalent:

[SOME_ACTION]: state => ({
    ..state,
    orders: {
        ...state.orders,
        [someOrderId]: {
            ...state.orders[someOrderId],
            fulfilled: true
        }
    }
})

Example:

const state = {
    isModified: false,
    orders: {
        "order1": {
            customer: "Joe Bloggs",
            fulfilled: false
        },
        "order2": {
            customer: "Jane Doe",
            fulfilled: false
        }
    },
    documentation: {
        foo: {},
        bar: {}
    }
};

const someOrderId = Math.random() < 0.5 ? "order1" : "order2";
const updated = newState(state, ["orders", someOrderId, "fulfilled"], true);
console.log(`Updated order '${someOrderId}':`);
console.log(updated);

function newState(state, path, value) {
    const result = {...state};
    const lastKey = path[path.length - 1];
    let obj = state;
    for (const key of path.slice(0, path.length - 1)) {
        obj = obj[key];
    }
    obj[lastKey] = value;
    return result;
}


问:
Blynk.syncVirtual(V1) not updating Virtual Pins values
I was trying this code to run stepper motors and print Blynk app joystick's X and Y coordinates. But the code is only getting the joystick values once. But it works fine when I use if condition instead of while(). I needed while condition to run stepper motors continuously but with if condition they turn off and on very quickly decrease the speed of stepper motors.

Please help me deal this situation

Code

```<code>#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <AccelStepper.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "LRTCZUnCI06P-pqh5rlPXRbuOUgQ_uGH";

AccelStepper stepper_1(1,D2,D1);
AccelStepper stepper_2(1,D5,D6);

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Airtel_7599998800";
char pass[] = "air71454";

int prev_x = 0;
int prev_y = 0;

BLYNK_WRITE(V1) {
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("; Y = ");
  Serial.println(y);

  MoveControls(x , y);
}

void setup()
{
  // Debug console
  Serial.begin(9600);

  stepper_1.setAcceleration(1000);
  stepper_2.setAcceleration(1000);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
// ESP.wdtDisable();
// ESP.wdtEnable(WDTO_8S);
}

void loop()
{// ESP.wdtFeed();

  Blynk.run();
 // Serial.println("A");
}

void MoveControls(int x, int y) {

 ///////////////////////////////////////////Move Forward////////////////////////////////////////////////////

  if(y >= 150 && x <= 150 && x >= -150){
    stepper_1.enableOutputs();
    stepper_2.enableOutputs();

    stepper_1.setMaxSpeed(1000);
    stepper_2.setMaxSpeed(1000);

    stepper_1.move(1000);
    stepper_2.move(1000);

    while(x != prev_x && y != prev_y){

    stepper_1.run();
    stepper_2.run();

    Blynk.syncVirtual(V1);
    Blynk.run();

    Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);
    }

    prev_x = x;
    prev_y = y;

  }

 ///////////////////////////////////////////Neutral Zone////////////////////////////////////////////////////
 if(y <= 150 && x <= 150 && x >= -150 && y >= -150){
    stepper_1.disableOutputs();
    stepper_2.disableOutputs();

  prev_x = x;
  prev_y = y;
  }

  yield();
  }
</code>```

This is that while loop

```<code>while(x != prev_x && y != prev_y){

    stepper_1.run();
    stepper_2.run();

    Blynk.syncVirtual(V1);
    Blynk.run();

    Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);
    }

    prev_x = x;
    prev_y = y;

  }
</code>```

I know that the code is very much wrong and doesn't make much sense but I need to fix only the Blynk.syncVirtual() issue.

I also tried to add Blynk.run() after Blynk.syncVirtual() because someone told in Blynk Community to do that
https://community.blynk.cc/t/blynk-syncvirtual-doesnt-work-as-expected/40047/4

答: In your while loop you're setting prev_x = x && prev_y = y which is satisfying the condition of the while loop

Body:
I was trying this code to run stepper motors and print Blynk app joystick's X and Y coordinates. But the code is only getting the joystick values once. But it works fine when I use if condition instead of while(). I needed while condition to run stepper motors continuously but with if condition they turn off and on very quickly decrease the speed of stepper motors.

Please help me deal this situation

Code

#define BLYNK_PRINT Serial

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <AccelStepper.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "LRTCZUnCI06P-pqh5rlPXRbuOUgQ_uGH";

AccelStepper stepper_1(1,D2,D1);
AccelStepper stepper_2(1,D5,D6);

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Airtel_7599998800";
char pass[] = "air71454";

int prev_x = 0;
int prev_y = 0;

BLYNK_WRITE(V1) {
  int x = param[0].asInt();
  int y = param[1].asInt();

  // Do something with x and y
  Serial.print("X = ");
  Serial.print(x);
  Serial.print("; Y = ");
  Serial.println(y);

  MoveControls(x , y);
}

void setup()
{
  // Debug console
  Serial.begin(9600);

  stepper_1.setAcceleration(1000);
  stepper_2.setAcceleration(1000);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
// ESP.wdtDisable();
// ESP.wdtEnable(WDTO_8S);
}

void loop()
{// ESP.wdtFeed();

  Blynk.run();
 // Serial.println("A");
}

void MoveControls(int x, int y) {

 ///////////////////////////////////////////Move Forward////////////////////////////////////////////////////

  if(y >= 150 && x <= 150 && x >= -150){
    stepper_1.enableOutputs();
    stepper_2.enableOutputs();

    stepper_1.setMaxSpeed(1000);
    stepper_2.setMaxSpeed(1000);

    stepper_1.move(1000);
    stepper_2.move(1000);

    while(x != prev_x && y != prev_y){

    stepper_1.run();
    stepper_2.run();

    Blynk.syncVirtual(V1);
    Blynk.run();

    Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);
    }

    prev_x = x;
    prev_y = y;

  }

 ///////////////////////////////////////////Neutral Zone////////////////////////////////////////////////////
 if(y <= 150 && x <= 150 && x >= -150 && y >= -150){
    stepper_1.disableOutputs();
    stepper_2.disableOutputs();

  prev_x = x;
  prev_y = y;
  }

  yield();
  }

This is that while loop

while(x != prev_x && y != prev_y){

    stepper_1.run();
    stepper_2.run();

    Blynk.syncVirtual(V1);
    Blynk.run();

    Serial.print("X = ");
    Serial.print(x);
    Serial.print("; Y = ");
    Serial.println(y);
    }

    prev_x = x;
    prev_y = y;

  }

I know that the code is very much wrong and doesn't make much sense but I need to fix only the Blynk.syncVirtual() issue.

I also tried to add Blynk.run() after Blynk.syncVirtual() because someone told in Blynk Community to do that
https://community.blynk.cc/t/blynk-syncvirtual-doesnt-work-as-expected/40047/4


问:
Deepsecurity's Management Console
asked DSM and solved Thank you very much.</p>

答:
Trend Micro Deep Security Manager runs on port 4119 by default, which is unlikely to be in-use by other products.  Please see https://help.deepsecurity.trendmicro.com/12_0/on-premise/Manage-Components/ports.html for more details.

I am a Trend Micro employee.

Thanks,
Nick

Title: Deepsecurity's Management Console


问:
Could not transfer artifact from/to central because of InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
When I try to install the pom.xml of maven project, I get the following error. Please help.

Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.6:resources (default-resources) on project pm: Execution default-resources of goal org.apache.maven.plugins:maven-resources-plugin:2.6:resources failed: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved: Could not transfer artifact classworlds:classworlds:jar:1.1 from/to central (https://repo.maven.apache.org/maven2): java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty

答:
Had the same issue, found
https://groups.google.com/d/msg/osv-dev/wFzT12-p2bw/vT42CiuOBQAJ
which recommended

$ sudo apt install openjdk-8-jre
$ sudo rm /etc/ssl/certs/java/cacerts
$ sudo update-ca-certificates --fresh
```

Worked first try for me, so leaving it here if anyone else stumbles upon this.

Body:
Had the same issue, found
https://groups.google.com/d/msg/osv-dev/wFzT12-p2bw/vT42CiuOBQAJ
which recommended

$ sudo apt install openjdk-8-jre
$ sudo rm /etc/ssl/certs/java/cacerts
$ sudo update-ca-certificates --fresh

Worked first try for me, so leaving it here if anyone else stumbles upon this.


问:
Need a Regular expresssion that should not allow only space in string, It can allow spaces along with characters
Need a Regular expresssion that should not allow  only space  in string, It can allow spaces along  with characters.

e.g: space+char+space  is  allowed  where  as  only  space  is not allowed

答: /\S/ is sufficient to match a non-empty string.