问:
Can't upload files in spring boot
I've been struggling with this for the past 3 days now, I keep getting the following exception when I try upload a file in my spring boot project.
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present

I'm not sure if it makes a differance but I am deploying my application as a war onto weblogic,
here is my controller

@PostMapping
public AttachmentDto createAttachment(@RequestParam(value = "file") MultipartFile file) {
    logger.info("createAttachment - {}", file.getOriginalFilename());
    AttachmentDto attachmentDto = null;
    try {
        attachmentDto = attachmentService.createAttachment(new AttachmentDto(file, 1088708753L));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return attachmentDto;
}
```

multi part beans I can see in spring boot actuator

payload seen in chrome

答:
None of the above solutions worked for me, but when I digged deeper i found that spring security was the main culprit. Even if i was sending the CSRF token, I repeatedly faced the issue POST not supported. I came to know that i was receiving forbidden 403 when i inspected using developer tools in google chrome and saw the status code in the network tab. I added the mapping to ignoredCsrfMapping in Spring Security configuration and then it worked absolutely without any other flaw. Don't know why i was not allowed to post multipart data by security. Some of the mandatory setting that needs to be stated in application.properties file are as follows:</p>

```<code>spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
spring.http.multipart.enabled=true
</code>```

Title: Can't upload files in spring boot

Body:
I've been struggling with this for the past 3 days now, I keep getting the following exception when I try upload a file in my spring boot project.
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present

I'm not sure if it makes a differance but I am deploying my application as a war onto weblogic,
here is my controller

@PostMapping
public AttachmentDto createAttachment(@RequestParam(value = "file") MultipartFile file) {
    logger.info("createAttachment - {}", file.getOriginalFilename());
    AttachmentDto attachmentDto = null;
    try {
        attachmentDto = attachmentService.createAttachment(new AttachmentDto(file, 1088708753L));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return attachmentDto;
}

multi part beans I can see in spring boot actuator

payload seen in chrome

Body:
None of the above solutions worked for me, but when I digged deeper i found that spring security was the main culprit. Even if i was sending the CSRF token, I repeatedly faced the issue POST not supported. I came to know that i was receiving forbidden 403 when i inspected using developer tools in google chrome and saw the status code in the network tab. I added the mapping to ignoredCsrfMapping in Spring Security configuration and then it worked absolutely without any other flaw. Don't know why i was not allowed to post multipart data by security. Some of the mandatory setting that needs to be stated in application.properties file are as follows:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
spring.http.multipart.enabled=true


来源: stackexchange

问:
CORB ISSUE IN IONIC 3
i am getting Cross-Origin Read Blocking (CORB) blocked cross-origin response with MIME type application/json.

```<code>SyntaxError</b>: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.js:1091)
    at MapSubscriber.project (auth.service.ts:29)
    at MapSubscriber._next (map.js:79)
    at MapSubscriber.Subscriber.next (Subscriber.js:93)
    at CatchSubscriber.Subscriber._next (Subscriber.js:129)
    at CatchSubscriber.Subscriber.next (Subscriber.js:93)
    at TimeoutSubscriber.Subscriber._next (Subscriber.js:129)
    at TimeoutSubscriber._next (timeout.js:132)
    at TimeoutSubscriber.Subscriber.next (Subscriber.js:93)
</code>```

Is there any way to bypass this?

答: To Solve the problem of corb issue in ionic. In server end you need to add Access-Control-Allow-Origin type in the header. Furthermore please check this screenshot and make changes according to your backend platform

ContentLicense: CC BY-SA 4.0

Title: CORB ISSUE IN IONIC 3

Body:
i am getting Cross-Origin Read Blocking (CORB) blocked cross-origin response with MIME type application/json.

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Response.Body.json (http.js:1091)
    at MapSubscriber.project (auth.service.ts:29)
    at MapSubscriber._next (map.js:79)
    at MapSubscriber.Subscriber.next (Subscriber.js:93)
    at CatchSubscriber.Subscriber._next (Subscriber.js:129)
    at CatchSubscriber.Subscriber.next (Subscriber.js:93)
    at TimeoutSubscriber.Subscriber._next (Subscriber.js:129)
    at TimeoutSubscriber._next (timeout.js:132)
    at TimeoutSubscriber.Subscriber.next (Subscriber.js:93)

Is there any way to bypass this?


问:
How do I test a method defined within a functional component, that interacts with DOM elements and has no arguments
I have been having trouble getting 100% test coverage on one of my buttons (A React functional components.) Basically when it is clicked, it executes some code and then also calls another method from within this onClick called resetButtons. This method will find all the buttons like it in the app and remove a class. This is a preemptive behavior so that only one button at a time can be active.

So far I have tested the click using .simulate, passing in a mocked domElement. And then test that the domElement.classList.add method is called with 'active'.

Obviously this being a DOM centered operation, I am finding it very difficult to test the resetButtons method that lies within the component. especially considering it doesn't have any methods.

I have tried defining the resetButtons method outside of the component and then exported it so the jest test could import it. However I have been unable to test the method as it seems to want it to be a spy or mock, and not the method itself. (Matcher error: received value must be a mock or spy function
)

Here is the react Functional Component:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import classes from './MainButton.module.scss';

const MainButton = (props) => {
  const resetButtons = () => {
    const elements = document.getElementsByClassName('mainButton');
    for (let i = 0; i < elements.length; i += 1) {
      elements[i].classList.remove('active');
    }
  };

  const handleClick = (event) => {
    if (!event.target.classList.contains('active')) {
      resetButtons();
      event.target.classList.add('active');
      props.setVisualState(props.className.split('-')[0]);
    }
  };

  return (
    <button
      onClick={handleClick}
      type="button"
      className={`${classes.mainButton} ${props.className}`}
    >
      {props.children}
    </button>
  );
};

MainButton.propTypes = {
  children: PropTypes.node,
  className: PropTypes.string,
  setVisualState: PropTypes.func.isRequired,
};

MainButton.defaultProps = {
  children: 'Button',
  className: '',
};

export default MainButton;

</code>```

Here is the Test

```<code>import React from 'react';
import { shallow } from 'enzyme';
import MainButton from './MainButton';

describe('MainButton', () => {
  const domElement = { classList: { contains: jest.fn(), remove: jest.fn(), add: jest.fn() } };
  const setVisualStateMock = jest.fn();
  const mainButton = shallow(<MainButton setVisualState={setVisualStateMock} />);

  it(' is rendered properly', () => {
    expect(mainButton).toMatchSnapshot();
  });

  describe('when clicked', () => {
    beforeEach(() => {
      mainButton.find('button').simulate('click', { target: domElement });
    });

    it('it runs `classlist.add` to assign `active` class', () => {
      expect(domElement.classList.add).toHaveBeenCalledWith('active');
    });

    it('it runs set visual state to update `Allergen` container `state`', () => {
      expect(setVisualStateMock).toHaveBeenCalled();
    });
  });
});
</code>```

Currently the coverage report is reporting 92% coverage, but the branch is at 50 and the line that is causing the trouble is on line 9 (the elements[i].classList.remove('active'); line.

I know at 90% I should probably just move on but this is something I want to be able to figure out. Feel like getting head around this will make me a better tested.

Hope you guys can help!

答:
You should be able to mount multiple MainButtons, click one and expect that the other(s) had domElement.classList.remove called on them.

However, user konqi is right in that React provides better ways of manipulating elements/components.

You could replace this test:

```<code>expect(domElement.classList.add).toHaveBeenCalledWith('active');
</code>```

with a test that checks that the button has (or does not have) the active className (instead of checking that the function was called with the right argument). With that test in place, if you like, you could refactor this in the way that konqi suggests.

Body:
I have been having trouble getting 100% test coverage on one of my buttons (A React functional components.) Basically when it is clicked, it executes some code and then also calls another method from within this onClick called resetButtons. This method will find all the buttons like it in the app and remove a class. This is a preemptive behavior so that only one button at a time can be active.

So far I have tested the click using .simulate, passing in a mocked domElement. And then test that the domElement.classList.add method is called with 'active'.

Obviously this being a DOM centered operation, I am finding it very difficult to test the resetButtons method that lies within the component. especially considering it doesn't have any methods.

I have tried defining the resetButtons method outside of the component and then exported it so the jest test could import it. However I have been unable to test the method as it seems to want it to be a spy or mock, and not the method itself. (Matcher error: received value must be a mock or spy function
)

Here is the react Functional Component:

import React from 'react';
import PropTypes from 'prop-types';
import classes from './MainButton.module.scss';

const MainButton = (props) => {
  const resetButtons = () => {
    const elements = document.getElementsByClassName('mainButton');
    for (let i = 0; i < elements.length; i += 1) {
      elements[i].classList.remove('active');
    }
  };

  const handleClick = (event) => {
    if (!event.target.classList.contains('active')) {
      resetButtons();
      event.target.classList.add('active');
      props.setVisualState(props.className.split('-')[0]);
    }
  };

  return (
    <button
      onClick={handleClick}
      type="button"
      className={`${classes.mainButton} ${props.className}`}
    >
      {props.children}
    </button>
  );
};

MainButton.propTypes = {
  children: PropTypes.node,
  className: PropTypes.string,
  setVisualState: PropTypes.func.isRequired,
};

MainButton.defaultProps = {
  children: 'Button',
  className: '',
};

export default MainButton;

Here is the Test

import React from 'react';
import { shallow } from 'enzyme';
import MainButton from './MainButton';

describe('MainButton', () => {
  const domElement = { classList: { contains: jest.fn(), remove: jest.fn(), add: jest.fn() } };
  const setVisualStateMock = jest.fn();
  const mainButton = shallow(<MainButton setVisualState={setVisualStateMock} />);

  it(' is rendered properly', () => {
    expect(mainButton).toMatchSnapshot();
  });

  describe('when clicked', () => {
    beforeEach(() => {
      mainButton.find('button').simulate('click', { target: domElement });
    });

    it('it runs `classlist.add` to assign `active` class', () => {
      expect(domElement.classList.add).toHaveBeenCalledWith('active');
    });

    it('it runs set visual state to update `Allergen` container `state`', () => {
      expect(setVisualStateMock).toHaveBeenCalled();
    });
  });
});

Currently the coverage report is reporting 92% coverage, but the branch is at 50 and the line that is causing the trouble is on line 9 (the elements[i].classList.remove('active'); line.

I know at 90% I should probably just move on but this is something I want to be able to figure out. Feel like getting head around this will make me a better tested.

Hope you guys can help!

Body:
You should be able to mount multiple MainButtons, click one and expect that the other(s) had domElement.classList.remove called on them.

However, user konqi is right in that React provides better ways of manipulating elements/components.

You could replace this test:

expect(domElement.classList.add).toHaveBeenCalledWith('active');

with a test that checks that the button has (or does not have) the active className (instead of checking that the function was called with the right argument). With that test in place, if you like, you could refactor this in the way that konqi suggests.


问:
Swift - Unable to open file in target Xcode 10
I am trying to run Aplication which I have downloaded from GitHub.

When I run get error unable to open file in target, I have Xcode 10.

I already searched for solution and get this one.

I had the same problem, but in Xcode 6.1.1 - what fixed it for me was to change the configuration file setting to None for the two Pods-related targets, then run pod install again.

The configuration file setting is found by selecting the project (not the target) and then the Info tab.

But cant find configuration file location.

Here is the error picture:
https://i.stack.imgur.com/Ql3M5.png

答:
I had this issue too with project I cloned from GitLab. Your error looks extremely similar to mine. I solved it by running this in Terminal:

```<code>cd path/to/your/project
pod install
</code>```

When I checked project folder in Finder, there was a Podfile. But same project viewed in Xcode had nothing under 'Pods' module. From this I figured out the pods are not installed (or installed properly?) and installing them solved this error.

If there is some Pods or .xcworkspace file, it might be worth doing pod deintegrate before installation - just to be sure :)

Body:
I had this issue too with project I cloned from GitLab. Your error looks extremely similar to mine. I solved it by running this in Terminal:

cd path/to/your/project
pod install

When I checked project folder in Finder, there was a Podfile. But same project viewed in Xcode had nothing under 'Pods' module. From this I figured out the pods are not installed (or installed properly?) and installing them solved this error.

If there is some Pods or .xcworkspace file, it might be worth doing pod deintegrate before installation - just to be sure :)


