问:
In Matlab, how can I use chroma subsampling to downscale a 4:4:4 image to 4:2:0 when the image is in YCbCr?
I have already converted the jpg images from RGB to YCbCr but must now use Chroma Subsampling to make them 4:2:0. I have searched but have not found any information on how to do this (note: I am very new to Matlab)

Edit: I now have this but at the bottom where I am setting ycbcr(:,:,2) = newCb it says "Unable to perform assignment because the size of the left side is 1273-by-1910 and the size of the right side is
1273-by-955-by-0."

```<code>function f = conversion(source_image, source_name)

image = imread(source_image);

% conversion_matrix = [0.299 -0.168736 0.5;
%                      0.587 -.0331264 -.0418688;
%                      0.114  0.5 -.081312];

conversion_matrix = [0.299 0.587 0.114;
                     -0.168736 -.0331264 0.5;
                     0.5  -.0418688 -.081312];

ycbr = reshape(double(image),[],3)*conversion_matrix;

ycbr = reshape(uint8(ycbr),size(image));

Y = ycbr(:,:,1)+ 0;
Cb = ycbr(:,:,2)+ 0.5;
Cr = ycbr(:,:,3)+ 0.5;

Cb = double(Cb);
newCb = uint8(round((Cb(:,1:2:end, 1:2:end) + Cb(:,2:2:end, 1:2:end) + Cb(:,1:2:end, 2:2:end) + Cb(:,2:2:end, 2:2:end)) / 4));
Cr = double(Cr);
newCr = uint8(round((Cr(:,1:2:end, 1:2:end) + Cr(:,2:2:end, 1:2:end) + Cr(:,1:2:end, 2:2:end) + Cr(:,2:2:end, 2:2:end)) / 4));

ycbcr(:,:,1) = Y;
ycbcr(:,:,2) = newCb;
ycbcr(:,:,3) = newCr;

imshow(ycbcr);
imwrite(ycbcr, source_name);

f = ycbcr;
</code>```

答:
You can simply resize Cb and Cr by a factor of 0.5 in each axis:

Assume:

```<code>YUV = rgb2ycbcr(RGB);
Y = YUV(:, :, 1);
U = YUV(:, :, 2);
V = YUV(:, :, 3);
</code>```

Y channel is unmodified (same Y for 4:2:0 as in 4:4:4 format)

Down-sample U and V by a factor of 0.5 for getting 4:2:0 format:

```<code>newU = imresize(U, 0.5);
newV = imresize(V, 0.5);
</code>```

In MATLAB you usually like to keep the 420 result Y, newU, newV and 3 matrices (planar format), and not merge the matrices into one matrix.

The 4:2:0 format doesn't dictates specific components ordering (like I420, or NV12...) so the three matrices are considered to be in 4:2:0 format.

Down-sampling without using imresize:

You can Down-sample U and V using the following code sample:

```<code>U = double(U);
newU = uint8(round((U(1:2:end, 1:2:end) + U(2:2:end, 1:2:end) + U(1:2:end, 2:2:end) + U(2:2:end, 2:2:end)) / 4));
</code>```

Result is equivalent to resizing with bi-linear interpolation, without Anti-aliasing filter:

```<code>shrunkU = imresize(U, 0.5, 'bilinear', 'Antialiasing', false);
</code>```

Update:

The conversion formula you have posted is incorrect (at least not the same as MATLAB builtin rgb2ycbcr conversion formula).

MATLAB conversion formula matches BT.601 "limited range" standard.

It also looks like you have a mistake in the vector by matrix multiplication.

As I commented, I recommend you to save the 420 result to binary file.

The following code sample performs the following steps:

Convert RGB to YCbCr without using builtin function, and compare the result to MATLAB rgb2ycbcr result.

Convert from YCbCr 444 to YCbCr 420 (without using builtin function).

Save the 420 result to binary file im.yuv

Convert im.yuv to PNG format using FFmpeg command line tool, and show the result.

Here is the code:

```<code>RGB = imresize(imread('autumn.png'), [100, 170]); % Load RGB image for testing (and resize)

% Convert to YCbCr using MATLAB builtin function (used as reference)
refYUV = rgb2ycbcr(RGB);

% Conversion matrix applies BT.601 standard ("limited range").
T = [ 0.2568    0.5041    0.0979
     -0.1482   -0.2910    0.4392
      0.4392   -0.3678   -0.0714];

% Conversion offset (for "limted range" standard the offset for Y channel is 16)
offset = [16
          128
          128];

% Manual conversion from RGB to YCbCr (YUV is a shortcut name from YCbCr):
% Multiply T matrix (from the left side) by three "long rows" of RGB elements and add offsets vector.
YUV = T*(reshape(double(RGB), [], 3))' +  offset;

% Reshape YUV to the shape of RGB, and convert back to uint8.
YUV = uint8(reshape(YUV', size(RGB)));

% Verify that YUV equals refYUV (maximum difference result is 1 out of 255)
disp(['Max Diff = ', num2str(max(imabsdiff(YUV(:), refYUV(:))))]);

% Convert to YUV 420 (without builtin function):
Y = YUV(:, :, 1)
U = double(YUV(:, :, 2))
V = double(YUV(:, :, 3))
newU = uint8(round((U(1:2:end, 1:2:end) + U(2:2:end, 1:2:end) + U(1:2:end, 2:2:end) + U(2:2:end, 2:2:end)) / 4));
newV = uint8(round((V(1:2:end, 1:2:end) + V(2:2:end, 1:2:end) + V(1:2:end, 2:2:end) + V(2:2:end, 2:2:end)) / 4));

% Save result to YUV file (file format is going to be raw I420 foramt):
% Make sure to transpose the matrix before saving (becuase MATLAB is "column major", and fomrat is "row major").
f = fopen('im.yuv', 'w');
fwrite(f, Y', 'uint8');
fwrite(f, newU', 'uint8');
fwrite(f, newV', 'uint8');
fclose(f);

% Convert im.yuv to PNG format using FFmpeg (free command line tool).
% For Windows system, download stable stsatic build from https://ffmpeg.zeranoe.com/builds/
% Place ffmpeg.exe in the same path of the script (just for testing withing MATLAB)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[status, cmdout] = system('ffmpeg -y -s 170x100 -i im.yuv -pix_fmt yuv420p im.png');

% Read and show im.png for testing:
I = imread('im.png');
imshow(I)
</code>```

Result (after converting to YCbCr 420 and converting back to RGB using FFmpeg):

Body:
I have already converted the jpg images from RGB to YCbCr but must now use Chroma Subsampling to make them 4:2:0. I have searched but have not found any information on how to do this (note: I am very new to Matlab)

Edit: I now have this but at the bottom where I am setting ycbcr(:,:,2) = newCb it says "Unable to perform assignment because the size of the left side is 1273-by-1910 and the size of the right side is
1273-by-955-by-0."

function f = conversion(source_image, source_name)

image = imread(source_image);

% conversion_matrix = [0.299 -0.168736 0.5;
%                      0.587 -.0331264 -.0418688;
%                      0.114  0.5 -.081312];

conversion_matrix = [0.299 0.587 0.114;
                     -0.168736 -.0331264 0.5;
                     0.5  -.0418688 -.081312];

ycbr = reshape(double(image),[],3)*conversion_matrix;

ycbr = reshape(uint8(ycbr),size(image));

Y = ycbr(:,:,1)+ 0;
Cb = ycbr(:,:,2)+ 0.5;
Cr = ycbr(:,:,3)+ 0.5;

Cb = double(Cb);
newCb = uint8(round((Cb(:,1:2:end, 1:2:end) + Cb(:,2:2:end, 1:2:end) + Cb(:,1:2:end, 2:2:end) + Cb(:,2:2:end, 2:2:end)) / 4));
Cr = double(Cr);
newCr = uint8(round((Cr(:,1:2:end, 1:2:end) + Cr(:,2:2:end, 1:2:end) + Cr(:,1:2:end, 2:2:end) + Cr(:,2:2:end, 2:2:end)) / 4));

ycbcr(:,:,1) = Y;
ycbcr(:,:,2) = newCb;
ycbcr(:,:,3) = newCr;

imshow(ycbcr);
imwrite(ycbcr, source_name);

f = ycbcr;

Body:
You can simply resize Cb and Cr by a factor of 0.5 in each axis:

Assume:

YUV = rgb2ycbcr(RGB);
Y = YUV(:, :, 1);
U = YUV(:, :, 2);
V = YUV(:, :, 3);

Y channel is unmodified (same Y for 4:2:0 as in 4:4:4 format)

Down-sample U and V by a factor of 0.5 for getting 4:2:0 format:

newU = imresize(U, 0.5);
newV = imresize(V, 0.5);

In MATLAB you usually like to keep the 420 result Y, newU, newV and 3 matrices (planar format), and not merge the matrices into one matrix.

The 4:2:0 format doesn't dictates specific components ordering (like I420, or NV12...) so the three matrices are considered to be in 4:2:0 format.

Down-sampling without using imresize:

You can Down-sample U and V using the following code sample:

U = double(U);
newU = uint8(round((U(1:2:end, 1:2:end) + U(2:2:end, 1:2:end) + U(1:2:end, 2:2:end) + U(2:2:end, 2:2:end)) / 4));

Result is equivalent to resizing with bi-linear interpolation, without Anti-aliasing filter:

shrunkU = imresize(U, 0.5, 'bilinear', 'Antialiasing', false);

Update:

The conversion formula you have posted is incorrect (at least not the same as MATLAB builtin rgb2ycbcr conversion formula).

MATLAB conversion formula matches BT.601 "limited range" standard.

It also looks like you have a mistake in the vector by matrix multiplication.

As I commented, I recommend you to save the 420 result to binary file.

The following code sample performs the following steps:

Convert RGB to YCbCr without using builtin function, and compare the result to MATLAB rgb2ycbcr result.

Convert from YCbCr 444 to YCbCr 420 (without using builtin function).

Save the 420 result to binary file im.yuv

Convert im.yuv to PNG format using FFmpeg command line tool, and show the result.

Here is the code:

RGB = imresize(imread('autumn.png'), [100, 170]); % Load RGB image for testing (and resize)

% Convert to YCbCr using MATLAB builtin function (used as reference)
refYUV = rgb2ycbcr(RGB);

% Conversion matrix applies BT.601 standard ("limited range").
T = [ 0.2568    0.5041    0.0979
     -0.1482   -0.2910    0.4392
      0.4392   -0.3678   -0.0714];

% Conversion offset (for "limted range" standard the offset for Y channel is 16)
offset = [16
          128
          128];

% Manual conversion from RGB to YCbCr (YUV is a shortcut name from YCbCr):
% Multiply T matrix (from the left side) by three "long rows" of RGB elements and add offsets vector.
YUV = T*(reshape(double(RGB), [], 3))' +  offset;