问:
Forms Authentication: How to change the Username using LINq
I have a system whereby an administrator enters in the IT credentials for users who use the system.
Included in this is the Username for that person.
However if she makes a mistake, I am not sure how she can correct it.
I am using Forms Authentication, MVC and Entity Framework 4.0.
I am using the aspnetdb database supplied by Microsoft with the User credentials.

One possible solution is to delete and then create the user with the new username. But the problem then is that I lose the password.

Should I create a model of the database in EF so I can modify the database, or should I try something else like stored procedures?

答: I think the easiest will be to create a stored procedure that will update just the UserName field in aspnet_Users table

ContentLicense: CC BY-SA 3.0


问:
Drawing full screen chessboard pattern?
I'm working in OpenCV (camera calibration and then creating 3d model) and till now I always printed a checkerboard pattern on paper and then took pictures needed for calibration. I tried to find a way to draw the pattern on the full screen with pre-defined square sizes (so I could set that square size in the calibration process), but I only found the Python turtle module which seems to only be for drawing on part of screen, and it always draws an arrow on last square. I need to draw the pattern with some small offset from the screen borders and, inside those offsets, draw a checkerboard with uniform squares. Also, I saw some people are drawing patterns in GIMP, but not on the full screen.

OpenCV has the function drawChessboardCorners but it requires founded corners from previous imported images, which need to be calibrated, so I think it doesn't make sense.

If anybody has an idea how to solve this problem, either with some program or module in some programming language (Python if possible), I would be grateful.

答:
I only found turtle module which seems to be only for drawing on part
  of screen and it always draws arrow on last square.

Let's dispense with these two issues by drawing a grid in a window the size of the screen with no arrow on the last square:

```<code>from turtle import Screen, Turtle

BLOCK_SIZE = 72  # pixels
CURSOR_SIZE = 20  # pixels

BORDER = 1  # blocks

screen = Screen()
screen.setup(1.0, 1.0)  # display size window
width, height = screen.window_width(), screen.window_height()
screen.setworldcoordinates(0, 0, width, height)

block = Turtle('square', visible=False)  # hide the cursor completely
block.pencolor('black')
block.shapesize(BLOCK_SIZE / CURSOR_SIZE)
block.penup()

x_count = width // BLOCK_SIZE - BORDER * 2
x_width = x_count * BLOCK_SIZE
x_start = (width - x_width) // 2
x_limit = x_width + (BORDER + 1) * BLOCK_SIZE

y_count = height // BLOCK_SIZE - BORDER * 2
y_height = y_count * BLOCK_SIZE
y_start = (height - y_height) // 2
y_limit = y_height + (BORDER + 1) * BLOCK_SIZE

screen.tracer(False)

for parity_y, y in enumerate(range(y_start, y_limit, BLOCK_SIZE)):
    block.sety(y)

    for parity_x, x in enumerate(range(x_start, x_limit, BLOCK_SIZE)):
        block.fillcolor(['white', 'black'][(parity_y % 2) == (parity_x % 2)])
        block.setx(x)
        block.stamp()

screen.tracer(True)
screen.mainloop()
</code>```

(Hide your dock in OS X if you want to cover even more of the screen.)

Unfortunately, this is drawing in pixel units which is arbitrary.  See my answer about drawing in a standardized measure using the pixel pitch value of your display.

Title: Drawing full screen chessboard pattern?

Body:
I only found turtle module which seems to be only for drawing on part
  of screen and it always draws arrow on last square.

Let's dispense with these two issues by drawing a grid in a window the size of the screen with no arrow on the last square:

from turtle import Screen, Turtle

BLOCK_SIZE = 72  # pixels
CURSOR_SIZE = 20  # pixels

BORDER = 1  # blocks

screen = Screen()
screen.setup(1.0, 1.0)  # display size window
width, height = screen.window_width(), screen.window_height()
screen.setworldcoordinates(0, 0, width, height)

block = Turtle('square', visible=False)  # hide the cursor completely
block.pencolor('black')
block.shapesize(BLOCK_SIZE / CURSOR_SIZE)
block.penup()

x_count = width // BLOCK_SIZE - BORDER * 2
x_width = x_count * BLOCK_SIZE
x_start = (width - x_width) // 2
x_limit = x_width + (BORDER + 1) * BLOCK_SIZE

y_count = height // BLOCK_SIZE - BORDER * 2
y_height = y_count * BLOCK_SIZE
y_start = (height - y_height) // 2
y_limit = y_height + (BORDER + 1) * BLOCK_SIZE

screen.tracer(False)

for parity_y, y in enumerate(range(y_start, y_limit, BLOCK_SIZE)):
    block.sety(y)

    for parity_x, x in enumerate(range(x_start, x_limit, BLOCK_SIZE)):
        block.fillcolor(['white', 'black'][(parity_y % 2) == (parity_x % 2)])
        block.setx(x)
        block.stamp()

screen.tracer(True)
screen.mainloop()

(Hide your dock in OS X if you want to cover even more of the screen.)

Unfortunately, this is drawing in pixel units which is arbitrary.  See my answer about drawing in a standardized measure using the pixel pitch value of your display.


问:
Why I am getting syntax error in selenium relative xpath?
I am an absolute beginner in programming and trying to locate an element from a webtool using Selenium and Python. I had to look for relative path since absolute path DIV value keep changing. Using ChroPath I found the relative path.

Absolute path is:
/html/body/div[4]/div/div/div/div/div[5]/div/div[31]/div/table/tbody/tr[2]/td[2]/div/div/table/tbody/tr/td/div

here element which is at div[31] sometimes becomes div[30] or div[32]. I searched web and found that I need to look for relative path instead of absolute path.

So I tried relative path method.

HTML line:

//div class="vp-btnc-text" xpath="1">CS-CORE Capacity Planning

Relative path provided by Chropath:
//div[contains(text(),'CS-CORE Capacity Planning')]

My line in code that I am trying is :
driver.find_element_by_xpath('//div[contains(text(),'CS-CORE Capacity Planning')]').click()

Error that I am getting is:
driver.find_element_by_xpath('//div[contains(text(),'CS-CORE Capacity Planning')]')
                                                          ^
SyntaxError: invalid syntax

Need help to resolve the issue please.

答:
Maybe add an explicit wait time or implicit wait
Example:

```<code>WebElement messageElement = wait.until( ExpectedConditions.presenceOfElementLocated(By.id("AnotherElementBeforeThisElementIsLoaded")) );
</code>```

or implicit wait:

```<code>driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
</code>```

Also,

```<code>driver.findElement(by.xpath(//divclass='vp-btnc-text' xpath='1'>CS-CORE Capacity Planning));
</code>```

Sometime,you need to change double quotes to single quotes for xpath.

Body:
Maybe add an explicit wait time or implicit wait
Example:

WebElement messageElement = wait.until( ExpectedConditions.presenceOfElementLocated(By.id("AnotherElementBeforeThisElementIsLoaded")) );

or implicit wait:

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Also,

driver.findElement(by.xpath(//divclass='vp-btnc-text' xpath='1'>CS-CORE Capacity Planning));

Sometime,you need to change double quotes to single quotes for xpath.


问:
C# statement inside using block returns null
I'm new to C# and curious about next example:

Imagine we have such code:

```<code>private static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
    }
    return output.ToArray();
}
</code>```

And:

```<code>private static byte[] Compress(byte[] data)
{
    using (var output = new MemoryStream())
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
        return output.ToArray();
    }
}
</code>```

The first example works as expected, while the latter just returns null.
How does using work internally?
I expect it to work like simple try/finally, but it seems it closes MemoryStream before invoking toArray.

On the other hand following code works as expected too, which brings even more mysteriousness:

```<code>private static byte[] Decompress(byte[] payload)
{
   using(var inputStream = new MemoryStream(payload))
   using(var outputStream = new MemoryStream())
   using (var deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress))
   {
       deflateStream.CopyTo(outputStream);
       return outputStream.ToArray();
   }
}
</code>```

答:
The behaviour you are seeing is because for many Stream implementations, data that is written to the stream is not necessarily immediately acted on and pushed to its final destination. That might be for reasons of performance, such as a FileStream buffering up data in memory to write before physically writing to disk, or because the final output is not known until all the input data is available - such as a cryptographic stream where the output has to be a certain size and the end of the data may have to be padded. So, unless you are certain of the implementation, you can only assume all the data is available once the Stream is disposed or closed.

So in your first example,

```<code>private static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
    }
    return output.ToArray();
}
</code>```

Here the using statement disposes the DeflateStream which triggers it to send all the output to the MemoryStream. You call ToArray() on the MemoryStream, and it has the output as you would expect.

However, in your second example:

```<code>using (var output = new MemoryStream())
using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
{
    deflateStream.Write(data, 0, data.Length);
    return output.ToArray();
}
</code>```

You are returning the content of the MemoryStream before DeflateStream is disposed, because the call is inside the second using block. At that point, DeflateStream has not had the Dispose call which triggers it to write its compressed data to the output stream, and so the MemoryStream is empty and you get a null result.

For your final example, CopyTo generally reads from one stream into a buffer, and then writes that buffer to the target stream until all the input data is read. So in the case, it works because data is still written to the MemoryStream before you return the result.

Body:
I'm new to C# and curious about next example:

Imagine we have such code:

private static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
    }
    return output.ToArray();
}

And:

private static byte[] Compress(byte[] data)
{
    using (var output = new MemoryStream())
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
        return output.ToArray();
    }
}

The first example works as expected, while the latter just returns null.
How does using work internally?
I expect it to work like simple try/finally, but it seems it closes MemoryStream before invoking toArray.

On the other hand following code works as expected too, which brings even more mysteriousness:

private static byte[] Decompress(byte[] payload)
{
   using(var inputStream = new MemoryStream(payload))
   using(var outputStream = new MemoryStream())
   using (var deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress))
   {
       deflateStream.CopyTo(outputStream);
       return outputStream.ToArray();
   }
}

Body:
The behaviour you are seeing is because for many Stream implementations, data that is written to the stream is not necessarily immediately acted on and pushed to its final destination. That might be for reasons of performance, such as a FileStream buffering up data in memory to write before physically writing to disk, or because the final output is not known until all the input data is available - such as a cryptographic stream where the output has to be a certain size and the end of the data may have to be padded. So, unless you are certain of the implementation, you can only assume all the data is available once the Stream is disposed or closed.

So in your first example,

private static byte[] Compress(byte[] data)
{
    var output = new MemoryStream();
    using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
    {
        deflateStream.Write(data, 0, data.Length);
    }
    return output.ToArray();
}

Here the using statement disposes the DeflateStream which triggers it to send all the output to the MemoryStream. You call ToArray() on the MemoryStream, and it has the output as you would expect.

However, in your second example:

using (var output = new MemoryStream())
using (var deflateStream = new DeflateStream(output, CompressionLevel.Fastest))
{
    deflateStream.Write(data, 0, data.Length);
    return output.ToArray();
}

You are returning the content of the MemoryStream before DeflateStream is disposed, because the call is inside the second using block. At that point, DeflateStream has not had the Dispose call which triggers it to write its compressed data to the output stream, and so the MemoryStream is empty and you get a null result.

For your final example, CopyTo generally reads from one stream into a buffer, and then writes that buffer to the target stream until all the input data is read. So in the case, it works because data is still written to the MemoryStream before you return the result.


问:
Strange texture result when mix two camera textures in glsl
I'm making a simple image filter app in android and I implemented lowpass filter using same method in GPUImage(https://github.com/BradLarson/GPUImage)

it buffers the previous and current camera frames mixture and render it.
So i created a buffer FBO and render the current camera texture, re-use it as a texture for mixture in lowpass filter shader with next camera texture.

I tested my code with some smartphones(Galaxy S10, Nexus 6P, etc..) and it worked well. However in Galaxy S8(Mali-G71) the result is strange and I don't know what was wrong.

These are the wrong results

Here are my code:

```<code>Fragment shader:
varying vec2 vTextureCoord;
uniform sampler2D sTexture1;
uniform float filterStrength;

void main() {
    vec4 texColor0 = texture2D(sTexture, vTextureCoord);
    vec4 texColor1 = texture2D(sTexture1, vTextureCoord);
    gl_FragColor = mix(texColor0, texColor1, filterStrength);
}
</code>```

What can cause this results?
Thanks in advance.

答:
The artifacts look tile aligned for Mali, so if I had to guess you are reading the currently bound framebuffer color attachment as an input texture at the same time as writing in to it.

This is "implementation defined" behavior in the specification, and concurrent reads and writes will definitely do bad things on a tile-based renderer like Mali.

Body:
I'm making a simple image filter app in android and I implemented lowpass filter using same method in GPUImage(https://github.com/BradLarson/GPUImage)

it buffers the previous and current camera frames mixture and render it.
So i created a buffer FBO and render the current camera texture, re-use it as a texture for mixture in lowpass filter shader with next camera texture.

I tested my code with some smartphones(Galaxy S10, Nexus 6P, etc..) and it worked well. However in Galaxy S8(Mali-G71) the result is strange and I don't know what was wrong.

These are the wrong results

Here are my code:

Fragment shader:
varying vec2 vTextureCoord;
uniform sampler2D sTexture1;
uniform float filterStrength;

void main() {
    vec4 texColor0 = texture2D(sTexture, vTextureCoord);
    vec4 texColor1 = texture2D(sTexture1, vTextureCoord);
    gl_FragColor = mix(texColor0, texColor1, filterStrength);
}

What can cause this results?
Thanks in advance.


问:
How to split each digit of a number into different rows
I want something like SELECT splitDigits(123456789) as digits to return:

 digits
-------
  1
  2
  3
  4
  5
  6
  7
  8
  9
```

What I really need

I'm trying to make this validation (Perú's RUC ID) in a stored procedure:

I'm trying to avoid loops so I'm stuck in the first step, which is to grab the first 10 digits and multiply each digit by a fixed scalar that depends on the position, then I have to sum all those multiplications.

It's basically vector multiplication, and I'm trying to construct a vector from the first 10 digit of an 11-digit-number.

Body:
I want something like SELECT splitDigits(123456789) as digits to return:

 digits
-------
  1
  2
  3
  4
  5
  6
  7
  8
  9

What I really need

I'm trying to make this validation (Perú's RUC ID) in a stored procedure:

I'm trying to avoid loops so I'm stuck in the first step, which is to grab the first 10 digits and multiply each digit by a fixed scalar that depends on the position, then I have to sum all those multiplications.

It's basically vector multiplication, and I'm trying to construct a vector from the first 10 digit of an 11-digit-number.

Body:
Since the format of number is fixed you just need some basic math:

SELECT num div          10 % 10 * 2
     + num div         100 % 10 * 3
     + num div        1000 % 10 * 4
     + num div       10000 % 10 * 5
     + num div      100000 % 10 * 6
     + num div     1000000 % 10 * 7
     + num div    10000000 % 10 * 2
     + num div   100000000 % 10 * 3
     + num div  1000000000 % 10 * 4
     + num div 10000000000 % 10 * 5 AS s
FROM (
    SELECT 20503644968 AS num
) AS t
-- 157


问:
Is it possible to display element index as a comment?
I am initializing a list with data using a collection initializer. Since there's quite a few elements in the list it is hard to keep track of the index of each element. As such I have been keeping track of the index manually using comments, but this leads to extra work keeping the indices up to date. Is there a tool or script that will automatically do this for me? Alternately is there any solution not involving comments?

var list = new List<Element>
{
    new Element() // 0 <-- I want to keep this number up to date
    {
        // Data
    }
    new Element() // 1
    {
        // Data
    }
    new Element() // 2
    {
        // Data
    }
}
```

答:
You might want to explore using Dictionaries for this purpose, though it's hard to know what you're hoping to do with your List. A Dictionary is a collection of keys and values and you can get to the value via the key. For example:

```<code>var myDictionary = new Dictionary<int, Element>();
myDictionary.Add(1, new Element{
        PropertyA = "sss",
        PropertyB = 1234,
    })
</code>```

etc. You can then get and set the keys as needed.

Not certain, but your question kind of "feels" like a dictionary type question. You shouldn't be using indices on Lists in the structured way you seem to be wanting to

see:
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8

Body:
You might want to explore using Dictionaries for this purpose, though it's hard to know what you're hoping to do with your List. A Dictionary is a collection of keys and values and you can get to the value via the key. For example:

var myDictionary = new Dictionary<int, Element>();
myDictionary.Add(1, new Element{
        PropertyA = "sss",
        PropertyB = 1234,
    })

etc. You can then get and set the keys as needed.

Not certain, but your question kind of "feels" like a dictionary type question. You shouldn't be using indices on Lists in the structured way you seem to be wanting to

see:
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8


问:
How to edit "Reference Resolution" by script in Unity?
I want to change Reference Resolutuion with C# script in real time game, how can I make it?