% Reshape YUV to the shape of RGB, and convert back to uint8.
YUV = uint8(reshape(YUV', size(RGB)));

% Verify that YUV equals refYUV (maximum difference result is 1 out of 255)
disp(['Max Diff = ', num2str(max(imabsdiff(YUV(:), refYUV(:))))]);

% Convert to YUV 420 (without builtin function):
Y = YUV(:, :, 1)
U = double(YUV(:, :, 2))
V = double(YUV(:, :, 3))
newU = uint8(round((U(1:2:end, 1:2:end) + U(2:2:end, 1:2:end) + U(1:2:end, 2:2:end) + U(2:2:end, 2:2:end)) / 4));
newV = uint8(round((V(1:2:end, 1:2:end) + V(2:2:end, 1:2:end) + V(1:2:end, 2:2:end) + V(2:2:end, 2:2:end)) / 4));

% Save result to YUV file (file format is going to be raw I420 foramt):
% Make sure to transpose the matrix before saving (becuase MATLAB is "column major", and fomrat is "row major").
f = fopen('im.yuv', 'w');
fwrite(f, Y', 'uint8');
fwrite(f, newU', 'uint8');
fwrite(f, newV', 'uint8');
fclose(f);

% Convert im.yuv to PNG format using FFmpeg (free command line tool).
% For Windows system, download stable stsatic build from https://ffmpeg.zeranoe.com/builds/
% Place ffmpeg.exe in the same path of the script (just for testing withing MATLAB)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[status, cmdout] = system('ffmpeg -y -s 170x100 -i im.yuv -pix_fmt yuv420p im.png');

% Read and show im.png for testing:
I = imread('im.png');
imshow(I)

Result (after converting to YCbCr 420 and converting back to RGB using FFmpeg):


来源: stackexchange

问:
Does FlashPlayer 10 support MP4 and AAC audio codecs in addition to MP3?
I am developing an Audio Player application in Adobe AIR with Flex SDK 3.2. I wanted to know if i can play songs in other audio formats?</p>

答: Although Adobe's site says, Flash Player 9 Update 3 onwards supports AAC and MP4 also, i am not able to play them when i tested. So i think its safe to say that, Flash Player will only support MP3 and WAV files to play sounds.</p>

ContentLicense: CC BY-SA 3.0


问:
How to install VS Code in Alpine Linux
I have an operating environment that is Alpine linux only and I need to install VS Code. How can VS Code be run on Alpine Linux?</p>

答:
Apologies for necrobump, but as what Marco suggested, coder.com has moved to github

the software, code-server is quite litterally VSCode, as a web application, I have been using this for about half a year and it is quite well developed, Alpine support is still spotty but i recall getting a few releases to function well a while back when i ran Alpine as my main.

ContentLicense: CC BY-SA 4.0

Title: How to install VS Code in Alpine Linux


问:
Alamofire 5 inherit 'DataRequest'
Trying to inherit DataRequest from Alamofire gives me an access error because from Alamofire 5 I see that DataRequest class is public and not open. My question is: Is there a possibility to inherit it without modifying the Alamofire sources?

Edit 1:

I'm looking to make a CoreData cache system. I'll like to save the request and the response before decoding it. In routes I specify the age and size of each one.

```<code>@discardableResult
    func performRequest<T: Decodable>(for route: Route, decoder: JSONDecoder = JSONDecoder(), completion: @escaping (Result<T, AFError>) -> Void) -> DataRequest {
        return sessionManager.request(NetworkRouter(route))
            .validate(statusCode: 200..<300)
            .cacheResponse()
            .responseDecodable(decoder: decoder) { (response: DataResponse<T, AFError>) in
                completion(response.result)
        }
    }
</code>```

答:
No, DataRequest is purposefully not open. If you'd like to discuss alternatives to subclassing, update your question with your requirements or feel free to open a topic on our Swift forum.

To separate out a cache, it really depends on what you're caching. If you're caching data and want to operate directly in the request pipeline, you can implement CachedResponseHandler to decided when and where to cache responses. If you want to do it after a response, you could put the handling in your responseDecodable, or implement your own ResponseSerializer if you need access to the raw Data.

Ultimately, where you'd implement the cache comes down to what exactly you're caching and when you want to cache it. A subclass isn't necessary.

Title: Alamofire 5 inherit 'DataRequest'

Body:
Trying to inherit DataRequest from Alamofire gives me an access error because from Alamofire 5 I see that DataRequest class is public and not open. My question is: Is there a possibility to inherit it without modifying the Alamofire sources?

Edit 1:

I'm looking to make a CoreData cache system. I'll like to save the request and the response before decoding it. In routes I specify the age and size of each one.

@discardableResult
    func performRequest<T: Decodable>(for route: Route, decoder: JSONDecoder = JSONDecoder(), completion: @escaping (Result<T, AFError>) -> Void) -> DataRequest {
        return sessionManager.request(NetworkRouter(route))
            .validate(statusCode: 200..<300)
            .cacheResponse()
            .responseDecodable(decoder: decoder) { (response: DataResponse<T, AFError>) in
                completion(response.result)
        }
    }


问:
API Gateway with Static Elastic IP
Hi We have an aws API gateway configured with lambda and now want to integrate with a vendor wherein vendor want us to provide him with a Static IP against the API Gateway that we have. As per my knowledge API gateway serves request through Dynamic Elastic IP which are listed here

Is there a way to achieve this other than putting a forward proxy or NLB.

答: You can also use a static IP proxy service such as QuotaGuard. I use that to deal with services that want to whitelist my IP when using dynamic DNS.</p>

Title: API Gateway with Static Elastic IP


问:
Using classes breaks my code by IDs don't
When I use IDs in my HTML and select them in my javascript code with the getElementByID, my code works, but when I change them to classes my code does not work anymore.

I would like to use classes because I am working on a project with someone else who prefers classes.

Also, does it make a difference using classes vs IDs for javascript code?

const email = document.getElementsByClassName('email');
const form = document.getElementsByClassName('form');
const emailMessage = document.getElementsByClassName('empty-email-message');
const errorEmail = document.getElementsByClassName('invalid-email-message');

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    emailMessage.innerHTML = 'where is the email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form" id="form" action="submit">
            <input class="email" type="email"/>
            <button type="submit">Go</button>
            <!-- dont use id -->
            <p class="empty-email-message"></p>
            <p class="invalid-email-message"></p>
          </form></code>```

const email = document.getElementById('email');
const form = document.getElementById('form');
const emailMessage = document.getElementById('empty-email-message');
const errorEmail = document.getElementById('invalid-email-message');

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    emailMessage.innerHTML = 'where is the email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form" id="form" action="submit">
            <input id="email" type="email"/>
            <button type="submit">Go</button>
            <!-- dont use id -->
            <p id="empty-email-message"></p>
            <p id="invalid-email-message"></p>
          </form></code>```

答:
Use ID when there is only one of them and you need to refer to it directly. It wouldn't make as much sense to use classes given that the idea of classes is to have multiple but the JavaScript can only get one.

You can go for getElementsByClassName but like I said if you are only getting one then use IDs.

Body:
When I use IDs in my HTML and select them in my javascript code with the getElementByID, my code works, but when I change them to classes my code does not work anymore.

I would like to use classes because I am working on a project with someone else who prefers classes.

Also, does it make a difference using classes vs IDs for javascript code?

const email = document.getElementsByClassName('email');
const form = document.getElementsByClassName('form');
const emailMessage = document.getElementsByClassName('empty-email-message');
const errorEmail = document.getElementsByClassName('invalid-email-message');

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    emailMessage.innerHTML = 'where is the email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});

<form class="form" id="form" action="submit">
            <input class="email" type="email"/>
            <button type="submit">Go</button>

          </form>

const email = document.getElementById('email');
const form = document.getElementById('form');
const emailMessage = document.getElementById('empty-email-message');
const errorEmail = document.getElementById('invalid-email-message');

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    emailMessage.innerHTML = 'where is the email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});

<form class="form" id="form" action="submit">
            <input id="email" type="email"/>
            <button type="submit">Go</button>

          </form>


问:
Command to display last directory with a special file
I have a directory with this structure:

```<code>Fruitables
├── Fruits
│   ├── Grapes
│   │   └── Muscat Grape
│   │       ├── Moscato Giallo
│   │       │   └── information.txt
│   │       └── Muscat Ottonel
│   │           └── information.txt
│   └── Mangoes
│       ├── Ataulfo Mango
│       │   └── information.txt
│       └── Tommy Atkins Mango
│           └── information.txt
└── Vegetables
    └── Potatoes
        ├── Ratte Potato
        │   └── information.txt
        └── Yukon Gold Potato
            └── information.txt
</code>```

Some of the information.txt files have the String: "Special Fruit or Vegetable" .. What I want is to display the directory that contains a information.txt file with that string

I tried this:

```<code>shopt -s extglob
shopt -s globstar
grep -H 'Special Fruit or Vegetable' @(Fruitables)/**/*.txt | cut -d: -f1
</code>```

This is the output:

```<code>Fruitables/Fruits/Grapes/Muscat Grape/Moscato Giallo/information.txt
Fruitables/Fruits/Mangoes/Ataulfo Mango/information.txt
Fruitables/Vegetables/Potatoes/Ratte Potato/information.txt
</code>```

I want to display the last directory only, like this:

```<code>Moscato Giallo
Ataulfo Mango
Ratte Potato
</code>```

答:
Not POSIX compatible, but a bit safer on the file names:

```<code>grep -rlZ 'Special Fruit or Vegetable' --include 'information.txt' ./ |
  xargs -0 dirname -z |
  xargs -0 -n1 basename
</code>```

-r recursively search all directories

-l return filenames with match instead of matching lines

-Z separate filenames with null instead of newline/:

--include 'information.txt' - search only files with name information.txt

xargs -0 dirname -z - run dirname with the found files, output a null after each dirname (-z)

xargs -0 -n1 basename - run basename with one argument (-n1) as many times needed.

POSIX variant:

```<code>find ./ -name 'information.txt' \
    -exec grep -q 'Special Fruit or Vegetable' {} \;
    -exec sh -c 'basename "$(dirname "{}")"' \;
</code>```

-name 'information.txt' - search for files named information.txt

-exec grep -q 'Special Fruit or Vegetable' {} \; - do they match ? -q tells grep just to have the exit code set if a match is found

-exec sh -c 'basename "$(dirname "{}")"' \; - uses shell script to extract the basename of the dirname of the file.

Body:
I have a directory with this structure:

Fruitables
├── Fruits
│   ├── Grapes
│   │   └── Muscat Grape
│   │       ├── Moscato Giallo
│   │       │   └── information.txt
│   │       └── Muscat Ottonel
│   │           └── information.txt
│   └── Mangoes
│       ├── Ataulfo Mango
│       │   └── information.txt
│       └── Tommy Atkins Mango
│           └── information.txt
└── Vegetables
    └── Potatoes
        ├── Ratte Potato
        │   └── information.txt
        └── Yukon Gold Potato
            └── information.txt

Some of the information.txt files have the String: "Special Fruit or Vegetable" .. What I want is to display the directory that contains a information.txt file with that string

I tried this:

shopt -s extglob
shopt -s globstar
grep -H 'Special Fruit or Vegetable' @(Fruitables)/**/*.txt | cut -d: -f1

This is the output:

Fruitables/Fruits/Grapes/Muscat Grape/Moscato Giallo/information.txt
Fruitables/Fruits/Mangoes/Ataulfo Mango/information.txt
Fruitables/Vegetables/Potatoes/Ratte Potato/information.txt

I want to display the last directory only, like this:

Moscato Giallo
Ataulfo Mango
Ratte Potato

Body:
Not POSIX compatible, but a bit safer on the file names:

grep -rlZ 'Special Fruit or Vegetable' --include 'information.txt' ./ |
  xargs -0 dirname -z |
  xargs -0 -n1 basename

-r recursively search all directories

-l return filenames with match instead of matching lines

-Z separate filenames with null instead of newline/:

--include 'information.txt' - search only files with name information.txt

xargs -0 dirname -z - run dirname with the found files, output a null after each dirname (-z)

xargs -0 -n1 basename - run basename with one argument (-n1) as many times needed.

POSIX variant:

find ./ -name 'information.txt' \
    -exec grep -q 'Special Fruit or Vegetable' {} \;
    -exec sh -c 'basename "$(dirname "{}")"' \;

-name 'information.txt' - search for files named information.txt

-exec grep -q 'Special Fruit or Vegetable' {} \; - do they match ? -q tells grep just to have the exit code set if a match is found

-exec sh -c 'basename "$(dirname "{}")"' \; - uses shell script to extract the basename of the dirname of the file.


问:
Instantiate all class objects serialized from xml
I have deserialized a XML file into a class that make my soap request object.
When I'm serializing C# class most of classes object not fill the output xml file.

Example

```<code>GetUserReq.Envelope getUser = new GetUserReq.Envelope();
getUserResponse = new GetUserRes.Envelope();
getUser.Body = new GetUserReq.Body();
getUser.Body.GetUser = new GetUserReq.GetUser();
getUser.Body.GetUser.ReturnedTags = new GetUserReq.ReturnedTags();

if (allReturnTags)
{
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups = new GetUserReq.AssociatedGroups();
    getUser.Body.GetUser.ReturnedTags.AssociatedDevices = new GetUserReq.AssociatedDevices();
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup = new GetUserReq.UserGroup() { Name = "", UserRoles = new GetUserReq.UserRoles() };
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup.UserRoles = new GetUserReq.UserRoles() { UserRole = "" };
}
</code>```

For each item nested in the "envelope", I need to create new object otherwise the output xml file will be empty by that tag.

There are any method could do a iteration and made what I need?

These is  a snippet code where start Envelope

```<code>public class GetUserReq {
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public class Envelope
        {
            [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
            public string Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Soapenv { get; set; }
            [XmlAttribute(AttributeName = "ns", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Ns { get; set; }
        }
</code>```

and go on with body that contains other classes

```<code>[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Body
    {
        [XmlElement(ElementName = "getUser", Namespace = "http://www.cisco.com/AXL/API/9.1")]
        public GetUser GetUser { get; set; }
    }
</code>```

答:
I did this code made from your example and modified for my neededs

```<code>    public T AllReturnTags<T>() => (T)AllReturnTags(typeof(T));

    public object AllReturnTags(Type type)
    {
        var newObj = Activator.CreateInstance(type); // create new instance of your target class

        Func<PropertyInfo, bool> query = q
             => q.PropertyType.IsClass &&
                q.CanWrite;

        foreach (var el in type.GetProperties().Where(query))
        {
            // create new instance of el cascade
            if (el.PropertyType == typeof(string))
            {
                el.SetValue(newObj, "", null);
            }
            if (el.PropertyType == typeof(Int32))
            {
                el.SetValue(newObj, 0, null);
            }
            if (el.PropertyType.IsClass && el.PropertyType != typeof(string) && el.PropertyType != typeof(Int32) && el.PropertyType.IsGenericType == true && el.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
            {
                var elInstance = AllReturnTags(el.PropertyType);
                Type itemType = typeof(List<>).MakeGenericType(elInstance.GetType());
                IList res = (IList)Activator.CreateInstance(itemType);
                res.Add(elInstance);
                try { el.SetValue(newObj, res, null); } catch {  };
            }
            if (el.PropertyType.IsClass && el.PropertyType != typeof(string) && el.PropertyType != typeof(Int32) && el.PropertyType.IsGenericType != true )
            {
                var elInstance = AllReturnTags(el.PropertyType);
                try { el.SetValue(newObj, elInstance, null); } catch { return elInstance; };
            }

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

This seems to work with single items and lists.
Thx you @AliReza

Body:
I have deserialized a XML file into a class that make my soap request object.
When I'm serializing C# class most of classes object not fill the output xml file.

Example

GetUserReq.Envelope getUser = new GetUserReq.Envelope();
getUserResponse = new GetUserRes.Envelope();
getUser.Body = new GetUserReq.Body();
getUser.Body.GetUser = new GetUserReq.GetUser();
getUser.Body.GetUser.ReturnedTags = new GetUserReq.ReturnedTags();

if (allReturnTags)
{
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups = new GetUserReq.AssociatedGroups();
    getUser.Body.GetUser.ReturnedTags.AssociatedDevices = new GetUserReq.AssociatedDevices();
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup = new GetUserReq.UserGroup() { Name = "", UserRoles = new GetUserReq.UserRoles() };
    getUser.Body.GetUser.ReturnedTags.AssociatedGroups.UserGroup.UserRoles = new GetUserReq.UserRoles() { UserRole = "" };
}

For each item nested in the "envelope", I need to create new object otherwise the output xml file will be empty by that tag.

There are any method could do a iteration and made what I need?

These is  a snippet code where start Envelope

public class GetUserReq {
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
        public class Envelope
        {
            [XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
            public string Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Soapenv { get; set; }
            [XmlAttribute(AttributeName = "ns", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Ns { get; set; }
        }

and go on with body that contains other classes

[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Body
    {
        [XmlElement(ElementName = "getUser", Namespace = "http://www.cisco.com/AXL/API/9.1")]
        public GetUser GetUser { get; set; }
    }

Body:
I did this code made from your example and modified for my neededs

    public T AllReturnTags<T>() => (T)AllReturnTags(typeof(T));

    public object AllReturnTags(Type type)
    {
        var newObj = Activator.CreateInstance(type); // create new instance of your target class

        Func<PropertyInfo, bool> query = q
             => q.PropertyType.IsClass &&
                q.CanWrite;

        foreach (var el in type.GetProperties().Where(query))
        {
            // create new instance of el cascade
            if (el.PropertyType == typeof(string))
            {
                el.SetValue(newObj, "", null);
            }
            if (el.PropertyType == typeof(Int32))
            {
                el.SetValue(newObj, 0, null);
            }
            if (el.PropertyType.IsClass && el.PropertyType != typeof(string) && el.PropertyType != typeof(Int32) && el.PropertyType.IsGenericType == true && el.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
            {
                var elInstance = AllReturnTags(el.PropertyType);
                Type itemType = typeof(List<>).MakeGenericType(elInstance.GetType());
                IList res = (IList)Activator.CreateInstance(itemType);
                res.Add(elInstance);
                try { el.SetValue(newObj, res, null); } catch {  };
            }
            if (el.PropertyType.IsClass && el.PropertyType != typeof(string) && el.PropertyType != typeof(Int32) && el.PropertyType.IsGenericType != true )
            {
                var elInstance = AllReturnTags(el.PropertyType);
                try { el.SetValue(newObj, elInstance, null); } catch { return elInstance; };
            }

        }
        return newObj;
    }

This seems to work with single items and lists.
Thx you @AliReza


问:
Getting Voting Responses according to the different mails sent which have same subject
```<code>Sub ExportVotingStatistics_Excel()
    Dim objRecipient As Outlook.Recipient
    Dim objVoteDictionary As Object
    Dim varVotingCounts As Variant
    Dim varVotingOptions As Variant
    Dim varVotingOption As Variant
    Dim i As Long
    Dim nRow As Integer
    Dim olapp As Outlook.Application
    Dim olMail As Outlook.MailItem
    Dim OutlookApp As Outlook.Application
    Dim OutlookNameSpace As Namespace
    Dim Folder As MAPIFolder
    Dim OutlookMail As Variant

Set olMail = Outlook.Application.ActiveExplorer.Selection(1)

Set OutlookApp = New Outlook.Application
Set OutlookNameSpace = OutlookApp.GetNamespace("MAPI")

Set Folder = OutlookNameSpace.GetDefaultFolder(olFolderInbox)

    'Fill in the predefined values
    Worksheets("Mail-Extraction").Activate
    With ActiveSheet
         .Cells.Font.Name = "Calibri"
         .Cells(1, 1) = "Voting Results for Email:"
         .Cells(1, 2) = "Company follow-up with client"
         .Cells(3, 1) = "Voting Options"
         .Cells(3, 2) = "Voting Recepient"
    End With
Set objVoteDictionary = CreateObject("Scripting.Dictionary")
'get the default voting options
varVotingOptions = Split(olMail.VotingOptions, ";")
'Add the voting responses to the dictionary
For Each varVotingOption In varVotingOptions
    objVoteDictionary.Add varVotingOption, 0
Next
'Add a custom voting response - "No Reply"
objVoteDictionary.Add "No Reply", 0

'Process all the voting responses
For Each olMailRecepient In olMail.Recipients
    If olMailRecepient.TrackingStatus = olTrackingReplied And olMail.Subject = "3rd follow-up with Sales Team Member" Then
'For Each OutlookMail In Folder.Items
'    If OutlookMail.Subject = "3rd follow-up with Sales Team Member" And OutlookMail.ReceivedTime = #2/17/2020# Then
        If objVoteDictionary.Exists(olMailRecepient.AutoResponse) Then
            objVoteDictionary.Item(olMailRecepient.AutoResponse) = objVoteDictionary.Item(olMailRecipient.AutoResponse) + 1
        Else
            objVoteDictionary.Add olMailRecepient.AutoResponse, 1
        End If
    End If
Next
'Get the voting options and Vote counts
varVotingOptions = objVoteDictionary.Keys
varVotingCounts = objVoteDictionary.Items

'Fill in the values in specific cells
    nRow = 4
    For i = LBound(varVotingOptions) To UBound(varVotingOptions)
        With ActiveSheet
             .Cells(nRow, 1) = olMail.VotingResponse
             .Cells(nRow, 2) = olMail.SenderName
        End With
        nRow = nRow + 1
    Next

End Sub
</code>```

The above code just gives the voting response for the mail that I have currently selected and not the entire mail directory.

答:
Well, of course, your code only works with the currently selected message returned by Outlook.Application.ActiveExplorer.Selection.

Add a loop over the Inbox items:

```<code>dim item As Object
...
for each item in Folder.Items
  if item.Class = 43 Then
    set olMail  = item
    For Each olMailRecepient In olMail.Recipients
      ...
    next
  End If
next
</code>```

Body:
Sub ExportVotingStatistics_Excel()
    Dim objRecipient As Outlook.Recipient
    Dim objVoteDictionary As Object
    Dim varVotingCounts As Variant
    Dim varVotingOptions As Variant
    Dim varVotingOption As Variant
    Dim i As Long
    Dim nRow As Integer
    Dim olapp As Outlook.Application
    Dim olMail As Outlook.MailItem
    Dim OutlookApp As Outlook.Application
    Dim OutlookNameSpace As Namespace
    Dim Folder As MAPIFolder
    Dim OutlookMail As Variant

Set olMail = Outlook.Application.ActiveExplorer.Selection(1)

Set OutlookApp = New Outlook.Application
Set OutlookNameSpace = OutlookApp.GetNamespace("MAPI")

Set Folder = OutlookNameSpace.GetDefaultFolder(olFolderInbox)

    'Fill in the predefined values
    Worksheets("Mail-Extraction").Activate
    With ActiveSheet
         .Cells.Font.Name = "Calibri"
         .Cells(1, 1) = "Voting Results for Email:"
         .Cells(1, 2) = "Company follow-up with client"
         .Cells(3, 1) = "Voting Options"
         .Cells(3, 2) = "Voting Recepient"
    End With
Set objVoteDictionary = CreateObject("Scripting.Dictionary")
'get the default voting options
varVotingOptions = Split(olMail.VotingOptions, ";")
'Add the voting responses to the dictionary
For Each varVotingOption In varVotingOptions
    objVoteDictionary.Add varVotingOption, 0
Next
'Add a custom voting response - "No Reply"
objVoteDictionary.Add "No Reply", 0

'Process all the voting responses
For Each olMailRecepient In olMail.Recipients
    If olMailRecepient.TrackingStatus = olTrackingReplied And olMail.Subject = "3rd follow-up with Sales Team Member" Then
'For Each OutlookMail In Folder.Items
'    If OutlookMail.Subject = "3rd follow-up with Sales Team Member" And OutlookMail.ReceivedTime = #2/17/2020# Then
        If objVoteDictionary.Exists(olMailRecepient.AutoResponse) Then
            objVoteDictionary.Item(olMailRecepient.AutoResponse) = objVoteDictionary.Item(olMailRecipient.AutoResponse) + 1
        Else
            objVoteDictionary.Add olMailRecepient.AutoResponse, 1
        End If
    End If
Next
'Get the voting options and Vote counts
varVotingOptions = objVoteDictionary.Keys
varVotingCounts = objVoteDictionary.Items

'Fill in the values in specific cells
    nRow = 4
    For i = LBound(varVotingOptions) To UBound(varVotingOptions)
        With ActiveSheet
             .Cells(nRow, 1) = olMail.VotingResponse
             .Cells(nRow, 2) = olMail.SenderName
        End With
        nRow = nRow + 1
    Next

End Sub

The above code just gives the voting response for the mail that I have currently selected and not the entire mail directory.

Body:
Well, of course, your code only works with the currently selected message returned by Outlook.Application.ActiveExplorer.Selection.

Add a loop over the Inbox items:

dim item As Object
...
for each item in Folder.Items
  if item.Class = 43 Then
    set olMail  = item
    For Each olMailRecepient In olMail.Recipients
      ...
    next
  End If
next


问:
React Native - Promise returns undefined
I have a js file that returns whether I have internet connection or not, and then in another js I have an if else statement that gets that value. The thing is im getting connection = undefined.</p>

```<code>import React from 'react';
import NetInfo from "@react-native-community/netinfo";

const isConnected = function() {
  NetInfo.fetch().then(state => {
    console.log("state.isConnected: ", state.isConnected)
    return state.isConnected
  });
}

export default isConnected;
</code>```

```<code>import isConnected from '../../src/utils/internetConnection';

async checking(){
   var connection = await isConnected()
   console.log("connection : ", connection)
   if (connection){
      return true
   }

   Alert.alert("There is no Internet connection")
   return
}
</code>```

答:
I am not 100% sure on this, but it could be as simple as

const isConnected = function() {
  return NetInfo.fetch().then(state => {
    console.log("state.isConnected: ", state.isConnected)
    return state.isConnected
  });
}```

Body:
I have a js file that returns whether I have internet connection or not, and then in another js I have an if else statement that gets that value. The thing is im getting connection = undefined.

import React from 'react';
import NetInfo from "@react-native-community/netinfo";

const isConnected = function() {
  NetInfo.fetch().then(state => {
    console.log("state.isConnected: ", state.isConnected)
    return state.isConnected
  });
}

export default isConnected;

import isConnected from '../../src/utils/internetConnection';

async checking(){
   var connection = await isConnected()
   console.log("connection : ", connection)
   if (connection){
      return true
   }

   Alert.alert("There is no Internet connection")
   return
}


问:
C++ Dynamic Array Increase Size By 1 with each add - ERROR
I'm working on an assignment for an OO C++ class and I'm stumped. The assignment is to add grade (int) to a dynamic array and increase the size of that array by 1. The array must start with zero. Here are the specifications given to us:

Specification Bundle.

Specification B1 - Dynamic Array
Create an array on the heap. Store student scores in it.

Specification B2 - Add Elements
Start your array at size 0 and increase it by one every time you add
a new score with menu option 1.

I've looked at numerous examples on the web in our book and I am just banging my head against the wall. I've moved stuff around, tried to put things in different orders etc. I've come up with the following code and it just wont work. I'm pretty sure someone with experience is just gonna tell me I forgot a comma but here goes. I understand the basic concept is to create the dynamic array, create a temporary array that is one size bigger, then copy the elements of the original array to the temp array and then to just point the dynamic array to the temp array's memory address, delete the old array then wash rinse repeat, but i just cant seem to do it. I need help :) Currently i get a heap corruption error message. Here's the code.

```<code>#include <iostream>
#include <cstdlib> // do not use
#include <ctime> // for seeding random numbers
#include <string>

using namespace std;

//Global Variables

//Function Prototypes
void ProgramGreeting(); // All programs will have this method - Draw a happy litte tree
int mainMenu(int[], int*, int*); //Main Menu
void addGrade(int[], int*, int*); // Add a grade to the list. Takes the array  and the number of items in the array
void displayGrades(int[], int); // Display all the grades. Takes the array and the number of items in the array
void processGrades(int[], int); // Process all the grades. Takes the array and the number of items in the array
char letterGrade(int); // Return a letter grade
void Unittest(); // All CISP400 programs should have this.

int main()
{
    // Specification B1 - Dynamic Array
    int* grades = NULL;
    int max = 0;
    int numofGrades = 0; //A counter for the size of the dynamic array
    grades = new int[max];

    ProgramGreeting();
    mainMenu(grades, &numofGrades, &max);

    delete[] grades;

    return 0;
}

void ProgramGreeting()
{
    // Specification C1 - Program Greeting Function
    cout << "Welcome to GPA Analyzer!" << endl;
    cout << "Written by William Graves" << endl;
    cout << "This assignment is due on February 16, 2020" << endl;
}

int mainMenu(int grades[], int *numofGrades, int *max)
{
    char ans;

    do {

        cout << "Main Menu" << endl;
        cout << "--------------" << endl;
        cout << "1) Add Grade" << endl;
        cout << "2) Display All Grades" << endl;
        cout << "3) Process All Grades" << endl;
        cout << "4) Quit" << endl << endl;
        cout << "Enter your choice: ";
        cin >> ans;

        switch (ans) {
        case '1': //The user selected add grade
            addGrade(grades, numofGrades, max);
            break;
        case '2': //Display all grades
            displayGrades(grades, *numofGrades);
            break;
        case '3': //Display all grades
            processGrades(grades, *numofGrades);
            break;
        case '4': //The user chose to exit.
            cout << "Exit time. ";
            return 1000;
            break;
            // Specification C4 - Bulletproof Menu
        default:
            cout << "Your selection of '" << ans << "' is invalid. Try again." << endl;
            break;
        }
    } while (1);

}

void addGrade(int grades[], int *numofGrades, int *max) // Add a grade to the list. Takes the array  and the number of items in the array
{
    int gradeEntry = 0;
    cout << "Enter the grade: ";
    cin >> gradeEntry;
    if (gradeEntry <= 100 && gradeEntry >= 0) //verify that the grade entered is between 0 and 100
    {
        grades[*numofGrades] = gradeEntry;
        cout << "Grade of " << gradeEntry << " added successfully.";
        *numofGrades = *numofGrades + 1;
        if (*numofGrades >= *max)
        {
            *max += 1;
            //create a temporary array a size bigger:
            int* tempArray = new int[*max];
            //copy the contents of the old array to the newly allocated array
            for (int i = 0; i < *numofGrades; i++)
            {
                tempArray[i] = grades[i];
            }
            //get rid of the old array.
            delete[] grades;
            //change the memory location.
            grades = tempArray;
        }
        return;
    }
    else
    {
        cout << "Error occured. User entered: " << gradeEntry << " The grade must be an integer between 0 and 100. No grade added." << endl;
        return;
    }
}
</code>```

答:
Your primary problem is you are passing a pointer to grades to your addGrade function:

```<code>void addGrade(int grades[], int *numofGrades, int *max)
</code>```

(int grades[] is actually passed as int *grades)

When you do that addGrade receives a copy of the pointer, and since you are not returning the new pointer, nothing you do to grades in addGrade is ever seen back in the calling function. All changes are lost when the function returns.

You have two (really three) options (1) pass a reference to the pointer grades, or (2) change the return type of addGrade to int * and return a pointer to the new block of memory allocated and assign it to grades back in main(), and (3) - a note, you can pass the address of the pointer for grades to addGrade with int** as you would in C)

Here, preserving your void return type, the sensible thing to do is pass a reference to the pointer grades, e.g.

```<code>void addGrade (int*& grades, int *ngrades, int gradetoadd)
</code>```

(with the general note that the really sensible thing to do is to use the STL provided std::vector<int> instead of the fundamental type int*, but I understand this is a learning exercise)

The next thing that will greatly help with debugging is to Separate Your Implementation From Your User Interface, meaning, don't co-mingle the user interface and the actual data processing logic of your code. Keep them separate. It makes coding and testing the implementation must easier. Then add the interface after your core data handling code is done.

For example, let's just write the addGrade function alone and a short interface that feeds it grades for testing. The only interface will be to send integers to addGrade for testing and a loop to spit out the results, e.g.

```<code>#include <iostream>
#include <iomanip>
#include <cstring>

void addGrade (int*& grades, int *ngrades, int gradetoadd)
{
    int *newgrades = new int[*ngrades + 1];     /* allocate +1 integer */

    if (*ngrades) { /* if reallocating existing block of mem */
        memcpy (newgrades, grades, *ngrades * sizeof *grades);    /* copy */
        delete[] grades;       /* delete old */
    }
    grades = newgrades;        /* assign new block of mem to pointer */

    grades[(*ngrades)++] = gradetoadd;   /* add grade, increment ngrades */
}

int main (void) {

    int *grades = NULL,         /* a pointer to block of mem holding grades */
        ngrades = 0,            /* number of grades stored */
        tmp;                    /* temporary integer for input */

    while (std::cin >> tmp)                 /* while integer read */
        addGrade (grades, &ngrades, tmp);  /* add to grades, passing address of ptr */

    for (int i = 0; i < ngrades; i++)   /* output storged grades */
        std::cout << "grade[" << std::setw(2) << i << "] : " << grades[i] << '\n';

    delete[] grades;    /* free allocated block of memory */
}
</code>```

Now any debugging is limited to the logic of the gradeAdd function itself uncluttered by menus, etc.. Above, gradeAdd now takes a reference to the pointer for grades and any changes to grades in addGrade are now made to the original grades from main() instead of a copy of the pointer. Compile and test:

Example Input File

File with 20 grades 50-100:

```<code>$ cat dat/grades.txt
74
61
67
75
73
86
95
54
93
99
68
100
95
84
50
58
79
86
98
80
</code>```

Example Use/Output

Simple redirect the dat/grades.txt file as input on stdin to your test program:

```<code>$ ./bin/addgrade < dat/grades.txt
grade[ 0] : 74
grade[ 1] : 61
grade[ 2] : 67
grade[ 3] : 75
grade[ 4] : 73
grade[ 5] : 86
grade[ 6] : 95
grade[ 7] : 54
grade[ 8] : 93
grade[ 9] : 99
grade[10] : 68
grade[11] : 100
grade[12] : 95
grade[13] : 84
grade[14] : 50
grade[15] : 58
grade[16] : 79
grade[17] : 86
grade[18] : 98
grade[19] : 80
</code>```

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to ensure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

```<code>$ valgrind ./bin/addgrade < dat/grades.txt
==4612== Memcheck, a memory error detector
==4612== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4612== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4612== Command: ./bin/addgrade
==4612==
grade[ 0] : 74
grade[ 1] : 61
grade[ 2] : 67
grade[ 3] : 75
grade[ 4] : 73
grade[ 5] : 86
grade[ 6] : 95
grade[ 7] : 54
grade[ 8] : 93
grade[ 9] : 99
grade[10] : 68
grade[11] : 100
grade[12] : 95
grade[13] : 84
grade[14] : 50
grade[15] : 58
grade[16] : 79
grade[17] : 86
grade[18] : 98
grade[19] : 80
==4612==
==4612== HEAP SUMMARY:
==4612==     in use at exit: 0 bytes in 0 blocks
==4612==   total heap usage: 23 allocs, 23 frees, 78,664 bytes allocated
==4612==
==4612== All heap blocks were freed -- no leaks are possible
==4612==
==4612== For counts of detected and suppressed errors, rerun with: -v
==4612== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Always confirm that you have freed all memory you have allocated and that there are no memory errors. (All memory freed and no-errors is confirmation that you are using the memory you allocate correctly)

Now you gradeAdd function is read to be incorporated into the remainder of your code and you can have confidence that there are no problems with that function. Any further debugging is simplified. Look things over and let me know if you have questions.

Body:
I'm working on an assignment for an OO C++ class and I'm stumped. The assignment is to add grade (int) to a dynamic array and increase the size of that array by 1. The array must start with zero. Here are the specifications given to us:

Specification Bundle.

Specification B1 - Dynamic Array
Create an array on the heap. Store student scores in it.

Specification B2 - Add Elements
Start your array at size 0 and increase it by one every time you add
a new score with menu option 1.

I've looked at numerous examples on the web in our book and I am just banging my head against the wall. I've moved stuff around, tried to put things in different orders etc. I've come up with the following code and it just wont work. I'm pretty sure someone with experience is just gonna tell me I forgot a comma but here goes. I understand the basic concept is to create the dynamic array, create a temporary array that is one size bigger, then copy the elements of the original array to the temp array and then to just point the dynamic array to the temp array's memory address, delete the old array then wash rinse repeat, but i just cant seem to do it. I need help :) Currently i get a heap corruption error message. Here's the code.

#include <iostream>
#include <cstdlib> // do not use
#include <ctime> // for seeding random numbers
#include <string>

using namespace std;

//Global Variables

//Function Prototypes
void ProgramGreeting(); // All programs will have this method - Draw a happy litte tree
int mainMenu(int[], int*, int*); //Main Menu
void addGrade(int[], int*, int*); // Add a grade to the list. Takes the array  and the number of items in the array
void displayGrades(int[], int); // Display all the grades. Takes the array and the number of items in the array
void processGrades(int[], int); // Process all the grades. Takes the array and the number of items in the array
char letterGrade(int); // Return a letter grade
void Unittest(); // All CISP400 programs should have this.

int main()
{
    // Specification B1 - Dynamic Array
    int* grades = NULL;
    int max = 0;
    int numofGrades = 0; //A counter for the size of the dynamic array
    grades = new int[max];

    ProgramGreeting();
    mainMenu(grades, &numofGrades, &max);

    delete[] grades;

    return 0;
}

void ProgramGreeting()
{
    // Specification C1 - Program Greeting Function
    cout << "Welcome to GPA Analyzer!" << endl;
    cout << "Written by William Graves" << endl;
    cout << "This assignment is due on February 16, 2020" << endl;
}

int mainMenu(int grades[], int *numofGrades, int *max)
{
    char ans;

    do {

        cout << "Main Menu" << endl;
        cout << "--------------" << endl;
        cout << "1) Add Grade" << endl;
        cout << "2) Display All Grades" << endl;
        cout << "3) Process All Grades" << endl;
        cout << "4) Quit" << endl << endl;
        cout << "Enter your choice: ";
        cin >> ans;

        switch (ans) {
        case '1': //The user selected add grade
            addGrade(grades, numofGrades, max);
            break;
        case '2': //Display all grades
            displayGrades(grades, *numofGrades);
            break;
        case '3': //Display all grades
            processGrades(grades, *numofGrades);
            break;
        case '4': //The user chose to exit.
            cout << "Exit time. ";
            return 1000;
            break;
            // Specification C4 - Bulletproof Menu
        default:
            cout << "Your selection of '" << ans << "' is invalid. Try again." << endl;
            break;
        }
    } while (1);

}

void addGrade(int grades[], int *numofGrades, int *max) // Add a grade to the list. Takes the array  and the number of items in the array
{
    int gradeEntry = 0;
    cout << "Enter the grade: ";
    cin >> gradeEntry;
    if (gradeEntry <= 100 && gradeEntry >= 0) //verify that the grade entered is between 0 and 100
    {
        grades[*numofGrades] = gradeEntry;
        cout << "Grade of " << gradeEntry << " added successfully.";
        *numofGrades = *numofGrades + 1;
        if (*numofGrades >= *max)
        {
            *max += 1;
            //create a temporary array a size bigger:
            int* tempArray = new int[*max];
            //copy the contents of the old array to the newly allocated array
            for (int i = 0; i < *numofGrades; i++)
            {
                tempArray[i] = grades[i];
            }
            //get rid of the old array.
            delete[] grades;
            //change the memory location.
            grades = tempArray;
        }
        return;
    }
    else
    {
        cout << "Error occured. User entered: " << gradeEntry << " The grade must be an integer between 0 and 100. No grade added." << endl;
        return;
    }
}

Body:
Your primary problem is you are passing a pointer to grades to your addGrade function:

void addGrade(int grades[], int *numofGrades, int *max)

(int grades[] is actually passed as int *grades)

When you do that addGrade receives a copy of the pointer, and since you are not returning the new pointer, nothing you do to grades in addGrade is ever seen back in the calling function. All changes are lost when the function returns.

You have two (really three) options (1) pass a reference to the pointer grades, or (2) change the return type of addGrade to int * and return a pointer to the new block of memory allocated and assign it to grades back in main(), and (3) - a note, you can pass the address of the pointer for grades to addGrade with int** as you would in C)

Here, preserving your void return type, the sensible thing to do is pass a reference to the pointer grades, e.g.

void addGrade (int*& grades, int *ngrades, int gradetoadd)

(with the general note that the really sensible thing to do is to use the STL provided std::vector<int> instead of the fundamental type int*, but I understand this is a learning exercise)

The next thing that will greatly help with debugging is to Separate Your Implementation From Your User Interface, meaning, don't co-mingle the user interface and the actual data processing logic of your code. Keep them separate. It makes coding and testing the implementation must easier. Then add the interface after your core data handling code is done.

For example, let's just write the addGrade function alone and a short interface that feeds it grades for testing. The only interface will be to send integers to addGrade for testing and a loop to spit out the results, e.g.

#include <iostream>
#include <iomanip>
#include <cstring>

void addGrade (int*& grades, int *ngrades, int gradetoadd)
{
    int *newgrades = new int[*ngrades + 1];     /* allocate +1 integer */

    if (*ngrades) { /* if reallocating existing block of mem */
        memcpy (newgrades, grades, *ngrades * sizeof *grades);    /* copy */
        delete[] grades;       /* delete old */
    }
    grades = newgrades;        /* assign new block of mem to pointer */

    grades[(*ngrades)++] = gradetoadd;   /* add grade, increment ngrades */
}

int main (void) {

    int *grades = NULL,         /* a pointer to block of mem holding grades */
        ngrades = 0,            /* number of grades stored */
        tmp;                    /* temporary integer for input */

    while (std::cin >> tmp)                 /* while integer read */
        addGrade (grades, &ngrades, tmp);  /* add to grades, passing address of ptr */

    for (int i = 0; i < ngrades; i++)   /* output storged grades */
        std::cout << "grade[" << std::setw(2) << i << "] : " << grades[i] << '\n';

    delete[] grades;    /* free allocated block of memory */
}

Now any debugging is limited to the logic of the gradeAdd function itself uncluttered by menus, etc.. Above, gradeAdd now takes a reference to the pointer for grades and any changes to grades in addGrade are now made to the original grades from main() instead of a copy of the pointer. Compile and test:

Example Input File

File with 20 grades 50-100:

$ cat dat/grades.txt
74
61
67
75
73
86
95
54
93
99
68
100
95
84
50
58
79
86
98
80

Example Use/Output

Simple redirect the dat/grades.txt file as input on stdin to your test program:

$ ./bin/addgrade < dat/grades.txt
grade[ 0] : 74
grade[ 1] : 61
grade[ 2] : 67
grade[ 3] : 75
grade[ 4] : 73
grade[ 5] : 86
grade[ 6] : 95
grade[ 7] : 54
grade[ 8] : 93
grade[ 9] : 99
grade[10] : 68
grade[11] : 100
grade[12] : 95
grade[13] : 84
grade[14] : 50
grade[15] : 58
grade[16] : 79
grade[17] : 86
grade[18] : 98
grade[19] : 80

Memory Use/Error Check

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to ensure you do not attempt to access memory or write beyond/outside the bounds of your allocated block, attempt to read or base a conditional jump on an uninitialized value, and finally, to confirm that you free all the memory you have allocated.

For Linux valgrind is the normal choice. There are similar memory checkers for every platform. They are all simple to use, just run your program through it.

$ valgrind ./bin/addgrade < dat/grades.txt
==4612== Memcheck, a memory error detector
==4612== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4612== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4612== Command: ./bin/addgrade
==4612==
grade[ 0] : 74
grade[ 1] : 61
grade[ 2] : 67
grade[ 3] : 75
grade[ 4] : 73
grade[ 5] : 86
grade[ 6] : 95
grade[ 7] : 54
grade[ 8] : 93
grade[ 9] : 99
grade[10] : 68
grade[11] : 100
grade[12] : 95
grade[13] : 84
grade[14] : 50
grade[15] : 58
grade[16] : 79
grade[17] : 86
grade[18] : 98
grade[19] : 80
==4612==
==4612== HEAP SUMMARY:
==4612==     in use at exit: 0 bytes in 0 blocks
==4612==   total heap usage: 23 allocs, 23 frees, 78,664 bytes allocated
==4612==
==4612== All heap blocks were freed -- no leaks are possible
==4612==
==4612== For counts of detected and suppressed errors, rerun with: -v
==4612== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm that you have freed all memory you have allocated and that there are no memory errors. (All memory freed and no-errors is confirmation that you are using the memory you allocate correctly)

Now you gradeAdd function is read to be incorporated into the remainder of your code and you can have confidence that there are no problems with that function. Any further debugging is simplified. Look things over and let me know if you have questions.


问:
How to package magento extension

Possible Duplicate:

  Magento Packaging an Extension

Hi,

I have created a wireframe theme for magento(1.5).I m trying to pack as an extension.But its not working.Here's what i did.I put my theme file wireframe(app,skin)in ./app/code/local/.
I selected magento local module has target path,I gave ./app/code/local/ in path.Is this correct?.What should i give in type section.What is the difference between file and recursive dir.
Magento creating 1kb zip file in var/connect/.But when i extract,i can see only xml file.
Any help would be appreciated?

答:
I selected magento local module has
  target path,I gave ./app/code/local/
  in path.Is this correct?

No. This is not correct.

Magento Local Module file is relative to app/code/local/. So, here you should give path as YourNamespace/YourModule and select Type as Recursive Dir.

What is the difference between file
  and recursive dir?

File means single file. Like a module global file in app/etc/YourNamespace_YourModule.xml.

Recursive Dir means a whole directory. Like in app/code/local/YourNamespace/YourModule.

After you create package, the package module is inside var/pear directory.

Hope this helps.

Edit:-

For skin files, select contents as below:-

Target = Magento Theme Skin (Images, CSS, JS) [ This is relative to skin/ (a slash after skin)]

Path = frontend/default/default/css/styles.css

See this article for screenshots:- Magento: How to create extension package? (IMAGES)

Title: How to package magento extension


问:
How to calculate the result list numbers in column?
I'm using SpreadsheetMapper tool, I want to calculate the result listed numbers in a column.

This code is not working when I use the result list.

```<code><#function TW nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum >
  </#if>
</#function>
${TW(result['TotalWeightListResult']!)}
</code>```

https://prnt.sc/r3h137

It works when I use static listed numbers.

```<code><#function TW nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum >
  </#if>
</#function>
${TW(10 20)}
</code>```

reference - https://freemarker.apache.org/docs/ref_directive_function.html

here is the first thing I'm thinking - How to calculate the listed numbers from the child datastore?

答:
If you declare TW with nums... parameter, and you pass a list to TW, it will be just the first element inside nums. That's because parameters have no declared type in FreeMarker, so it's not obvious what you meant.

There's a further confusing coincidence in you example. If you are sending somethingMissing! to TW, then the first element of nums will be an empty string, which is the result of the expression! operation. Because + is overloaded to work both as addition, and as string concatenation, sum += num will no fail, instead, it will do a string concatenation. So first it converts sum to the string "0", and then append the empty string to it. So you end up with return value "0", a string, which when it's printed, looks just like the number 0. But it's not really a 0 number.

So, just use <#function TW nums>, then it will work as expected. In case you want to pass a literal list, you can write TW([10, 20]) then. But I guess typically you don't want to pass a predefined list to TW, and so the extra [] is not a big deal.

Body:
I'm using SpreadsheetMapper tool, I want to calculate the result listed numbers in a column.

This code is not working when I use the result list.

<#function TW nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum >
  </#if>
</#function>
${TW(result['TotalWeightListResult']!)}

https://prnt.sc/r3h137

It works when I use static listed numbers.

<#function TW nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum >
  </#if>
</#function>
${TW(10 20)}

reference - https://freemarker.apache.org/docs/ref_directive_function.html

here is the first thing I'm thinking - How to calculate the listed numbers from the child datastore?


问:
POI doesn't copy ppt slide notes
When I tried to copy a ppt slide to a new ppt document. The slide presentation part was copied, but the slide notes was not copied.

I tried the MergePresentations.java from POI example. It does not copy the notes either.

I explicitly get notes from the source slide, then set it to the target slide. It still didn't work.

```<code>XSLFNotes sreNotes = srcSlide.getNotes();

XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide targetSlide = ppt.createSlide();
targetSlide.importContent(slide);
targetSlide.setNotes(sreNotes);
FileOutputStream out = new FileOutputStream(getNextFileName(RESULT_DIR, charName));
ppt.write(out);
out.close();
</code>```

How to copy ppt slides with notes? Your help is appreciated.

答:
I found a way to get notes from the source slide, then set it to a new slide. Of course, the text formatting will be lost.</p>

```<code>//Get note from a slide
private static String getNotesText(XSLFSlide slide) {

    XSLFNotes mynotes = slide.getNotes();
    for (XSLFShape shape : mynotes) {
        if (shape instanceof XSLFTextShape) {
            XSLFTextShape txShape = (XSLFTextShape) shape;
            for (XSLFTextParagraph xslfParagraph : txShape.getTextParagraphs()) {

                resultBuffer.append(xslfParagraph.getText())
                .append("\n");
            }
        }
    }

    return resultBuffer.toString();
}

private static void createNewPpt(XSLFSlide slide, Dimension pageSize) throws IOException {

    try (XMLSlideShow ppt = new XMLSlideShow()) {

        ppt.setPageSize(pageSize);

        XSLFSlide targetSlide = ppt.createSlide();
        targetSlide.importContent(slide);

        XSLFNotes targetNotes = ppt.getNotesSlide(targetSlide);
        for (XSLFTextShape targetShape : targetNotes.getPlaceholders()) {

            if (targetShape.getTextType() == Placeholder.BODY) {

                targetShape.setText(getNotesText(slide));
                break;
            }
        }

        FileOutputStream out = new FileOutputStream(getNextFileName(RESULT_DIR, charName));
        ppt.write(out);
        out.close();
    }
}
</code>```

Title: POI doesn't copy ppt slide notes

Body:
When I tried to copy a ppt slide to a new ppt document. The slide presentation part was copied, but the slide notes was not copied.

I tried the MergePresentations.java from POI example. It does not copy the notes either.

I explicitly get notes from the source slide, then set it to the target slide. It still didn't work.

XSLFNotes sreNotes = srcSlide.getNotes();

XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide targetSlide = ppt.createSlide();
targetSlide.importContent(slide);
targetSlide.setNotes(sreNotes);
FileOutputStream out = new FileOutputStream(getNextFileName(RESULT_DIR, charName));
ppt.write(out);
out.close();

How to copy ppt slides with notes? Your help is appreciated.

Body:
I found a way to get notes from the source slide, then set it to a new slide. Of course, the text formatting will be lost.

//Get note from a slide
private static String getNotesText(XSLFSlide slide) {

    XSLFNotes mynotes = slide.getNotes();
    for (XSLFShape shape : mynotes) {
        if (shape instanceof XSLFTextShape) {
            XSLFTextShape txShape = (XSLFTextShape) shape;
            for (XSLFTextParagraph xslfParagraph : txShape.getTextParagraphs()) {

                resultBuffer.append(xslfParagraph.getText())
                .append("\n");
            }
        }
    }

    return resultBuffer.toString();
}

private static void createNewPpt(XSLFSlide slide, Dimension pageSize) throws IOException {

    try (XMLSlideShow ppt = new XMLSlideShow()) {

        ppt.setPageSize(pageSize);

        XSLFSlide targetSlide = ppt.createSlide();
        targetSlide.importContent(slide);

        XSLFNotes targetNotes = ppt.getNotesSlide(targetSlide);
        for (XSLFTextShape targetShape : targetNotes.getPlaceholders()) {

            if (targetShape.getTextType() == Placeholder.BODY) {

                targetShape.setText(getNotesText(slide));
                break;
            }
        }

        FileOutputStream out = new FileOutputStream(getNextFileName(RESULT_DIR, charName));
        ppt.write(out);
        out.close();
    }
}


问:
Efficient date range overlap calculation?
I have two date ranges where each range is determined by a start and end date (obviously, datetime.date instances). The two ranges can overlap or not. I need the number of days of the overlap. Of course I can pre-fill two sets with all dates within both ranges and the perform a set intersection but this is possibly inefficient...is there a better way apart from another solution using a long if-elif section covering all cases?

答:
You can use the datetimerange package: https://pypi.org/project/DateTimeRange/

```<code>from datetimerange import DateTimeRange
time_range1 = DateTimeRange("2015-01-01T00:00:00+0900", "2015-01-04T00:20:00+0900")
time_range2 = DateTimeRange("2015-01-01T00:00:10+0900", "2015-01-04T00:20:00+0900")
tem3 = time_range1.intersection(time_range2)
if tem3.NOT_A_TIME_STR == 'NaT':  # No overlap
    S_Time = 0
else: # Output the overlap seconds
    S_Time = tem3.timedelta.total_seconds()
</code>```

"2015-01-01T00:00:00+0900" inside the DateTimeRange() can also be datetime format, like Timestamp('2017-08-30 20:36:25').

Body:
You can use the datetimerange package: https://pypi.org/project/DateTimeRange/

from datetimerange import DateTimeRange
time_range1 = DateTimeRange("2015-01-01T00:00:00+0900", "2015-01-04T00:20:00+0900")
time_range2 = DateTimeRange("2015-01-01T00:00:10+0900", "2015-01-04T00:20:00+0900")
tem3 = time_range1.intersection(time_range2)
if tem3.NOT_A_TIME_STR == 'NaT':  # No overlap
    S_Time = 0
else: # Output the overlap seconds
    S_Time = tem3.timedelta.total_seconds()

"2015-01-01T00:00:00+0900" inside the DateTimeRange() can also be datetime format, like Timestamp('2017-08-30 20:36:25').


问:
how to include a parameter into a mask or where function in a Koalas dataframe
I have a Koalas dataframe running in Azure databricks, lets say:

```<code>import databricks.koalas   as pd

df = pd.DataFrame({'category': ['A', 'A', 'B'],
                   'col1': [1, 2, 3],
                   'col2': [4, 5, 6]},
                  columns=['category', 'col1', 'col2'])
</code>```

I want to create a new column (currently in a function) that evaluates a column depending on its values (which are finite and known) and fills the new column with elements from another dataset's columns. (Why?, because this second dataset contains parameters to include and has been previously filtered before being used for this data extraction)

I have tried (code from within a function that calls df and params)

```<code>    return      df.assign(col3= df.category.map({
      'A': params['column1'] ,
      'B' : params['column2']  ,
      'C': params['column3']
    #}) )
</code>```

with error message:

```<code>PandasNotImplementedError: The method `pd.Index.__iter__()` is not implemented. If you want to collect your data as an NumPy array, use 'to_numpy()' instead.
</code>```

which is weird as I have no call to Pandas anywhere

Also I have tried:

```<code>    df = df.assign(col3 = None)

    return     df.col3.mask(df.category== 'A', params['column1']) \
                .mask(df.category == 'B' , params['column2'])\
                .mask(df.category == 'C', params['column3'])
</code>```

In the second case, the returned dataframe has all nan values.

I have also already set 'compute.ops_on_diff_frames' to True

答:
I found a work-around to this issue, but I am still not clear on the why.

In my case I am making two steps. The first is to reset index of the filtered parameter dataframe.

```<code>params = orig_params.loc[*whatever filtering may fit here*].reset_index()
</code>```

Secondly, just use the filtered element that we want. If not using this step, the masking will require you to input a series as long as required. Here, we just convert it into a scalar, like:

```<code>    temp = df.category
    temp = temp.mask(temp == 'A', params['column1'][0]) \
      .mask(temp == 'B' , params['column2'][0])\
      .mask(temp == 'C', params['column3'][0])
    df1 = df.assign(col3 = temp)
    return df1
</code>```

Hopefully this is useful.
If anybody has a better solution and/or explanation please post it.

Body:
I have a Koalas dataframe running in Azure databricks, lets say:

import databricks.koalas   as pd

df = pd.DataFrame({'category': ['A', 'A', 'B'],
                   'col1': [1, 2, 3],
                   'col2': [4, 5, 6]},
                  columns=['category', 'col1', 'col2'])

I want to create a new column (currently in a function) that evaluates a column depending on its values (which are finite and known) and fills the new column with elements from another dataset's columns. (Why?, because this second dataset contains parameters to include and has been previously filtered before being used for this data extraction)

I have tried (code from within a function that calls df and params)

    return      df.assign(col3= df.category.map({
      'A': params['column1'] ,
      'B' : params['column2']  ,
      'C': params['column3']
    #}) )

with error message:

PandasNotImplementedError: The method `pd.Index.__iter__()` is not implemented. If you want to collect your data as an NumPy array, use 'to_numpy()' instead.

which is weird as I have no call to Pandas anywhere

Also I have tried:

    df = df.assign(col3 = None)

    return     df.col3.mask(df.category== 'A', params['column1']) \
                .mask(df.category == 'B' , params['column2'])\
                .mask(df.category == 'C', params['column3'])

In the second case, the returned dataframe has all nan values.

I have also already set 'compute.ops_on_diff_frames' to True

Body:
I found a work-around to this issue, but I am still not clear on the why.

In my case I am making two steps. The first is to reset index of the filtered parameter dataframe.

params = orig_params.loc[*whatever filtering may fit here*].reset_index()

Secondly, just use the filtered element that we want. If not using this step, the masking will require you to input a series as long as required. Here, we just convert it into a scalar, like:

    temp = df.category
    temp = temp.mask(temp == 'A', params['column1'][0]) \
      .mask(temp == 'B' , params['column2'][0])\
      .mask(temp == 'C', params['column3'][0])
    df1 = df.assign(col3 = temp)
    return df1

Hopefully this is useful.
If anybody has a better solution and/or explanation please post it.


问:
what is the meaning of the expression " x * Math.cos(angle) - y * Math.sin(angle)"?
The above expression was taken from the below method.
I know that to rotate a point around the center we have to

Move the point to the origin

Make the rotation and

Move the point back

But the pieces I don't get my head around are:

```<code>r[0] = x * Math.cos(angle) - y * Math.sin(angle);
                           ^
                           |
                          why we use the minus sign here?

r[1] = x * Math.sin(angle) + y * Math.cos(angle);
                           ^
                           |
                            And why here we use plus sign instead of minus?

Vec2.prototype.rotate = function (center, angle) {
//rotate in counterclockwise
var r = [];
var x = this.x - center.x;
var y = this.y - center.y;
r[0] = x * Math.cos(angle) - y * Math.sin(angle);
r[1] = x * Math.sin(angle) + y * Math.cos(angle);
r[0] += center.x;
r[1] += center.y;
return new Vec2(r[0], r[1]);
};
</code>```

The book was to be great but it doesn't explain most of the code it simply spits out.

答:
I got it! Just saw a video of Dr Peyam on transformation matrix.

To get x' and y'  we multiply the transformation matrix by the current coordinate (x,y)
enter image description here

Body:
The above expression was taken from the below method.
I know that to rotate a point around the center we have to

Move the point to the origin

Make the rotation and

Move the point back

But the pieces I don't get my head around are:

r[0] = x * Math.cos(angle) - y * Math.sin(angle);
                           ^
                           |
                          why we use the minus sign here?

r[1] = x * Math.sin(angle) + y * Math.cos(angle);
                           ^
                           |
                            And why here we use plus sign instead of minus?

Vec2.prototype.rotate = function (center, angle) {
//rotate in counterclockwise
var r = [];
var x = this.x - center.x;
var y = this.y - center.y;
r[0] = x * Math.cos(angle) - y * Math.sin(angle);
r[1] = x * Math.sin(angle) + y * Math.cos(angle);
r[0] += center.x;
r[1] += center.y;
return new Vec2(r[0], r[1]);
};

The book was to be great but it doesn't explain most of the code it simply spits out.


问:
Efficient way to get a matrix of high and low expressions for multiple variables to be used for simulations
I want to have a matrix including one high (1 sd above average) and low (1 sd below median) expression for each variable out of multiple variables.

In one variant, for each variable I would like to have one high expression, while all other variables are low.

In addition, I would like to have a variant in which all other variables are set to 0 and then there is a high and a low expression for each variable.

I want to use it for model predictions.

For three variables I would already need for variant 1:

```<code>pred_da <- data.frame(var1 = c(median(da$var1)+1*sd(da$var1), median(da$var1)-1*sd(da$var1), median(da$var1)-1*sd(da$var1)), var2 = c(median(da$var2)-1*sd(da$var2), median(da$var2)+1*sd(da$var2), median(da$var2)-1*sd(da$var2)), var3 = c(median(da$var3)-1*sd(da$var3), median(da$var3)-1*sd(da$var3), median(da$var3)+1*sd(da$var3)))
</code>```

For variant 2 it would be even more...

There should be a more efficient way to do it?

答:
It's a bit of a mind-squeezer with nonstandard eval, but I managed to get it to work with my example data:</p>

```<code>library(tidyverse)

da <- tibble(ID = 1:10, V1 = rnorm(10, 0, 1), V2 = rpois(10, 2), V3 = rexp(10, 1))

varnames <- colnames(da)[-1]

median_da <- da %>%
  select(- ID) %>%
  mutate_all(~ median(.x)) %>%
  slice(1)

sds <- da %>%
  select(- ID) %>%
  summarise_all(sd)

add_sd <- function(varname, sd) {

  median <- median_da %>%
    pluck(varname)

  median_low <- median_da %>%
    mutate(!!varname := median - sd)

  median_high <- median_da %>%
    mutate(!!varname := median + sd)

  median_low %>%
     bind_rows(median_high)

}

preds_da <- map2(varnames, sds, ~ add_sd(varname = .x, sd = .y)) %>% bind_rows()

</code>```

Body:
I want to have a matrix including one high (1 sd above average) and low (1 sd below median) expression for each variable out of multiple variables.

In one variant, for each variable I would like to have one high expression, while all other variables are low.

In addition, I would like to have a variant in which all other variables are set to 0 and then there is a high and a low expression for each variable.

I want to use it for model predictions.

For three variables I would already need for variant 1:

pred_da <- data.frame(var1 = c(median(da$var1)+1*sd(da$var1), median(da$var1)-1*sd(da$var1), median(da$var1)-1*sd(da$var1)), var2 = c(median(da$var2)-1*sd(da$var2), median(da$var2)+1*sd(da$var2), median(da$var2)-1*sd(da$var2)), var3 = c(median(da$var3)-1*sd(da$var3), median(da$var3)-1*sd(da$var3), median(da$var3)+1*sd(da$var3)))

For variant 2 it would be even more...

There should be a more efficient way to do it?

Body:
It's a bit of a mind-squeezer with nonstandard eval, but I managed to get it to work with my example data:

library(tidyverse)

da <- tibble(ID = 1:10, V1 = rnorm(10, 0, 1), V2 = rpois(10, 2), V3 = rexp(10, 1))

varnames <- colnames(da)[-1]

median_da <- da %>%
  select(- ID) %>%
  mutate_all(~ median(.x)) %>%
  slice(1)

sds <- da %>%
  select(- ID) %>%
  summarise_all(sd)

add_sd <- function(varname, sd) {

  median <- median_da %>%
    pluck(varname)

  median_low <- median_da %>%
    mutate(!!varname := median - sd)

  median_high <- median_da %>%
    mutate(!!varname := median + sd)

  median_low %>%
     bind_rows(median_high)

}

preds_da <- map2(varnames, sds, ~ add_sd(varname = .x, sd = .y)) %>% bind_rows()


问:
H2 Get row count for all tables
I would like to know the total number of rows for each table. And that for all tables at once. Is this possible with H2?

I'm thinking of a table:

```
|table name | row size |
```

At the moment I'm using the current version 1.3.170 (2012-11-30).

答: Try SELECT table_name, row_count_estimate FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'PUBLIC'. It will get you an "estimate", but chances are the results will get you the information you need.

Title: H2 Get row count for all tables

Body:
I would like to know the total number of rows for each table. And that for all tables at once. Is this possible with H2?

I'm thinking of a table:

|table name | row size |

At the moment I'm using the current version 1.3.170 (2012-11-30).


问:
Return count of rows on today's date grouped by the hour w/ 0's for hours with no count
I am trying to get the count of rows within a hour, starting with 12 am to the current hour. I currently am getting the last 24 hours easily, but am unsure how start the series with 2/17/2020 12:00 am up to the current time.

Here is what I have currently returning the last 24 hours where hours with no count return 0:

```<code>with hour_range as (
    select generate_series(date_trunc('hour', now() - interval '23 hours'), date_trunc('hour', now()), '1 hour':: interval) as hour
),

hour_count as (
    select date_trunc('hour', local_start_time) as hour,
        count (*) as ct
    from call_data.rc_api_call_logs
    where local_start_time::date = current_date -- today
    and br_call_flag = 1
    group by 1
)

select to_char(hour_range.hour, 'Mon DD YYYY HH12:MI:SSam'),
       coalesce(hour_count.ct, 0)
from hour_range
left outer join hour_count on hour_range.hour = hour_count.hour;
</code>```

Also I am just reformatting military time to normal time in my last select for readability. The local_start_time is of timestamp type. The issue is really with the generate_series query, and fixing the start time since I am using it to join to get the hours with count 0.

EDIT: Any suggestions for performance will be helpful, otherwise I will accept my answer.

答:
You don't need to subtract any interval to get start of range. Just use date_trunc('day',now()). This truncates the time component to "00:00:00". </p>

```<code> with hour_range as (
    select generate_series(date_trunc('day', now() ), date_trunc('hour', now()), '1 hour':: interval) as hour
)
select * from hour_range
</code>```

Body:
I am trying to get the count of rows within a hour, starting with 12 am to the current hour. I currently am getting the last 24 hours easily, but am unsure how start the series with 2/17/2020 12:00 am up to the current time.

Here is what I have currently returning the last 24 hours where hours with no count return 0:

with hour_range as (
    select generate_series(date_trunc('hour', now() - interval '23 hours'), date_trunc('hour', now()), '1 hour':: interval) as hour
),

hour_count as (
    select date_trunc('hour', local_start_time) as hour,
        count (*) as ct
    from call_data.rc_api_call_logs
    where local_start_time::date = current_date -- today
    and br_call_flag = 1
    group by 1
)

select to_char(hour_range.hour, 'Mon DD YYYY HH12:MI:SSam'),
       coalesce(hour_count.ct, 0)
from hour_range
left outer join hour_count on hour_range.hour = hour_count.hour;

Also I am just reformatting military time to normal time in my last select for readability. The local_start_time is of timestamp type. The issue is really with the generate_series query, and fixing the start time since I am using it to join to get the hours with count 0.

EDIT: Any suggestions for performance will be helpful, otherwise I will accept my answer.

Body:
You don't need to subtract any interval to get start of range. Just use date_trunc('day',now()). This truncates the time component to "00:00:00".

 with hour_range as (
    select generate_series(date_trunc('day', now() ), date_trunc('hour', now()), '1 hour':: interval) as hour
)
select * from hour_range


答:
You can use this, but its better to use with Ids:

const email = document.getElementsByClassName('email')[0];
const form = document.getElementsByClassName('form')[0];
const emailMessage = document.getElementsByClassName('empty-email-message')[0];
const errorEmail = document.getElementsByClassName('invalid-email-message')[0];

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    emailMessage.innerHTML = 'where is the email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form" id="form" action="submit">
            <input class="email" type="email"/>
            <button type="submit">Go</button>
            <!-- dont use id -->
            <p class="empty-email-message"></p>
            <p class="invalid-email-message"></p>
          </form></code>```

Title: Using classes breaks my code by IDs don't

Body:
When I use IDs in my HTML and select them in my javascript code with the getElementByID, my code works, but when I change them to classes my code does not work anymore.

I would like to use classes because I am working on a project with someone else who prefers classes.

Also, does it make a difference using classes vs IDs for javascript code?

const email = document.getElementsByClassName('email');
const form = document.getElementsByClassName('form');
const emailMessage = document.getElementsByClassName('empty-email-message');
const errorEmail = document.getElementsByClassName('invalid-email-message');

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    emailMessage.innerHTML = 'where is the email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});

<form class="form" id="form" action="submit">
            <input class="email" type="email"/>
            <button type="submit">Go</button>

          </form>

const email = document.getElementById('email');
const form = document.getElementById('form');
const emailMessage = document.getElementById('empty-email-message');
const errorEmail = document.getElementById('invalid-email-message');

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    emailMessage.innerHTML = 'where is the email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});

<form class="form" id="form" action="submit">
            <input id="email" type="email"/>
            <button type="submit">Go</button>

          </form>

Body:
You can use this, but its better to use with Ids:

const email = document.getElementsByClassName('email')[0];
const form = document.getElementsByClassName('form')[0];
const emailMessage = document.getElementsByClassName('empty-email-message')[0];
const errorEmail = document.getElementsByClassName('invalid-email-message')[0];

form.addEventListener('submit', e => {
  if (!email.value) {
    e.preventDefault();
    emailMessage.innerHTML = 'where is the email';
  } else {
    emailMessage.innerHTML = '';
    // return true;
  }
});

<form class="form" id="form" action="submit">
            <input class="email" type="email"/>
            <button type="submit">Go</button>
            <!-- dont use id -->
            <p class="empty-email-message"></p>
            <p class="invalid-email-message"></p>
          </form>


问:
How should I do the classification of images with different orientation?
I have been working on a dataset in which the goal is to determine that which type of orientation is it. It is a classification problem in which for each record(for most of them) I am having 4 images - front facing, left facing, right facing and back facing product images.
I want to classify these images in the above 4 categories.
The dataset looks like this :

I have downloaded the images and put them in different folders according to their classes.

Methods I have applied:

Till now I have applied two methods to classify these images.

1) I have tried vgg16 directly to classify the images but it did not give me even 50% accuracy.

2) I converted those images into edge images with black background as:

This is done using canny edge detection. It was done because in the result I was getting images with similar color dresses, similar design dresses, etc.
On top of these I again applied vgg16, resnet50, inception models but nothing seemed to work.

Can you suggest some ideas that can work in my case and classify the images in a better way.

答: first of all yor data set has to be equally splited. For instance 80% train and 20% test. After that you have to balance these sets (train set 60% of class A images, 40% of class B images) the exact same for test set. </p>


问:
how to crop a zoomed image using jquery
I have to make a customized avatar in which i need to zoom image and crop that using jquery
i found many plugins for zooming and cropping separately but precisely none for both . the server side i use is PHP.

答:
I use Jcrop to crop it. It allows you to set a marquee at a certain aspect ratio and see a live preview in another div (the preview is zoomed in if you're working with an image big enough to support the zooming).

It has several examples and also a script for PHP cropping on the back end and it also handles converting the hi-res cropped image to the correct size thumbnail.

Title: how to crop a zoomed image using jquery


问:
Not being able to pass values into database from eloquent relationships in laravel 6
I am working on my first laravel project, which is a library application.
I am now working on a form to create a book, and I had to create many eloquent relationships here. I created the relationship languages to books, which was easy, because one book can only have one language (in this case), but one language can be used for several books.
The problem I am facing now is, that I want to be able to select the genres as well on the form, so I connected the genres table with my book table with a belongsToMany relationship and of course I have also created a pivot table.
Now, I think that the problem has to be in my BookController's store function, but I just can't figure out what it is.

Here is some of my code: (sorry if I'm missing something this is my first time asking a question here)

My BookController's store function:

```<code>public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'author_id' => 'required',
            'year' => 'required|numeric',
            'publisher_id' => 'required',
            'genres' => 'exists:genres,id',
            'language_id' => 'required',
            'isbn' => 'required|numeric',
            'pages' => 'required|numeric',
        ]);

        $book = Book::create($validatedData);
        $book->genres()->attach(request('genre_id'));

        return redirect('books')->with('success', 'Book was added!');
    }
</code>```

If I submit my form right now I get this message:

SQLSTATE[HY000]: General error: 1364 Field 'genre_id' doesn't have a default value (SQL: insert into books (title, author_id, year, publisher_id, language_id, isbn, pages, updated_at, created_at) values (Spanish for cats, 1, 1994, 1, 1, 1234567891128, 2337, 2020-02-17 16:37:07, 2020-02-17 16:37:07))
my create.blade.php

```<code><div class="form-group">
                <label for="genre_id">Genre(s):</label>
                @foreach($genres as $genre)
                <input type="checkbox" name="genre_id[]" value="{{ $genre->id }}">{{ $genre->name }}
                @endforeach
                </select>
                @error('genre_id')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>
</code>```

The value of the genres show up in my form, but I can't seem to input them into my database.

Any help would be highly appreciated!

答:
First from your example I cannot be sure whether you intend to pass a
  single genre via the request data or an array of genres as using the word genres leads me to believe that there could be more than one genre but the validation key is singular, use genres.* if you intend to pass an array of genre_id values.

This is one of the downsides to Laravel's magic methods, since you are requesting $book->genres()->attach(request('genre_id')) and request('genre_id') does not appear to exist in your validation you will find that you are actually passing a null value like so $book->genres()->attach(null) which is causing the error.

To resolve this issue you should change the ->attach() call to  $book->genres()->attach($validatedData['genres']) which will ensure that you are passing your validated data to the attach method.

Body:
I am working on my first laravel project, which is a library application.
I am now working on a form to create a book, and I had to create many eloquent relationships here. I created the relationship languages to books, which was easy, because one book can only have one language (in this case), but one language can be used for several books.
The problem I am facing now is, that I want to be able to select the genres as well on the form, so I connected the genres table with my book table with a belongsToMany relationship and of course I have also created a pivot table.
Now, I think that the problem has to be in my BookController's store function, but I just can't figure out what it is.

Here is some of my code: (sorry if I'm missing something this is my first time asking a question here)

My BookController's store function:

public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'author_id' => 'required',
            'year' => 'required|numeric',
            'publisher_id' => 'required',
            'genres' => 'exists:genres,id',
            'language_id' => 'required',
            'isbn' => 'required|numeric',
            'pages' => 'required|numeric',
        ]);

        $book = Book::create($validatedData);
        $book->genres()->attach(request('genre_id'));

        return redirect('books')->with('success', 'Book was added!');
    }

If I submit my form right now I get this message:

SQLSTATE[HY000]: General error: 1364 Field 'genre_id' doesn't have a default value (SQL: insert into books (title, author_id, year, publisher_id, language_id, isbn, pages, updated_at, created_at) values (Spanish for cats, 1, 1994, 1, 1, 1234567891128, 2337, 2020-02-17 16:37:07, 2020-02-17 16:37:07))
my create.blade.php

                Genre(s):
                @foreach($genres as $genre)
                <input type="checkbox" name="genre_id[]" value="{{ $genre->id }}">{{ $genre->name }}
                @endforeach
                </select>
                @error('genre_id')

{{ $message }}

                @enderror

The value of the genres show up in my form, but I can't seem to input them into my database.

Any help would be highly appreciated!