Because I want to scale my controls with easiest way

答:
UI Scale Mode: Constant Pixel Size

Simple template:

```<code>public class Scale : MonoBehaviour {

    public float scale = 1f; // 1 by default

    public void Update()
    {
        GetComponent<Canvas>().scaleFactor = scale;
    }
}
</code>```

Body:
UI Scale Mode: Constant Pixel Size

Simple template:

public class Scale : MonoBehaviour {

    public float scale = 1f; // 1 by default

    public void Update()
    {
        GetComponent<Canvas>().scaleFactor = scale;
    }
}


问:
WebRTC Datachannel for high bandwidth application
I want to send unidirectional streaming data over a WebRTC datachannel, and is looking of the best configuration options (high BW, low latency/jitter) and others' experience with expected bitrates in this kind of application.

My test program sends chunks of 2k, with a bufferedAmountLowThreshold event callback of 2k and calls send again until bufferedAmount exceeds 16k. Using this in Chrome, I achieve ~135Mbit/s on LAN and ~20Mbit/s from/to a remote connection, that has 100Mbit/s WAN connection on both ends.

What is the limiting factor here?

How can I see if the data is truly going peer to peer directly, or whether a TURN server is used?

My ultimate application will use the google-webrtc library on Android - I'm only using JS for prototyping. Can I set options to speed up bitrate in the library, that I cannot do in official JS APIs?

答:
There are many variables that impact throughput and it also highly depends on how you've measured it. But I'll list a couple of things I have adjusted to increase the throughput of WebRTC data channels.

Disclaimer: I have not done these adjustments for libwebrtc but for my own WebRTC data channel library called RAWRTC, which btw also compiles for Android. However, both use the same SCTP library underneath, both use some OpenSSL-ish library and UDP sockets, so all of this should be appliable to libwebrtc.

Note that WebRTC data channel implementations using usrsctp are usually CPU bound when executed on the same machine, so keep that in mind when testing. With RAWRTC's default settings, I'm able to achieve ~520 Mbit/s on my i7 5820k. From my own tests, both Chrom(e|ium) and Firefox were able to achieve ~350 Mbit/s with default settings.

Alright, so let's dive into adjustments...

UDP Send/Receive Buffer Size

The default send/receive buffer of UDP sockets in Linux is quite small by default. If you can, you may want to adjust it.

DTLS Cipher Suites

Most Android devices have ARM processors without hardware AES support. ChaCha20 usually performs better in software and thus you may want to prefer it.

(This is what RAWRTC negotiates by default, so I have not included it in the end results.)

SCTP Send/Receive Buffer Size

The default send/receive window size of usrsctp, the SCTP stack used by libwebrtc, is 256 KiB which is way too small to achieve high throughput with moderate delay. The theoretical maximum throughput is limited by mbits = (window / (rtt_ms / 1000)) / 131072. So, with the default window of window=262144 and a fairly moderate RTT of rtt_ms=20, you will end up with a theoretical maximum of 100 Mbit/s.

The practical maximum is below that... actually, way lower than the theoretical maximum (see my test results). This may be a bug in the usrsctp stack (see sctplab/usrsctp#245).

The buffer size has been increased in Firefox (see bug 1051685) but not in libwebrtc used by Chrom(e|ium).

Release Builds

Optimisation level 3 makes a difference (duh!).

Message Size

You probably want to send 256 KiB sized messages.

Unless you need to support Chrome < ??? (sorry, I currently don't know where it landed...), then the maximum message size is 64 KiB (see issue 7774).

Unless you also need to support Firefox < 56, in which case the maximum message size is 16 KiB (see bug 979417).

It also depends on how much you send before you pause sending (i.e. the buffer's high water mark), and when you continue sending after the buffer has been drained (i.e. the buffer's low water mark). My tests have shown that targeting a high water mark of 1 MiB and setting a low water mark of 256 KiB results in adequate throughput.

This reduces the amount of API calls and can increase throughput.

End Results

Using optimisation level 3 with default settings on RAWRTC brought me up to ~600 Mbit/s.

Based on that, increasing the SCTP and UDP buffer sizes to 4 MiB brought me up further to ~700 Mbit/s, with one CPU core at 100% load.

However, I believe there is still room for improvements but it's unlikely to be low-hanging.

How can I see if the data is truly going peer to peer directly, or whether a TURN server is used?

Open about:webrtc in Firefox or chrome://webrtc-internals in Chrom(e|ium) and look for the chosen ICE candidate pair. Or use Wireshark.


问:
Fabric.js: Find the center of an object (rect) in a group
I need to find the center point of an object that has been placed into a group. Things l have tried:

•   getCenterPoint(): returns the center point as if the object were at 0,0.

•   Calculating the center point using getTop() and getLeft() of both the group and the object. Unfortunately while the group values work find the object returns negative values.

•   Calculated the values using heights/widths of objects. This gets close in the case listed below, but that’s only because of the very specific properties of my example, and would not generalize.

The object below is what I’m currently working with, specifically I’m looking to find the center of rect2:

```<code>        // create a rectangle object
        var rect = new fabric.Rect({
            top: 10,
            fill: 'white',
            stroke: 'black',
            width: 20,
            height: 20
        });

        // create a rectangle object
        var rect2 = new fabric.Rect({
            top: 10,
            left: 20,
            fill: 'white',
            stroke: 'black',
            width: 20,
            height: 20
        });

        var line = new fabric.Line([ 20, 20, 40, 20],
        {
            top: 0,
            left: 0,
            stroke: 'black'
        });

        var group = new fabric.Group([ rect, rect2, line ],{
            top: 100,
            left: 100,
            hasRotatingPoint: false
        });
</code>```

答:
Here is the math that I used to get the center of a given Rect

```<code> var x1 = e.target.oCoords.oCoords.mt.x;
 var y1 = e.target.oCoords.oCoords.mt.y;
 var x2 = e.target.oCoords.oCoords.mb.x;
 var y2 = e.target.oCoords.oCoords.mb.y;

 var centerX = (x1 + x2) / 2;
 var centerY = (y1 + y2) / 2;
</code>```

Then in my case I used the center coor to create a Line using:

```<code>var line = makeLine([centerx, centery, 250, 175]);
canvas.add(line);
</code>```

Body:
I need to find the center point of an object that has been placed into a group. Things l have tried:

•   getCenterPoint(): returns the center point as if the object were at 0,0.

•   Calculating the center point using getTop() and getLeft() of both the group and the object. Unfortunately while the group values work find the object returns negative values.

•   Calculated the values using heights/widths of objects. This gets close in the case listed below, but that’s only because of the very specific properties of my example, and would not generalize.

The object below is what I’m currently working with, specifically I’m looking to find the center of rect2:

        // create a rectangle object
        var rect = new fabric.Rect({
            top: 10,
            fill: 'white',
            stroke: 'black',
            width: 20,
            height: 20
        });

        // create a rectangle object
        var rect2 = new fabric.Rect({
            top: 10,
            left: 20,
            fill: 'white',
            stroke: 'black',
            width: 20,
            height: 20
        });

        var line = new fabric.Line([ 20, 20, 40, 20],
        {
            top: 0,
            left: 0,
            stroke: 'black'
        });

        var group = new fabric.Group([ rect, rect2, line ],{
            top: 100,
            left: 100,
            hasRotatingPoint: false
        });

Body:
Here is the math that I used to get the center of a given Rect

 var x1 = e.target.oCoords.oCoords.mt.x;
 var y1 = e.target.oCoords.oCoords.mt.y;
 var x2 = e.target.oCoords.oCoords.mb.x;
 var y2 = e.target.oCoords.oCoords.mb.y;

 var centerX = (x1 + x2) / 2;
 var centerY = (y1 + y2) / 2;

Then in my case I used the center coor to create a Line using:

var line = makeLine([centerx, centery, 250, 175]);
canvas.add(line);


问:
Add a popup modal to vuetify vue.js
I am trying to add a popup-modal to a table in vuetify vue.js but it always ends up getting the value of the first item.

The problem arises on the 4th  where I am trying to implement a pop-up modal.

It keeps getting the first element of the list only. I feel like it is a very easy fix.. it is the 4th  just to save you time.

Vue Template:

```<code><script>
        var model =  @Html.Raw(Json.Encode(Model))
</script>

<div id="app">
    <v-app id="inspire">
        <v-card>
            <v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn flat color="purple" href="/Home">Home</v-btn>
                    <v-btn flat color="purple">Inventory</v-btn>
                </v-card-actions>

                <v-spacer></v-spacer>

            </v-card-title>

        </v-card>

        <v-container grid-list-md text-xs-center>
            <v-layout>
                <v-flex xs8>

                    <v-card>

                        <v-card-title>
                            Un Added Lab Equipment
                            <v-spacer></v-spacer>
                            <v-text-field v-model="search"
                                          append-icon="search"
                                          label="Search"
                                          single-line
                                          hide-details></v-text-field>
                        </v-card-title>
                        <v-data-table :headers="Headers"
                                      :items="items"
                                      :search="search"
                                      item-key="equipment"
                                      hide-actions
                                      expand
                                      class="elevation-1">
                            <template slot="items" scope="props">
                                <td class="text-xs">{{ props.item.equipment }}</td>
                                <td class="text-xs">{{ props.item.location }}</td>
                                <td class="text-xs">{{ props.item.qty }}  </td>
                                <td>
                                    @*<a v-bind:href="props.item.pictureUrl">
                                        <i class="fa fa-info-circle fa-2x" style="color: rgb(159, 212, 172);"></i></a>*@
                                    <v-dialog v-model="dialog" lazy absolute>
                                        <i class="fa fa-info-circle fa-2x" style="color: rgb(159, 212, 172);" slot="activator"></i>
                                        <v-card>
                                            <v-card-title class="justify-center">
                                                <p class="headline">More Info  for '{{ props.item.equipment }}'</p>
                                            </v-card-title>
                                            <v-card-text>
                                                @*<v-img src="{{props.item.pictureUrl}}"
                                                    aspect-ratio="2.75"></v-img>*@ {{props.item.location}}
                                            </v-card-text>
                                            <v-card-actions>
                                                <v-spacer></v-spacer>
                                                <v-btn class="blue--text darken-1" flat="flat" v-on:click.native="dialog = false">No</v-btn>
                                                <v-btn class="blue--text darken-1" flat="flat" v-on:click.native="deleteRow(props.item)">Yes</v-btn>
                                            </v-card-actions>
                                        </v-card>
                                    </v-dialog>

                                </td>
                                <td class="text-xs">
                                    <button v-on:click="decrement(props.item.id)" :disabled="disabled == props.item.id ? true : false">
                                        <v-icon color="pink">remove</v-icon>
                                    </button>
                                    <button v-on:click="increment(props.item.id)" id="incrementButton" :disabled="disabled == props.item.id + '2' ? true : false">
                                        <v-icon color="green">add</v-icon>
                                    </button>
                                </td>

                            </template>
                        </v-data-table>
                    </v-card>
                </v-flex>

            </v-layout>
            <br />

        </v-container>

</div>

***Vue App:***
</code>```

```<code>new Vue({
el: '#app',
data() {
    return {
        disabled: "",
        searchAdded: '',
        message: 'omae wa moo shindeiruu',
        dialog: false,
        notifications: false,
        sound: true,
        test: true,
        widgets: false,
        search: '',
        Headers: [
            { text: 'Equipment', value: 'equipment' },
            { text: 'Location', value: 'location' },
            { text: 'Qty', value: 'qty' },
            { text: 'MoreInfo', value: 'pictureUrl',  sortable: false, disabled: true },
            { text: 'Add or Remove', value: 'addo', sortable: false, disabled: true }
        ],
        HeadersAdded: [
            { text: 'Equipment', value: 'itemName' },
            { text: 'Location', value: 'location' },
            { text: 'Qty', value: 'quantity' },
            { text: 'Add or Remove', value: 'addo', sortable: false, disabled: true }
        ],
        items: [{ equipment: "beaker", location: 'Room 3535 drawer 21', qty: 21, id: '07f37f', pictureUrl: 'https://www.bhphotovideo.com/images/images2500x2500/Photographers_Formulary_09_0095_Glass_Beaker_600ml_231378.jpg' },
            { equipment: "ruler", location: 'Room 3535 drawer 10', qty: 7, id: '08f312', pictureUrl: 'https://images-na.ssl-images-amazon.com/images/I/41qUVuXt2AL.jpg' },
            { equipment: "flask", location: 'Room 2121 drawer 22', qty: 6, id: '09f37d', pictureUrl: 'https://images-na.ssl-images-amazon.com/images/I/316GJIEdJxL._SY445_.jpg' },
            { equipment: "vernier-caliber", location: 'Room 4125 drawer 21', qty: 12, id: '07g3hf', pictureUrl: 'https://static.grainger.com/rp/s/is/image/Grainger/2ZUF3_AS01?$mdmain$' }
                ],
        itemsAdded: []
    }

}
</code>```

})

答:
I was able to get this to work by changing the v-model for the v-dialog on each item..

Code Snippet is below, and I have created a CodePen Mirror here as well.

It now sets the dialog open/close property for each specific item in the items list:

```<code><v-dialog v-model="dialog[props.item.equipment]"...
</code>```

The activator slot now looks like this:

```<code>...@click.stop="$set(dialog, props.item.equipment, true)" slot="activator"...
</code>```

..and the "close button" for the v-dialog had to also be modified to:

```<code>...@click.stop="$set(dialog, props.item.equipment, false)"...
</code>```

This means I also had to change dialog in your data() props to be an object:

```<code>data() {
  return {
    ...
    dialog: {},
    ...
  }
}
</code>```

CODE SNIPPET:

new Vue({
  el: "#app",
  data() {
    return {
      disabled: "",
      searchAdded: "",
      message: "omae wa moo shindeiruu",
      dialog: {},
      notifications: false,
      sound: true,
      test: true,
      widgets: false,
      search: "",
      Headers: [
        { text: "Equipment", value: "equipment" },
        { text: "Location", value: "location" },
        { text: "Qty", value: "qty" },
        {
          text: "MoreInfo",
          value: "pictureUrl",
          sortable: false,
          disabled: false
        },
        {
          text: "Add or Remove",
          value: "addo",
          sortable: false,
          disabled: true
        }
      ],
      HeadersAdded: [
        { text: "Equipment", value: "itemName" },
        { text: "Location", value: "location" },
        { text: "Qty", value: "quantity" },
        {
          text: "Add or Remove",
          value: "addo",
          sortable: false,
          disabled: true
        }
      ],
      items: [
        {
          equipment: "beaker",
          location: "Room 3535 drawer 21",
          qty: 21,
          id: "07f37f",
          pictureUrl:"https://www.bhphotovideo.com/images/images2500x2500/Photographers_Formulary_09_0095_Glass_Beaker_600ml_231378.jpg"
        },
        {
          equipment: "ruler",
          location: "Room 3535 drawer 10",
          qty: 7,
          id: "08f312",
          pictureUrl: "https://images-na.ssl-images-amazon.com/images/I/41qUVuXt2AL.jpg"
        },
        {
          equipment: "flask",
          location: "Room 2121 drawer 22",
          qty: 6,
          id: "09f37d",
          pictureUrl: "https://images-na.ssl-images-amazon.com/images/I/316GJIEdJxL._SY445_.jpg"
        },
        {
          equipment: "vernier-caliber",
          location: "Room 4125 drawer 21",
          qty: 12,
          id: "07g3hf",
          pictureUrl: "https://static.grainger.com/rp/s/is/image/Grainger/2ZUF3_AS01?$mdmain$"
        }
      ],
      itemsAdded: []
    };
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.5.14/vuetify.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.6/dist/vuetify.min.css" rel="stylesheet"/>
<link href="https://static.fontawesome.com/css/fontawesome-app.css" rel="stylesheet"/>
<link href="https://pro.fontawesome.com/releases/v5.2.0/css/all.css" rel="stylesheet"/>

<div id="app">
    <v-app id="inspire">
        <v-card>
            <v-card-title>
                Un Added Lab Equipment
                <v-spacer></v-spacer>
                <v-text-field v-model="search" append-icon="search" label="Search" single-line hide-details>
                </v-text-field>
            </v-card-title>
            <v-data-table :headers="Headers" :items="items" :search="search" item-key="equipment" hide-actions expand
                class="elevation-1">
                <template slot="items" scope="props">
                    <td class="text-xs">{{ props.item.equipment }}</td>
                    <td class="text-xs">{{ props.item.location }}</td>
                    <td class="text-xs">{{ props.item.qty }}</td>
                    <td>
                        <v-dialog v-model="dialog[props.item.equipment]" lazy absolute>
                            <v-btn flat icon color="blue lighten-2"
                                @click.stop="$set(dialog, props.item.equipment, true)" slot="activator">
                                <v-icon>info</v-icon>
                            </v-btn>
                            <v-card>
                                <v-card-title>
                                    <div class="headline">More Info for '{{ props.item.equipment }}'</div>
                                </v-card-title>
                                <v-card-text>
                                    <v-img :src="props.item.pictureUrl" aspect-ratio="2.75"></v-img>
                                    {{props.item.location}}
                                </v-card-text>
                                <v-card-actions>
                                    <v-spacer></v-spacer>
                                    <v-btn class="blue--text darken-1" flat="flat"
                                        @click.stop="$set(dialog, props.item.equipment, false)">No</v-btn>
                                    <v-btn class="blue--text darken-1" flat="flat"
                                        @click.native="deleteRow(props.item)">Yes</v-btn>
                                </v-card-actions>
                            </v-card>
                        </v-dialog>
                    </td>
                    <td class="text-xs">
                        <button v-on:click="decrement(props.item.id)"
                            :disabled="disabled == props.item.id ? true : false">
                            <v-icon color="pink">remove</v-icon>
                        </button>
                        <button v-on:click="increment(props.item.id)" id="incrementButton"
                            :disabled="disabled == props.item.id + '2' ? true : false">
                            <v-icon color="green">add</v-icon>
                        </button>
                    </td>
                </template>
            </v-data-table>
        </v-card>
    </v-app>
</div></code>```

Title: Add a popup modal to vuetify vue.js

Body:
I am trying to add a popup-modal to a table in vuetify vue.js but it always ends up getting the value of the first item.

The problem arises on the 4th  where I am trying to implement a pop-up modal.

It keeps getting the first element of the list only. I feel like it is a very easy fix.. it is the 4th  just to save you time.

Vue Template:

    <v-app id="inspire">
        <v-card>
            <v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn flat color="purple" href="/Home">Home</v-btn>
                    <v-btn flat color="purple">Inventory</v-btn>
                </v-card-actions>

                <v-spacer></v-spacer>

            </v-card-title>

        </v-card>

        <v-container grid-list-md text-xs-center>
            <v-layout>
                <v-flex xs8>

                    <v-card>

                        <v-card-title>
                            Un Added Lab Equipment
                            <v-spacer></v-spacer>
                            <v-text-field v-model="search"
                                          append-icon="search"
                                          label="Search"
                                          single-line
                                          hide-details></v-text-field>
                        </v-card-title>
                        <v-data-table :headers="Headers"
                                      :items="items"
                                      :search="search"
                                      item-key="equipment"
                                      hide-actions
                                      expand
                                      class="elevation-1">
                            <template slot="items" scope="props">
                                {{ props.item.equipment }}
                                {{ props.item.location }}
                                {{ props.item.qty }}

                                    @*
                                        *@
                                    <v-dialog v-model="dialog" lazy absolute>

                                        <v-card>
                                            <v-card-title class="justify-center">

More Info  for '{{ props.item.equipment }}'

                                            </v-card-title>
                                            <v-card-text>
                                                @*<v-img src="{{props.item.pictureUrl}}"
                                                    aspect-ratio="2.75"></v-img>*@ {{props.item.location}}
                                            </v-card-text>
                                            <v-card-actions>
                                                <v-spacer></v-spacer>
                                                <v-btn class="blue--text darken-1" flat="flat" v-on:click.native="dialog = false">No</v-btn>
                                                <v-btn class="blue--text darken-1" flat="flat" v-on:click.native="deleteRow(props.item)">Yes</v-btn>
                                            </v-card-actions>
                                        </v-card>
                                    </v-dialog>

                                    <button v-on:click="decrement(props.item.id)" :disabled="disabled == props.item.id ? true : false">
                                        <v-icon color="pink">remove</v-icon>
                                    </button>
                                    <button v-on:click="increment(props.item.id)" id="incrementButton" :disabled="disabled == props.item.id + '2' ? true : false">
                                        <v-icon color="green">add</v-icon>
                                    </button>

                            </template>
                        </v-data-table>
                    </v-card>
                </v-flex>

            </v-layout>

        </v-container>

***Vue App:***

new Vue({
el: '#app',
data() {
    return {
        disabled: "",
        searchAdded: '',
        message: 'omae wa moo shindeiruu',
        dialog: false,
        notifications: false,
        sound: true,
        test: true,
        widgets: false,
        search: '',
        Headers: [
            { text: 'Equipment', value: 'equipment' },
            { text: 'Location', value: 'location' },
            { text: 'Qty', value: 'qty' },
            { text: 'MoreInfo', value: 'pictureUrl',  sortable: false, disabled: true },
            { text: 'Add or Remove', value: 'addo', sortable: false, disabled: true }
        ],
        HeadersAdded: [
            { text: 'Equipment', value: 'itemName' },
            { text: 'Location', value: 'location' },
            { text: 'Qty', value: 'quantity' },
            { text: 'Add or Remove', value: 'addo', sortable: false, disabled: true }
        ],
        items: [{ equipment: "beaker", location: 'Room 3535 drawer 21', qty: 21, id: '07f37f', pictureUrl: 'https://www.bhphotovideo.com/images/images2500x2500/Photographers_Formulary_09_0095_Glass_Beaker_600ml_231378.jpg' },
            { equipment: "ruler", location: 'Room 3535 drawer 10', qty: 7, id: '08f312', pictureUrl: 'https://images-na.ssl-images-amazon.com/images/I/41qUVuXt2AL.jpg' },
            { equipment: "flask", location: 'Room 2121 drawer 22', qty: 6, id: '09f37d', pictureUrl: 'https://images-na.ssl-images-amazon.com/images/I/316GJIEdJxL._SY445_.jpg' },
            { equipment: "vernier-caliber", location: 'Room 4125 drawer 21', qty: 12, id: '07g3hf', pictureUrl: 'https://static.grainger.com/rp/s/is/image/Grainger/2ZUF3_AS01?$mdmain$' }
                ],
        itemsAdded: []
    }

}

})

Body:
I was able to get this to work by changing the v-model for the v-dialog on each item..

Code Snippet is below, and I have created a CodePen Mirror here as well.

It now sets the dialog open/close property for each specific item in the items list:

<v-dialog v-model="dialog[props.item.equipment]"...

The activator slot now looks like this:

...@click.stop="$set(dialog, props.item.equipment, true)" slot="activator"...

..and the "close button" for the v-dialog had to also be modified to:

...@click.stop="$set(dialog, props.item.equipment, false)"...

This means I also had to change dialog in your data() props to be an object:

data() {
  return {
    ...
    dialog: {},
    ...
  }
}

CODE SNIPPET:

new Vue({
  el: "#app",
  data() {
    return {
      disabled: "",
      searchAdded: "",
      message: "omae wa moo shindeiruu",
      dialog: {},
      notifications: false,
      sound: true,
      test: true,
      widgets: false,
      search: "",
      Headers: [
        { text: "Equipment", value: "equipment" },
        { text: "Location", value: "location" },
        { text: "Qty", value: "qty" },
        {
          text: "MoreInfo",
          value: "pictureUrl",
          sortable: false,
          disabled: false
        },
        {
          text: "Add or Remove",
          value: "addo",
          sortable: false,
          disabled: true
        }
      ],
      HeadersAdded: [
        { text: "Equipment", value: "itemName" },
        { text: "Location", value: "location" },
        { text: "Qty", value: "quantity" },
        {
          text: "Add or Remove",
          value: "addo",
          sortable: false,
          disabled: true
        }
      ],
      items: [
        {
          equipment: "beaker",
          location: "Room 3535 drawer 21",
          qty: 21,
          id: "07f37f",
          pictureUrl:"https://www.bhphotovideo.com/images/images2500x2500/Photographers_Formulary_09_0095_Glass_Beaker_600ml_231378.jpg"
        },
        {
          equipment: "ruler",
          location: "Room 3535 drawer 10",
          qty: 7,
          id: "08f312",
          pictureUrl: "https://images-na.ssl-images-amazon.com/images/I/41qUVuXt2AL.jpg"
        },
        {
          equipment: "flask",
          location: "Room 2121 drawer 22",
          qty: 6,
          id: "09f37d",
          pictureUrl: "https://images-na.ssl-images-amazon.com/images/I/316GJIEdJxL._SY445_.jpg"
        },
        {
          equipment: "vernier-caliber",
          location: "Room 4125 drawer 21",
          qty: 12,
          id: "07g3hf",
          pictureUrl: "https://static.grainger.com/rp/s/is/image/Grainger/2ZUF3_AS01?$mdmain$"
        }
      ],
      itemsAdded: []
    };
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.5.14/vuetify.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.6/dist/vuetify.min.css" rel="stylesheet"/>
<link href="https://static.fontawesome.com/css/fontawesome-app.css" rel="stylesheet"/>
<link href="https://pro.fontawesome.com/releases/v5.2.0/css/all.css" rel="stylesheet"/>

<div id="app">
    <v-app id="inspire">
        <v-card>
            <v-card-title>
                Un Added Lab Equipment
                <v-spacer></v-spacer>
                <v-text-field v-model="search" append-icon="search" label="Search" single-line hide-details>
                </v-text-field>
            </v-card-title>
            <v-data-table :headers="Headers" :items="items" :search="search" item-key="equipment" hide-actions expand
                class="elevation-1">
                <template slot="items" scope="props">
                    <td class="text-xs">{{ props.item.equipment }}</td>
                    <td class="text-xs">{{ props.item.location }}</td>
                    <td class="text-xs">{{ props.item.qty }}</td>
                    <td>
                        <v-dialog v-model="dialog[props.item.equipment]" lazy absolute>
                            <v-btn flat icon color="blue lighten-2"
                                @click.stop="$set(dialog, props.item.equipment, true)" slot="activator">
                                <v-icon>info</v-icon>
                            </v-btn>
                            <v-card>
                                <v-card-title>
                                    <div class="headline">More Info for '{{ props.item.equipment }}'</div>
                                </v-card-title>
                                <v-card-text>
                                    <v-img :src="props.item.pictureUrl" aspect-ratio="2.75"></v-img>
                                    {{props.item.location}}
                                </v-card-text>
                                <v-card-actions>
                                    <v-spacer></v-spacer>
                                    <v-btn class="blue--text darken-1" flat="flat"
                                        @click.stop="$set(dialog, props.item.equipment, false)">No</v-btn>
                                    <v-btn class="blue--text darken-1" flat="flat"
                                        @click.native="deleteRow(props.item)">Yes</v-btn>
                                </v-card-actions>
                            </v-card>
                        </v-dialog>
                    </td>
                    <td class="text-xs">
                        <button v-on:click="decrement(props.item.id)"
                            :disabled="disabled == props.item.id ? true : false">
                            <v-icon color="pink">remove</v-icon>
                        </button>
                        <button v-on:click="increment(props.item.id)" id="incrementButton"
                            :disabled="disabled == props.item.id + '2' ? true : false">
                            <v-icon color="green">add</v-icon>
                        </button>
                    </td>
                </template>
            </v-data-table>
        </v-card>
    </v-app>
</div>


问:
Warning "Potential leak of an object allocated on line ..." when declaring a 2D array
Initially i declared a 2D array in this way:

```<code>subUrb = [[NSArray alloc] initWithObjects:
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] ,
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil],
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil],
     nil];
</code>```

But when i try to 'analyze' the warnings of the project, i got three same type of issues in this chunk of code - "potential leak of an object allocated on line xxx"

I noticed that to get rid of it, i have to write sth like this:

```<code>subUrb =
    [[NSArray alloc] initWithObjects:
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil] autorelease],
        nil];
</code>```

Then i will not get any analyze warnings. But i dun like this...it is not logical. This 2D array should never be released in my controller actually, the entire 2D array should be retained for the entire life time of the controller for a PickerView.

How should I declare the 2D array more elegantly?

答:
You get the ownership if you allocate an array with alloc init and so you have to release it as you do in your second code.
You can also use:
 [[NSArray alloc]  initWithObjects:
[NSArray arayWithObjects:first,second, nil], nil];

Body:
Initially i declared a 2D array in this way:

subUrb = [[NSArray alloc] initWithObjects:
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] ,
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil],
     [[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil],
     nil];

But when i try to 'analyze' the warnings of the project, i got three same type of issues in this chunk of code - "potential leak of an object allocated on line xxx"

I noticed that to get rid of it, i have to write sth like this:

subUrb =
    [[NSArray alloc] initWithObjects:
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"East",@"South", @"West", @"North", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Kuala Lumpur SubUrb1", @"Kuala Lumpur SubUrb2", nil] autorelease],
        [[[NSArray alloc] initWithObjects:ALL_SUBURBS_LABEL, @"Jakarta SubUrb1",nil] autorelease],
        nil];

Then i will not get any analyze warnings. But i dun like this...it is not logical. This 2D array should never be released in my controller actually, the entire 2D array should be retained for the entire life time of the controller for a PickerView.

How should I declare the 2D array more elegantly?


问:
Starvation vs Convoy Effect
Is the only difference between starvation and convoy effect that convoy effect is mainly defined on FCFS scheduling algorithms and starvation is on priority based scheduling?

I researched on both effects but couldn't find a comparison. This is based on operating systems theory which I learned for my college degree.

答:
Starvation and convoys can occur both algorithms.   The simplest, starvation, can be simulated by a task entering this loop (I hope it isn't UDB):

```<code>while (1) {
}
</code>```

In FCFS, this task will never surrender the CPU, thus all tasks behind it will starve.   In a Priority based system, this same task will starve every task of a lower priority.

Convoys can be more generally recognized as a resource contention problem; one task has the resources (cpu), and other tasks have to wait until it is done with it.   In a priority-based system, this is manifest in priority inversion where a high priority task is blocked because it needs a resource owned by a lower priority task.   There are ways to mitigate these, including priority inheritance and ceiling protocols.  Absent these mechanisms, tasks contending for a resource will form a convoy much like in the fcfs; unlike the fcfs, tasks not contending for the resource are free to execute at will.

The aspirations of responsiveness, throughput and fairness are often at odds, which is partly why we don't have a true solution to scheduling problems.

Title: Starvation vs Convoy Effect

Body:
Starvation and convoys can occur both algorithms.   The simplest, starvation, can be simulated by a task entering this loop (I hope it isn't UDB):

while (1) {
}

In FCFS, this task will never surrender the CPU, thus all tasks behind it will starve.   In a Priority based system, this same task will starve every task of a lower priority.

Convoys can be more generally recognized as a resource contention problem; one task has the resources (cpu), and other tasks have to wait until it is done with it.   In a priority-based system, this is manifest in priority inversion where a high priority task is blocked because it needs a resource owned by a lower priority task.   There are ways to mitigate these, including priority inheritance and ceiling protocols.  Absent these mechanisms, tasks contending for a resource will form a convoy much like in the fcfs; unlike the fcfs, tasks not contending for the resource are free to execute at will.

The aspirations of responsiveness, throughput and fairness are often at odds, which is partly why we don't have a true solution to scheduling problems.


问:
Using Firestore document's auto-generated ID versus using a custom ID
I'm currently deciding on my Firestore data structure.

I'll need a products collection, and the products items will live inside of it as documents.

Here are my product's fields:

uniqueKey: string

description: array of strings

images: array of objects

price: number

QUESTION

Should I use Firestore auto-generated ID's to be the ID of my documents, or is it better to use my uniqueKey (which I'll query for in many occasions) as the document ID? Is there a best option between the 2?

I imagine that if I use my uniqueKey, it will make my life easier when retrieving a single document, but I'll have to query for more than 1 product on many occasions too.

Using my uniqueKey as ID:

```<code>db.collection("products").doc("myUniqueKey").get();
</code>```

Using my Firestore auto-generated ID:

```<code>db.collection("products").where("uniqueKey", "==", "myUniqueKey").get();
</code>```

Is this enough of a reason to go with my uniqueKey instead of the auto-generated one? Is there a rule of thumb here? What's the best practice in this case?

答:
In terms of making queries from a client, using only the information you've given in the question, I don't see that there's much practical difference between a document get using its known ID, or a query on a field that is also unique.  Either way, an index is used on the server side, and it costs exactly 1 document read.  The document get() might be marginally faster, but it's not worthwhile to optimize like this (in my opinion).

When making decision about data modeling like this, it's more important to think about things like system behavior under load and security rules.

If you're reading and writing a lot of documents whose IDs have a sequential property, you could run into hotspotting on those writes.  So, if you want to use your own ID, and you expect to be reading and writing them in that sequence under heavy load, you could have a problem.  If you don't anticipate this to be the situation, then it likely doesn't matter too much whose ID you use.

If you are going to use security rules to limit access to documents, and you use the contents of other documents to help with that, you'll need to be able to uniquely identify those documents in your rule.  You can't perform a query against a collection in rules, so you might need meaningful IDs that will give direct access when used by rules.  If your own IDs can be used easily this way in security rules, that might be more convenient overall.  If you're force to used Firestore's generated IDs, it might become inconvenient, difficult, or expensive to try to maintain a relationship between your IDs and Firestore's IDs.

In any event, the decision you're making is not just about which ID is "better" in a general sense, but which ID is better for your specific, anticipated situation, under load, with security in mind.

Body:
I'm currently deciding on my Firestore data structure.

I'll need a products collection, and the products items will live inside of it as documents.

Here are my product's fields:

uniqueKey: string

description: array of strings

images: array of objects

price: number

QUESTION

Should I use Firestore auto-generated ID's to be the ID of my documents, or is it better to use my uniqueKey (which I'll query for in many occasions) as the document ID? Is there a best option between the 2?

I imagine that if I use my uniqueKey, it will make my life easier when retrieving a single document, but I'll have to query for more than 1 product on many occasions too.

Using my uniqueKey as ID:

db.collection("products").doc("myUniqueKey").get();

Using my Firestore auto-generated ID:

db.collection("products").where("uniqueKey", "==", "myUniqueKey").get();

Is this enough of a reason to go with my uniqueKey instead of the auto-generated one? Is there a rule of thumb here? What's the best practice in this case?


问:
Find the resulting Sum after adding to the previous value in a Python list
I have a random number as input, lets say 5. What I need is the sum of the numbers 5 + 55 + 555 + 5555 + 55555.

Kindly help

答:
A recursive function is useful.

Please see comments as below:

```<code>def calc_iter(n, length = 1):
    value = ''
    for l in range(length): value += str(n)  # generate string number by length
    result = int(value)                      # convert string number to int
    if length == n: return result            # return int if length is equal n
    return result + calc_iter(n, length = length+1) # sum

num = int(input())
print (calc_iter(num))
</code>```

```<code>3
369  // 3 + 33 + 333
5
61725 // 5 + 55 + 555 + 5555 +55555
</code>```

Body:
A recursive function is useful.

Please see comments as below:

def calc_iter(n, length = 1):
    value = ''
    for l in range(length): value += str(n)  # generate string number by length
    result = int(value)                      # convert string number to int
    if length == n: return result            # return int if length is equal n
    return result + calc_iter(n, length = length+1) # sum

num = int(input())
print (calc_iter(num))

3
369  // 3 + 33 + 333
5
61725 // 5 + 55 + 555 + 5555 +55555


问:
why does having more than one thread(parallel processing) in some specific cases degrade performance?
i noticed that having more than a thread running for some code is much much slower than having one thread, and i have been really pulling my hair to know why,can anyone help?

code explanation :
i have ,sometimes, a very large array that i need to process parts of in a parallel way for optimization,each "part" of a row gets looped on and processed on in a specific thread, now i've noticed that if i only have one "part",i.e the whole array and a single worker thread that runs through it is noticeably faster than if i divide the array and process it as separate sub arrays with different threads.

```<code>    bool m_generate_row_worker(ull t_row_start,ull t_row_end)
    {
        for(;t_row_start<t_row_end;t_row_start++)
            {
                m_current_row[t_row_start]=m_singularity_checker(m_previous_row[t_row_start],m_shared_random_row[t_row_start]);

            }
        return true;
    }

    ...
    //code
    ...
    for(unsigned short thread_indx=0;thread_indx<noThreads-1;thread_indx++)
    {
        m_threads_array[thread_indx]=std::thread(
                m_generate_row_worker,this,
                thread_indx*(m_parts_per_thread),(thread_indx+1)*(m_parts_per_thread));
    }
    m_threads_array[noThreads-1]=std::thread(m_generate_row_worker,this,
            (noThreads-1)*(m_parts_per_thread),std::max((noThreads)*(m_parts_per_thread),m_blocks_per_row));
    //join
    for(unsigned short thread_indx=0;thread_indx<noThreads;thread_indx++)
    {
        m_threads_array[thread_indx].join();
    }
//EDIT
    inline ull m_singularity_checker(ull t_to_be_ckecked_with,ull
    t_to_be_ckecked)
    {
            return (t_to_be_ckecked & (t_to_be_ckecked_with<<1)
             & (t_to_be_ckecked_with>>1) ) | (t_to_be_ckecked_with &
    t_to_be_ckecked);
    }
</code>```

答:
why does having more than one thread(parallel processing) in some specific cases degrade performance?

Because thread creation has overhead. If the task to be performed has only small computational cost, then the cost of creating multiple threads is more than the time saved by parallelism. This is especially the case when creating significantly more threads than there are CPU cores.

Because many algorithms do not easily divide into independent sub-tasks. Dependencies on other threads requires synchronisation, which has overhead that can in some cases be more than the time saved by parallelism.

Because in poorly designed programs, synchronization can cause all tasks to be processed sequentially even if they are in separate threads.

Because (depending on CPU architecture) sometimes otherwise correctly implemented, and seemingly independent tasks have effectual dependency because they operate on the same area of memory.  More specifically, when a threads writes into a piece of memory, all threads operating on the same cache line must synchronise (the CPU does this for you automatically) to remain consistent. The cost of cache misses is often much higher than the time saved by parallelism. This problem is called "false sharing".

Because sometimes introduction of multi threading makes the program more complex, which makes it more difficult for the compiler / optimiser to make use of instruction level parallelism.

...

In conclusion: Threads are not a silver bullet that automatically multiplies the performance of your program.

Regarding your program, we cannot count out any of the above potential issues given the excerpt that you have shown.

Some tips on avoiding or finding above issues:

Don't create more threads than you have cores, discounting the number of threads that are expected to be blocking (waiting for input, disk, etc).

Only use multi-threading with problems that are computationally expensive, (or to do work while a thread is blocking, but this may be more efficiently solved using asynchronous I/O and coroutines).

Don't do (or do as little as possible) I/O from more than one thread into a single device (disk, NIC, virtual terminal, ...) unless it is specially designed to handle it.

Minimise the number of dependencies between threads. Consider all access to global things that may cause synchronisation, and avoid them. For example, avoid memory allocation. Keep in mind that things like operations on standard containers do memory allocation.

Keep the memory touched by distinct threads far from each other (not adjacent small elements of array). If processing an array, divide it in consecutive blocks, rather than striping one element every (number of threads)th element. In some extreme cases, extra copying into thread specific data structures, and then joining in the end may be efficient.

If you've done all you can, and multi threading measures slower, consider whether perhaps it is not a good solution for your problem.

Body:
i noticed that having more than a thread running for some code is much much slower than having one thread, and i have been really pulling my hair to know why,can anyone help?

code explanation :
i have ,sometimes, a very large array that i need to process parts of in a parallel way for optimization,each "part" of a row gets looped on and processed on in a specific thread, now i've noticed that if i only have one "part",i.e the whole array and a single worker thread that runs through it is noticeably faster than if i divide the array and process it as separate sub arrays with different threads.

    bool m_generate_row_worker(ull t_row_start,ull t_row_end)
    {
        for(;t_row_start<t_row_end;t_row_start++)
            {
                m_current_row[t_row_start]=m_singularity_checker(m_previous_row[t_row_start],m_shared_random_row[t_row_start]);

            }
        return true;
    }

    ...
    //code
    ...
    for(unsigned short thread_indx=0;thread_indx<noThreads-1;thread_indx++)
    {
        m_threads_array[thread_indx]=std::thread(
                m_generate_row_worker,this,
                thread_indx*(m_parts_per_thread),(thread_indx+1)*(m_parts_per_thread));
    }
    m_threads_array[noThreads-1]=std::thread(m_generate_row_worker,this,
            (noThreads-1)*(m_parts_per_thread),std::max((noThreads)*(m_parts_per_thread),m_blocks_per_row));
    //join
    for(unsigned short thread_indx=0;thread_indx<noThreads;thread_indx++)
    {
        m_threads_array[thread_indx].join();
    }
//EDIT
    inline ull m_singularity_checker(ull t_to_be_ckecked_with,ull
    t_to_be_ckecked)
    {
            return (t_to_be_ckecked & (t_to_be_ckecked_with<<1)
             & (t_to_be_ckecked_with>>1) ) | (t_to_be_ckecked_with &
    t_to_be_ckecked);
    }


问:
Returning content after Mapping is wrong (Automapper .NET Core)
I use automapper to map from entity to dto.

In appservice method I need to get all values from DB and push it to list

Here is my method

```<code> public class ExperienceAppService : IExperience
{
    private readonly ApplicationDbContext _context;
    private readonly IMapper _mapper;

    public ExperienceAppService(ApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<List<ExperienceListDto>> GetExperiences()
    {
        var experiences = await _context.Experiences
            .ProjectTo<ExperienceListDto>(_mapper.ConfigurationProvider)
            .ToListAsync();
        return experiences;
    }
</code>```

}

Here is mapping profile

```<code> public class MappingsProfile : Profile
{
    public MappingsProfile()
    {
        CreateMap<UserDto, User>();

        #region Experiences

        CreateMap<ExperienceDto, Experience>();
        CreateMap<Experience, ExperienceDto>().ForMember(x => x.Name,
                opt => opt.MapFrom(n => n.Name))
            .ForMember(x => x.City, opt => opt.MapFrom(c => c.City))
            .ForMember(x => x.Price, opt => opt.MapFrom(c => c.Price))
            .ForMember(x => x.Rating, opt => opt.MapFrom(c => c.Rating));

        #endregion
    }
}
</code>```

Here is how I register it in Startup.cs

```<code>services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver =
                    new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling =
                    ReferenceLoopHandling.Ignore;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        //Mapper.Initialize(cfg => cfg.AddProfile<MappingsProfile>());
        services.AddAutoMapper();
</code>```

My problem, that in response I get text like this

{   "stateMachine": {
        "<>1__state": 0,
        "<>t__builder": {},
        "<>4__this": {}   },   "context": {},   "moveNextAction": {
        "method": {
          "name": "MoveNext",
          "declaringType": "System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[[System.Collections.Generic.List1[[TooSeeWeb.Core.DtoModels.Experiences.ExperienceListDto,
    TooSeeWeb.Core, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0,
    Culture=neutral,
    PublicKeyToken=7cec85d7bea7798e],[TooSeeWeb.Infrastructure.AppServices.Experiences.ExperienceAppService+<GetExperiences>d__3,
    TooSeeWeb.Infrastructure, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0,
    Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
          "reflectedType": "System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[[System.Collections.Generic.List1[[TooSeeWeb.Core.DtoModels.Experiences.ExperienceListDto,
    TooSeeWeb.Core, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0,
    Culture=neutral,
    PublicKeyToken=7cec85d7bea7798e],[TooSeeWeb.Infrastructure.AppServices.Experiences.ExperienceAppService+d__3,
    TooSeeWeb.Infrastructure, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0,
    Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
          "memberType": 8,
          "metadataToken": 100682290,
          "module": {
            "mdStreamVersion": 131072,
            "fullyQualifiedName": "/usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.2.5/System.Private.CoreLib.dll",
            "moduleVersionId": "9aeda1ea-7722-4ca6-a7ca-c000af27dec0",
            "metadataToken": 1,

Aтв much more code, and in the end, I get values from method. Where is my problem can be?

答:
My problem was not in mapper.
In Controller, I was returning a list like this

```<code>    [HttpGet]
    public IActionResult GetExperiences()
    {
        var experiences = _experienceAppService.GetExperiences();
        return Ok(experiences);
    }
</code>```

Instead of this

```<code>    [HttpGet]
    public IActionResult GetExperiences()
    {
        var experiences = _experienceAppService.GetExperiences();
        return Ok(experiences.Result);
    }
</code>```

Body:
I use automapper to map from entity to dto.

In appservice method I need to get all values from DB and push it to list

Here is my method

 public class ExperienceAppService : IExperience
{
    private readonly ApplicationDbContext _context;
    private readonly IMapper _mapper;

    public ExperienceAppService(ApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<List<ExperienceListDto>> GetExperiences()
    {
        var experiences = await _context.Experiences
            .ProjectTo<ExperienceListDto>(_mapper.ConfigurationProvider)
            .ToListAsync();
        return experiences;
    }

}

Here is mapping profile

 public class MappingsProfile : Profile
{
    public MappingsProfile()
    {
        CreateMap<UserDto, User>();

        #region Experiences

        CreateMap<ExperienceDto, Experience>();
        CreateMap<Experience, ExperienceDto>().ForMember(x => x.Name,
                opt => opt.MapFrom(n => n.Name))
            .ForMember(x => x.City, opt => opt.MapFrom(c => c.City))
            .ForMember(x => x.Price, opt => opt.MapFrom(c => c.Price))
            .ForMember(x => x.Rating, opt => opt.MapFrom(c => c.Rating));

        #endregion
    }
}

Here is how I register it in Startup.cs

services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver =
                    new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling =
                    ReferenceLoopHandling.Ignore;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        //Mapper.Initialize(cfg => cfg.AddProfile<MappingsProfile>());
        services.AddAutoMapper();

My problem, that in response I get text like this

{   "stateMachine": {
        "<>1__state": 0,
        "<>t__builder": {},
        "<>4__this": {}   },   "context": {},   "moveNextAction": {
        "method": {
          "name": "MoveNext",
          "declaringType": "System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[[System.Collections.Generic.List1[[TooSeeWeb.Core.DtoModels.Experiences.ExperienceListDto,
    TooSeeWeb.Core, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0,
    Culture=neutral,
    PublicKeyToken=7cec85d7bea7798e],[TooSeeWeb.Infrastructure.AppServices.Experiences.ExperienceAppService+<GetExperiences>d__3,
    TooSeeWeb.Infrastructure, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0,
    Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
          "reflectedType": "System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[[System.Collections.Generic.List1[[TooSeeWeb.Core.DtoModels.Experiences.ExperienceListDto,
    TooSeeWeb.Core, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0,
    Culture=neutral,
    PublicKeyToken=7cec85d7bea7798e],[TooSeeWeb.Infrastructure.AppServices.Experiences.ExperienceAppService+d__3,
    TooSeeWeb.Infrastructure, Version=1.0.0.0, Culture=neutral,
    PublicKeyToken=null]], System.Private.CoreLib, Version=4.0.0.0,
    Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
          "memberType": 8,
          "metadataToken": 100682290,
          "module": {
            "mdStreamVersion": 131072,
            "fullyQualifiedName": "/usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.2.5/System.Private.CoreLib.dll",
            "moduleVersionId": "9aeda1ea-7722-4ca6-a7ca-c000af27dec0",
            "metadataToken": 1,

Aтв much more code, and in the end, I get values from method. Where is my problem can be?

Body:
My problem was not in mapper.
In Controller, I was returning a list like this

    [HttpGet]
    public IActionResult GetExperiences()
    {
        var experiences = _experienceAppService.GetExperiences();
        return Ok(experiences);
    }

Instead of this

    [HttpGet]
    public IActionResult GetExperiences()
    {
        var experiences = _experienceAppService.GetExperiences();
        return Ok(experiences.Result);
    }