问:
FormData() object is empty in console during POST
this question has been asked before but I couldn't find the answer in another question. when I log my formdata I just get {} i am sending two items that are text and one image file from my client html using fetch

my form

 <form id="addform">

        post
        <input type="text" class="form-control" id="title" placeholder="article title">
        <textarea type="text" class="form-control bigbox" id="body" placeholder=""></textarea>

        <input type="file" id="image" placeholder="image" name="imageFile">

      <button id="addpost" type="submit"class="btn btn-primary">add Post</button>
    </form>
```

<p>postdata function</p>

<pre class="lang-js prettyprint-override"><code> async function postData(url = '', data) {

  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'no-cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default , no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      //'Content-Type': 'application/json'
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}
</code>```

sending the request with a form object

document.getElementById("addpost").addEventListener('click',function(e){
      e.preventDefault()
      let form = document.getElementById('addform')
      let formdata = new FormData(form)
      formdata.append('title',document.getElementById("title").value)
      formdata.append('body',document.getElementById("body").value)
      formdata.append('imageFile',document.getElementById("image").files[0])

      postData(`http://${window.location.hostname}:3000/admin/addpost`,formdata)
      .then((data)=>{console.log(data.data)})
    })
```

<p>what i get in my XHR preview in chrome</p>

```{}
```

I'm not sure why this is happening it just seems to not be grabbing the form values at all

答:
Don't stringify your FormData, send it directly, and don't set the request headers, let the browser handle that too:

```<code>  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'no-cors', // you probably don't want this... let the default "cors"
    cache: 'no-cache', // not sure why you'd want that either...
    credentials: 'same-origin', // include, *same-origin, omit
// removed the Headers, the browser knows how to talk to a server, that's hos job.
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: data // pass directly the FormData here
  });
</code>```

And note that you don't have to, and probably even shouldn't set all the options of the fetch, just use the defaults, in 99% of cases that's what you need.

Body:
this question has been asked before but I couldn't find the answer in another question. when I log my formdata I just get {} i am sending two items that are text and one image file from my client html using fetch

my form

 <form id="addform">

        post
        <input type="text" class="form-control" id="title" placeholder="article title">
        <textarea type="text" class="form-control bigbox" id="body" placeholder=""></textarea>

        <input type="file" id="image" placeholder="image" name="imageFile">

      <button id="addpost" type="submit"class="btn btn-primary">add Post</button>
    </form>

postdata function

 async function postData(url = '', data) {

  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'no-cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default , no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      //'Content-Type': 'application/json'
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

sending the request with a form object

document.getElementById("addpost").addEventListener('click',function(e){
      e.preventDefault()
      let form = document.getElementById('addform')
      let formdata = new FormData(form)
      formdata.append('title',document.getElementById("title").value)
      formdata.append('body',document.getElementById("body").value)
      formdata.append('imageFile',document.getElementById("image").files[0])

      postData(`http://${window.location.hostname}:3000/admin/addpost`,formdata)
      .then((data)=>{console.log(data.data)})
    })

what i get in my XHR preview in chrome

{}

I'm not sure why this is happening it just seems to not be grabbing the form values at all

Body:
Don't stringify your FormData, send it directly, and don't set the request headers, let the browser handle that too:

  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'no-cors', // you probably don't want this... let the default "cors"
    cache: 'no-cache', // not sure why you'd want that either...
    credentials: 'same-origin', // include, *same-origin, omit
// removed the Headers, the browser knows how to talk to a server, that's hos job.
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: data // pass directly the FormData here
  });

And note that you don't have to, and probably even shouldn't set all the options of the fetch, just use the defaults, in 99% of cases that's what you need.


来源: stackexchange

问:
Revisited: How to launch a KDE konsole with multiple tabs running various progs?
As the title strongly suggests, I have already read How to launch a KDE konsole with multiple tabs running various progs?, and the answer is just what I need - except, I want to set the remote title, and I don't find any options for that. I can see elsewhere that it should be possible to do from the command line, but I'd rather use this config-file method, if possible. Is there an option for that?</p>

答:
This works for me cmd;
konsole  --tabs-from-file `/settings/s-tab-file

cat /settings/s-tab-file

```<code>title: Pay6 1 ;; command: ~/bin/pay_index    # scripts that call functions
title: Sal6 2 ;; command: ~/bin/sales_index #  <---[ scripts fails unless contains    #! /bin/sh  ]---
title: Led6 3 ;; command: ~/bin/ledger_index
</code>```

above is 3 separate lines, i  had to put a space line because post
turned them into one long line.

worked great right up to kubuntu 18.04  3 konsole tabs as expected
problem I'm having now is Kubuntu 20.04 is giving me a 4th trailing empty konsole
that looks stupid and has to be removed to look proper.

ContentLicense: CC BY-SA 4.0

Body:
This works for me cmd;
konsole  --tabs-from-file `/settings/s-tab-file

cat /settings/s-tab-file

title: Pay6 1 ;; command: ~/bin/pay_index    # scripts that call functions
title: Sal6 2 ;; command: ~/bin/sales_index #  <---[ scripts fails unless contains    #! /bin/sh  ]---
title: Led6 3 ;; command: ~/bin/ledger_index

above is 3 separate lines, i  had to put a space line because post
turned them into one long line.

worked great right up to kubuntu 18.04  3 konsole tabs as expected
problem I'm having now is Kubuntu 20.04 is giving me a 4th trailing empty konsole
that looks stupid and has to be removed to look proper.


问:
Increment hex string
I'm trying to increment an hex string like this:

```
#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;
```

Here's my procedure:

```<code>var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;
</code>```

Whith this procedure, only the second byte increment.
The result is:

```
#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1
```

Thanks

答:
Warning, not a Delphi expert

Don't do string manipulation and don't use an array of integers.

What you want is to increment a number, so do that!  A hex number represents a single integer, not an array of integers.

Convert Hex String to Integer

Increment Integer

Convert Integer to Hex String

Don't complain to me that this is inefficient, it is correct, simple and obvious.  That's how code should be.

And if your hex string is too large to fit in an integer, then go ahead and use an array of integers, just make sure to encapsulate that so it looks like your dealing with one type.  You can then test this array of integer type separately

ContentLicense: CC BY-SA 2.5

Title: Increment hex string

Body:
I'm trying to increment an hex string like this:

#$67#$1c#$87#$b1;
#$67#$1c#$87#$b2;
#$67#$1c#$87#$b3;

Here's my procedure:

var test : array [0..3] of char; intSequence : cardinal;

Sequence := #$67#$1c#$87#$b1;

procedure IncSequence;
begin
  move(Sequence[1],intSequence,SizeOF(Sequence));
  inc(intSequence);
  move(intSequence,Sequence[1],SizeOf(test));
end;

Whith this procedure, only the second byte increment.
The result is:

#$67#$1D#$87#$B1
#$67#$1E#$87#$B1
#$67#$1F#$87#$B1

Thanks

LastEditorDisplayName: Tomalak

OwnerDisplayName: Pyrolistical


问:
Sort string and number combination in descending in oralce
I am trying to sort a combination of string and number in descending order .

Input :

```<code>P9S1
P7S1
P13S1
P12S2
P10S1
</code>```

Expected output:

```<code>P13S1
P12S2
P10S1
P9S1
P7S1
</code>```

Here is what I tried

Sample code:

```<code>  with
      inputs (firmware) as (
        select 'P9S1'  from dual union all
        select 'P7S1' from dual union all
        select 'P13S1' from dual union all
        select 'P12S2' from dual union all
        select 'P10S1'      from dual
      )
    select firmware
    from   inputs
    order by
    regexp_replace(firmware, '\d+\.\d+') desc ;
</code>```

But this doesn't work as expected. Any help would be appreciated.

Thanks

答:
You did not actually explain how the strings should turned to numbers.

This would work for your dataset:

```<code>order by to_number(regexp_replace(firmware, '\D', '')) desc
</code>```

The idea is to remove all non-digits characters from the string, turn the resulting string to a number, and use it for sorting.

```<code>with inputs (firmware) as (
    select 'P9S1' from dual union all
    select 'P7S1' from dual union all
    select 'P13S1' from dual union all
    select 'P12S2' from dual union all
    select 'P10S1' from dual
)
select firmware
from   inputs
order by to_number(regexp_replace(firmware, '\D', '')) desc ;
</code>```

```
| FIRMWARE |
| :------- |
| P13S1    |
| P12S2    |
| P10S1    |
| P9S1     |
| P7S1     |
```

Body:
I am trying to sort a combination of string and number in descending order .

Input :

P9S1
P7S1
P13S1
P12S2
P10S1

Expected output:

P13S1
P12S2
P10S1
P9S1
P7S1

Here is what I tried

Sample code:

  with
      inputs (firmware) as (
        select 'P9S1'  from dual union all
        select 'P7S1' from dual union all
        select 'P13S1' from dual union all
        select 'P12S2' from dual union all
        select 'P10S1'      from dual
      )
    select firmware
    from   inputs
    order by
    regexp_replace(firmware, '\d+\.\d+') desc ;

But this doesn't work as expected. Any help would be appreciated.

Thanks

Body:
You did not actually explain how the strings should turned to numbers.

This would work for your dataset:

order by to_number(regexp_replace(firmware, '\D', '')) desc

The idea is to remove all non-digits characters from the string, turn the resulting string to a number, and use it for sorting.

with inputs (firmware) as (
    select 'P9S1' from dual union all
    select 'P7S1' from dual union all
    select 'P13S1' from dual union all
    select 'P12S2' from dual union all
    select 'P10S1' from dual
)
select firmware
from   inputs
order by to_number(regexp_replace(firmware, '\D', '')) desc ;

| FIRMWARE |
| :------- |
| P13S1    |
| P12S2    |
| P10S1    |
| P9S1     |
| P7S1     |


问:
How to count chars in a word?
Basically i'm trying to write function that takes GGHTTYYYD and returns 2GH2T3YD. Notice that numbers going first. I'm trying to write it in javascrript. How this can be done?
Basically here i s my code:

```<code>let s = 'GGHTTYYYD';

const count = (str) => {
  let hash = {};
  str.split('').forEach((char) => {
    hash[char] = hash[char] ? (hash[char] += 1) : 1;
  });
  return hash
};
</code>```

now i stuck at converting object named hash to string and filter all "1"

答:
It is a python implementation but I think it is straight-forward. I hope it helps!</p>

```<code>def func(st):
# string to be formed
new_st = ""
# current character
curr_char = st[0]
# current character repeat count
curr_char_times = 1
for char in st[1:]:
    # character changed
    if char != curr_char:
        # if times is 1 do not write 1
        if curr_char_times == 1:
            new_st += curr_char
        else:
            new_st += str(curr_char_times)+curr_char
        # return back to initial state
        curr_char = char
        curr_char_times = 1
    else:
        # if character not changed increment times
        curr_char_times += 1
# process the last char
if curr_char_times == 1:
    new_st += curr_char
else:
    new_st += str(curr_char_times)+curr_char
return new_st
</code>```

Title: How to count chars in a word?

Body:
Basically i'm trying to write function that takes GGHTTYYYD and returns 2GH2T3YD. Notice that numbers going first. I'm trying to write it in javascrript. How this can be done?
Basically here i s my code:

let s = 'GGHTTYYYD';

const count = (str) => {
  let hash = {};
  str.split('').forEach((char) => {
    hash[char] = hash[char] ? (hash[char] += 1) : 1;
  });
  return hash
};

now i stuck at converting object named hash to string and filter all "1"

Body:
It is a python implementation but I think it is straight-forward. I hope it helps!

def func(st):
# string to be formed
new_st = ""
# current character
curr_char = st[0]
# current character repeat count
curr_char_times = 1
for char in st[1:]:
    # character changed
    if char != curr_char:
        # if times is 1 do not write 1
        if curr_char_times == 1:
            new_st += curr_char
        else:
            new_st += str(curr_char_times)+curr_char
        # return back to initial state
        curr_char = char
        curr_char_times = 1
    else:
        # if character not changed increment times
        curr_char_times += 1
# process the last char
if curr_char_times == 1:
    new_st += curr_char
else:
    new_st += str(curr_char_times)+curr_char
return new_st


问:
In Vue.js, is there a way to keep component templates out of JavaScript strings?
I just worked through the Guide on Vue.js's website, and I have a bad feeling about templates for components.  It seems strange to me that they are specified in strings; sure, maybe this works for very short templates, but once you get to multiline templates, you need to start escaping your new lines and it just feels wrong to have html in javascript strings to begin with.  Not to mention that syntax highlighting or any other nice IDE features are useless with HTML in JS strings.

Two alternatives that are detailed in the docs are using inline templates, or X-templates, but both of these options are discouraged.

The only other alternative seems to be Single File Components, which seems like a good option, but they are in the Advanced section and in the docs, it is said that for small and medium sized apps, simply using Vue.component should be enough.  Furthermore, Single File Components look like they're more difficult to integrate into a project, requiring tapping into the project's build system (the docs talk about Webpack and Browserify).

So I'm confused.  Do I just need to accept that my component code is going to look as messy as this example, pulled straight from the docs?

```<code>Vue.component('currency-input', {
  template: '\
    <span>\
      $\
      <input\
        ref="input"\
        v-bind:value="value"\
        v-on:input="updateValue($event.target.value)"\
      >\
    </span>\
  ',
......
</code>```

答:
Thanks to @danidee answer I was able to track an Atom extension to properly do syntax highlighting for "backticked" HTML strings. However as he indicates it will only work when the template is declared inside the very component definition (and I want to separate template in another .js file). So I did this and it's a more ellegant solution, I think:

COMPONENT DEFINITION

```<code>/* template definition */
import { csFooterView } from './csfooter-view.js?v6';

/* component definition */
const csfooter = {
  name: 'csfooter',
  props: ['projectName'],
  data: function() {
      return {
          copyrightCompany: 'CSDev'
      }
  },
  template: csFooterView.template
};

/* exports */
export { csfooter };
</code>```

TEMPLATE DEFINITION

```<code>/**
 * VUE Footer Component
 * Template
 */

 /* template definition */
 const csFooterView = {
   template: `
    <footer class="footer bg-warning p-4 m-auto">
      <p>{{ copyrightCompany }} (c) 2020 - {{ projectName }}</p>
    </footer>
   `
 };

 export { csFooterView }
</code>```

ATOM SCREENSHOT WITH HTML SYNTAX HIGHLIGHTING IN THE .JS FILE

Link to Atom extension

Body:
I just worked through the Guide on Vue.js's website, and I have a bad feeling about templates for components.  It seems strange to me that they are specified in strings; sure, maybe this works for very short templates, but once you get to multiline templates, you need to start escaping your new lines and it just feels wrong to have html in javascript strings to begin with.  Not to mention that syntax highlighting or any other nice IDE features are useless with HTML in JS strings.

Two alternatives that are detailed in the docs are using inline templates, or X-templates, but both of these options are discouraged.

The only other alternative seems to be Single File Components, which seems like a good option, but they are in the Advanced section and in the docs, it is said that for small and medium sized apps, simply using Vue.component should be enough.  Furthermore, Single File Components look like they're more difficult to integrate into a project, requiring tapping into the project's build system (the docs talk about Webpack and Browserify).

So I'm confused.  Do I just need to accept that my component code is going to look as messy as this example, pulled straight from the docs?

Vue.component('currency-input', {
  template: '\
    \
      $\
      <input\
        ref="input"\
        v-bind:value="value"\
        v-on:input="updateValue($event.target.value)"\
      >\
    \
  ',
......

Body:
Thanks to @danidee answer I was able to track an Atom extension to properly do syntax highlighting for "backticked" HTML strings. However as he indicates it will only work when the template is declared inside the very component definition (and I want to separate template in another .js file). So I did this and it's a more ellegant solution, I think:

COMPONENT DEFINITION

/* template definition */
import { csFooterView } from './csfooter-view.js?v6';

/* component definition */
const csfooter = {
  name: 'csfooter',
  props: ['projectName'],
  data: function() {
      return {
          copyrightCompany: 'CSDev'
      }
  },
  template: csFooterView.template
};

/* exports */
export { csfooter };

TEMPLATE DEFINITION

/**
 * VUE Footer Component
 * Template
 */

 /* template definition */
 const csFooterView = {
   template: `
    <footer class="footer bg-warning p-4 m-auto">
      <p>{{ copyrightCompany }} (c) 2020 - {{ projectName }}</p>
    </footer>
   `
 };

 export { csFooterView }

ATOM SCREENSHOT WITH HTML SYNTAX HIGHLIGHTING IN THE .JS FILE

Link to Atom extension


问:
PostgreSQL Match any strings
I have a SQL query:

```<code>select recipe_title
             from recipe where
             meal_type ='BREAKFAST'
</code>```

Is it possible to match any meal_type by only change the BREAKFAST?

```<code>Such as:
    select recipe_title
                 from recipe where
                 meal_type = *
</code>```

I know I can use like %% but that will need to change many places in my code. Is it possible to get all  meal_type and still use =

Thanks!

答: No. = is an equality operator. The best you can do is WHERE meal_type = ANY('{BREAKFAST,LUNCH,DINNER}'), iff you have a known short list of all possible values, but there's no wildcard-like behavior with =. The correct way of doing this (returning all rows regardless of meal_type) is to not have a meal_type = <whatever> in your WHERE clause.

Title: PostgreSQL Match any strings

Body:
I have a SQL query:

select recipe_title
             from recipe where
             meal_type ='BREAKFAST'

Is it possible to match any meal_type by only change the BREAKFAST?

Such as:
    select recipe_title
                 from recipe where
                 meal_type = *

I know I can use like %% but that will need to change many places in my code. Is it possible to get all  meal_type and still use =

Thanks!


问:
Create a vector footprint of a multi-part raster [R]
I've read a raster into my R session, using this code:

raster <- stack("raster.tif")

and now I'd like to make a simple feature (sf) object representing the outline of that raster. I can't use a bounding box because the raster is multi-part so the bounding box would be much larger than the raster. So the footprint also needs to be a multi-part feature (sf multipolygon).

I'd appreciate any help with this. Thanks!

Mark

答:
If you want each raster in the stack you need to loop over each one with lapply. This will return a list of polygon layers. You then need to convert each component of the list to an sf multipolygon. Lastly, you need to concatenate the features (note that c is the c() function). shp should be your multipolygon. You may not want to dissolve the polygons, you didn't really make it clear what you wanted.

```<code>a <- lapply(as.list(raster), rasterToPolygons, dissolve=TRUE)
b <- lapply(a, st_as_sf) # convert to sf multipolygon
shp <- Reduce(c, b) # combine all polygons to one
</code>```

As a side note, it's probably not great to use raster as a variable name because the raster package has a function called raster.

Body:
If you want each raster in the stack you need to loop over each one with lapply. This will return a list of polygon layers. You then need to convert each component of the list to an sf multipolygon. Lastly, you need to concatenate the features (note that c is the c() function). shp should be your multipolygon. You may not want to dissolve the polygons, you didn't really make it clear what you wanted.

a <- lapply(as.list(raster), rasterToPolygons, dissolve=TRUE)
b <- lapply(a, st_as_sf) # convert to sf multipolygon
shp <- Reduce(c, b) # combine all polygons to one

As a side note, it's probably not great to use raster as a variable name because the raster package has a function called raster.


问:
HTML Canvas javascript move object on Z axis
I am trying to make a 3D like effect in HTML Canvas. I want to have the effect of a 2D object coming towards the first person view. Is there a way to make it look like a rectangle is moving on the Z axis?

This is my code. I sort of have what I want but it does not really look natural.

Use the up arrow key to move the object. You can also use the left and right arrow keys to move it to the left and right.

I am trying to make a game similar to this game: http://game.notch.net/christmaschopping/

var canvas = document.getElementById('canv');
var c = canvas.getContext('2d');

window.onload = function() {
    start();
    setInterval(update, 10);
}

class Obstacle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.w = 30;
        this.h = 60;
        this.xSpeed = 0;
        this.ySpeed = 0;
        this.passedView = false;
        this.zSpeed = 0;
    }
    show() {
        if (!this.passedView) {
            c.fillStyle = 'green';
            c.fillRect(this.x, this.y, this.w, this.h);
        }
    }
    update() {
        this.x += this.xSpeed;
        this.y += this.ySpeed;

        this.w+=this.zSpeed;
        this.h+=this.zSpeed;
        this.x-=this.zSpeed/2;
        this.y-=this.zSpeed/2;
    }
}

var ob;

function start() {
    ob = new Obstacle(385, 370);
}

function update() {
    //background
    c.fillStyle = 'lightblue';
    c.fillRect(0, 0, 800, 800);
    //obstacle
    ob.show();
    ob.update();
}

function keyDown(e) {
    switch(e.keyCode) {
        case 39:
            ob.xSpeed = 5;
            break;
        case 37:
            ob.xSpeed = -5;
            break;
        case 38:
            ob.zSpeed = 5;
            break;
    }
}

function keyUp(e) {
    switch(e.keyCode) {
        case 39:
            ob.xSpeed = 0;
            break;
        case 37:
            ob.xSpeed = 0;
            break;
        case 38:
            ob.zSpeed = 0;
            break;
    }
}

document.onkeydown = keyDown;
document.onkeyup = keyUp;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id='canv' width=800 height=800></canvas>
<script src="main.js"></script></code>```

答:
its hard to perceive 3D looking a one object so give yourself several objects moving independently ... let the objects move on their own

I suggest you introduce the notion of perspective projection ... its why objects moving away get smaller

to keep it simple assign objects a size then scale that size using their Z dimension location

in addition to giving each object a location in 3d ( x,y,z ) put all of them inside a world say the inside of a cube or a sphere

launch each new object in some random direction at a random speed, random size

put all objects into some datastructure so you have an array you can iterate across to do things to each object

introduce the notion of time into this world ... iterate across the datastructure of your objects and perform actions as in

gently move the x,y,z location of the current object just a tiny bit in each dim ... keep tract of the sign ( pos/neg ) of each increment in each dimension

if the current x or y or z goes outside the interior of the cube or sphere then toggle the sign of the increment for that dimension as mentioned above

when you draw a given object scale its size based on its Z dimension ... this is perspective projection

```<code>object_rendered_size = object_constant_size * Z dimension for this object
</code>```

advance the clock to the next epoch ... put above loop inside an outer loop so everything keeps moving all the time

And yes this will give you 3D ... no need to jump straight into WebGL until after projects like this just code themselves ...  with today's hardware you can go very far using your current approach of using canvas ... teach yourself linear algebra to manipulate object or camera location using matrix mechanics

have Fun !!!

Body:
I am trying to make a 3D like effect in HTML Canvas. I want to have the effect of a 2D object coming towards the first person view. Is there a way to make it look like a rectangle is moving on the Z axis?

This is my code. I sort of have what I want but it does not really look natural.

Use the up arrow key to move the object. You can also use the left and right arrow keys to move it to the left and right.

I am trying to make a game similar to this game: http://game.notch.net/christmaschopping/

var canvas = document.getElementById('canv');
var c = canvas.getContext('2d');

window.onload = function() {
    start();
    setInterval(update, 10);
}

class Obstacle {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.w = 30;
        this.h = 60;
        this.xSpeed = 0;
        this.ySpeed = 0;
        this.passedView = false;
        this.zSpeed = 0;
    }
    show() {
        if (!this.passedView) {
            c.fillStyle = 'green';
            c.fillRect(this.x, this.y, this.w, this.h);
        }
    }
    update() {
        this.x += this.xSpeed;
        this.y += this.ySpeed;

        this.w+=this.zSpeed;
        this.h+=this.zSpeed;
        this.x-=this.zSpeed/2;
        this.y-=this.zSpeed/2;
    }
}

var ob;

function start() {
    ob = new Obstacle(385, 370);
}

function update() {
    //background
    c.fillStyle = 'lightblue';
    c.fillRect(0, 0, 800, 800);
    //obstacle
    ob.show();
    ob.update();
}

function keyDown(e) {
    switch(e.keyCode) {
        case 39:
            ob.xSpeed = 5;
            break;
        case 37:
            ob.xSpeed = -5;
            break;
        case 38:
            ob.zSpeed = 5;
            break;
    }
}

function keyUp(e) {
    switch(e.keyCode) {
        case 39:
            ob.xSpeed = 0;
            break;
        case 37:
            ob.xSpeed = 0;
            break;
        case 38:
            ob.zSpeed = 0;
            break;
    }
}

document.onkeydown = keyDown;
document.onkeyup = keyUp;

<canvas id='canv' width=800 height=800></canvas>

Body:
its hard to perceive 3D looking a one object so give yourself several objects moving independently ... let the objects move on their own

I suggest you introduce the notion of perspective projection ... its why objects moving away get smaller

to keep it simple assign objects a size then scale that size using their Z dimension location

in addition to giving each object a location in 3d ( x,y,z ) put all of them inside a world say the inside of a cube or a sphere

launch each new object in some random direction at a random speed, random size

put all objects into some datastructure so you have an array you can iterate across to do things to each object

introduce the notion of time into this world ... iterate across the datastructure of your objects and perform actions as in

gently move the x,y,z location of the current object just a tiny bit in each dim ... keep tract of the sign ( pos/neg ) of each increment in each dimension

if the current x or y or z goes outside the interior of the cube or sphere then toggle the sign of the increment for that dimension as mentioned above

when you draw a given object scale its size based on its Z dimension ... this is perspective projection

object_rendered_size = object_constant_size * Z dimension for this object

advance the clock to the next epoch ... put above loop inside an outer loop so everything keeps moving all the time

And yes this will give you 3D ... no need to jump straight into WebGL until after projects like this just code themselves ...  with today's hardware you can go very far using your current approach of using canvas ... teach yourself linear algebra to manipulate object or camera location using matrix mechanics

have Fun !!!


问:
Could someone please explain how the boolean in this code works?
This question is more to understand a portion of code I am working with.  The "valid" boolean in line 1 becomes a condition for the while statement in line 2.  When you put a boolean in a while condition, does that automatically change the boolean?  I don't understand how if valid is initialized to false, it would ever become true outside of the while loop -unless there is something about it being in the while condition?  I'm including a portion of the code so you can see what is happening.  This is part of a fraction calculator I'm trying to understand.

Thanks for your help!

```<code>boolean valid = false;
while (!valid) {
    System.out.println("Please enter a Fraction a/b or integer (a): ");
    firstFraction = scan.nextLine();
    valid = validFraction(firstFraction);
    if (valid) {
        int findSlash = firstFraction.indexOf("/");
        if (findSlash >= 0) {
            firstFractionNumerator = Integer.parseInt(firstFraction.substring(0, findSlash));
            firstFractionDenominator = Integer.parseInt(firstFraction.substring(findSlash + 1, firstFraction.length()));
        }
        else {
            firstFractionNumerator = Integer.parseInt(firstFraction.substring(0, firstFraction.length()));
            firstFractionDenominator = 1;
        }
    }
}
</code>```

答:
Just think about it conceptually. The goal is to get a valid fraction. Before you've asked the user, you don't have any fraction, so it's not valid. Then you ask the user and it could be either valid or invalid. If it is valid, you can quit the loop because you've succeeded, if it is invalid, you need to ask them again so you need to loop again.

Consider this simple example. We will continue the loop if we make a random number between 6-10, and quit if we pick a number 0-5

```<code>boolean shouldContinue = true;

while(shouldContinue) {
    shouldContinue = new Random().nextInt(10) > 5;
}
</code>```

Body:
This question is more to understand a portion of code I am working with.  The "valid" boolean in line 1 becomes a condition for the while statement in line 2.  When you put a boolean in a while condition, does that automatically change the boolean?  I don't understand how if valid is initialized to false, it would ever become true outside of the while loop -unless there is something about it being in the while condition?  I'm including a portion of the code so you can see what is happening.  This is part of a fraction calculator I'm trying to understand.

Thanks for your help!

boolean valid = false;
while (!valid) {
    System.out.println("Please enter a Fraction a/b or integer (a): ");
    firstFraction = scan.nextLine();
    valid = validFraction(firstFraction);
    if (valid) {
        int findSlash = firstFraction.indexOf("/");
        if (findSlash >= 0) {
            firstFractionNumerator = Integer.parseInt(firstFraction.substring(0, findSlash));
            firstFractionDenominator = Integer.parseInt(firstFraction.substring(findSlash + 1, firstFraction.length()));
        }
        else {
            firstFractionNumerator = Integer.parseInt(firstFraction.substring(0, firstFraction.length()));
            firstFractionDenominator = 1;
        }
    }
}

Body:
Just think about it conceptually. The goal is to get a valid fraction. Before you've asked the user, you don't have any fraction, so it's not valid. Then you ask the user and it could be either valid or invalid. If it is valid, you can quit the loop because you've succeeded, if it is invalid, you need to ask them again so you need to loop again.

Consider this simple example. We will continue the loop if we make a random number between 6-10, and quit if we pick a number 0-5

boolean shouldContinue = true;

while(shouldContinue) {
    shouldContinue = new Random().nextInt(10) > 5;
}


问:
pandas perform multiple transformations and creating a new data frame
I have a daframe where I want to perform multiple (independent) transformations, and they create a new data frame (with a multi-index), where each index correspond to one of the transformations.

More concretely:

```<code>df = pd.DataFrame([[1, "X", 'H', 100], [2, "Y", 'K', 100] ,[3, "X", 'H', 200], [4, "Y", 'H', 100]], columns=['id', 'XY', 'HK', 'A']).set_index("id")

    XY  HK  A
id
1   X   H   100
2   Y   K   100
3   X   H   200
4   Y   H   100
</code>```

I now want to know how many XY and how many HK have the same A. The final results should look like this (with multi-index):

```<code>     XY      HK
    X   Y   H   K
A
100 1.0 2.0 2.0 1.0
200 1.0 NaN 1.0 NaN
</code>```

This is what I was expecting to work:

```<code>df.groupby(['A', 'XY', 'HK']).count()
</code>```

but it only contains the multi index without the values.

What I was able to do is:

count the XY:

```<code>xy_count = df.groupby(['A', 'XY']).count().HK.unstack()
</code>```

count the HK:

```<code>hk_count = df.groupby(['A', 'HK']).count().XY.unstack()
</code>```

merge the results (?)

```<code>results = pd.DataFrame()
results['XY'] = xy_count
results['HK'] = hk_count
</code>```

but this last part does now work.

So my questions are:

Q1: There seems to be a better way I am missing
Q2: why does step 3 not work?

Not really a question, but also I find confusing that to get the HK, you have to call the XY column and vice versa.

答:
I will do melt first

```<code>s=df.melt('A').groupby(['A','variable']).value.value_counts().unstack([1,2])
variable   HK        XY
value       H    K    Y    X
A
100       2.0  1.0  2.0  1.0
200       1.0  NaN  NaN  1.0
</code>```

Body:
I have a daframe where I want to perform multiple (independent) transformations, and they create a new data frame (with a multi-index), where each index correspond to one of the transformations.

More concretely:

df = pd.DataFrame([[1, "X", 'H', 100], [2, "Y", 'K', 100] ,[3, "X", 'H', 200], [4, "Y", 'H', 100]], columns=['id', 'XY', 'HK', 'A']).set_index("id")

    XY  HK  A
id
1   X   H   100
2   Y   K   100
3   X   H   200
4   Y   H   100

I now want to know how many XY and how many HK have the same A. The final results should look like this (with multi-index):

     XY      HK
    X   Y   H   K
A
100 1.0 2.0 2.0 1.0
200 1.0 NaN 1.0 NaN

This is what I was expecting to work:

df.groupby(['A', 'XY', 'HK']).count()

but it only contains the multi index without the values.

What I was able to do is:

count the XY:

xy_count = df.groupby(['A', 'XY']).count().HK.unstack()

count the HK:

hk_count = df.groupby(['A', 'HK']).count().XY.unstack()

merge the results (?)

results = pd.DataFrame()
results['XY'] = xy_count
results['HK'] = hk_count

but this last part does now work.

So my questions are:

Q1: There seems to be a better way I am missing
Q2: why does step 3 not work?

Not really a question, but also I find confusing that to get the HK, you have to call the XY column and vice versa.

Body:
I will do melt first

s=df.melt('A').groupby(['A','variable']).value.value_counts().unstack([1,2])
variable   HK        XY
value       H    K    Y    X
A
100       2.0  1.0  2.0  1.0
200       1.0  NaN  NaN  1.0


问:
ios swift How to programmattically change background color of view on screen rotation?
This is part of a much bigger issue I  am having. I have simplified it for you. I want to programmatically change the background color of view on device orientation ?

The following code prints "landcape" and "portrait" in the debugging console every-tome I  rotate the device in the simulator :-

```<code>  import UIKit
  class OrientationViewController: UIViewController {
  override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        print("landscape")
    } else {
        print("portrait")
    }
  }
}
</code>```

Though the following code does nothing :-

```<code>   import UIKit
   class AskitViewController: UIViewController {
    override func viewDidLoad() {
    let landscapesmallview = UIView()
    landscapesmallview.backgroundColor = .orange
   let portraitsmallview = UIView()
    portraitsmallview.backgroundColor = .purple
    view.addSubview(landscapesmallview)
    view.addSubview(portraitsmallview)

 func viewWillTransition(to size: CGSize, with coordinator:      UIViewControllerTransitionCoordinator) {
     if UIDevice.current.orientation.isLandscape {
        print("landscape")
    landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
     portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
    } else {
        print("potrait")
  portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
  landscapesmallview.translatesAutoresizingMaskIntoConstraints = true
        }
       }
      }
     }
</code>```

I am using swift 4.2 and or 5, xcode 10.2
   So, how to programmatically change the background color of view every-time I rotate  the device ?

Please, any of you experts help me ?

edit 1:

I had told you'll in the beginning that it is a part of a bigger issue -

I have buttons inside a view which in potrait mode I want like this -

which is achieved by the following code -

//original potrait mode/////

```<code>    import UIKit
    class PotraitViewController: UIViewController {
    override func viewDidLoad() {
    let buttonred = UIButton()
    buttonred.backgroundColor = UIColor.red
    let buttonblue = UIButton()
    buttonblue.backgroundColor = UIColor.blue
    let landscapesmallview = UIView()
    view.addSubview(landscapesmallview)
    landscapesmallview.addSubview(buttonred)
    landscapesmallview.addSubview(buttonblue)
    buttonred.translatesAutoresizingMaskIntoConstraints = false
    buttonblue.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([

        buttonred.topAnchor.constraint(equalTo: view.topAnchor,constant: 200),
        buttonred.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        buttonred.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
        buttonred.widthAnchor.constraint(equalToConstant: 50),
        //-------
        buttonblue.topAnchor.constraint(equalTo: buttonred.bottomAnchor,constant: 40),
        buttonblue.leadingAnchor.constraint(equalTo: buttonred.leadingAnchor),
        buttonblue.trailingAnchor.constraint(equalTo:buttonred.trailingAnchor),
        buttonblue.widthAnchor.constraint(equalTo: buttonred.widthAnchor)

        ])
    }

 }
</code>```

and in landscape mode  I want like this -

which is achieved by the following code -

// original lanscape mode/////

```<code>  import UIKit
  class LandscapeViewController: UIViewController {
   override func viewDidLoad() {
    let buttonred = UIButton()
    buttonred.backgroundColor = UIColor.red
    let buttonblue = UIButton()
    buttonblue.backgroundColor = UIColor.blue
    view.addSubview(buttonred)
    view.addSubview(buttonblue)
    buttonred.translatesAutoresizingMaskIntoConstraints = false
    buttonblue.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([

        buttonred.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        buttonred.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:40),
        buttonred.trailingAnchor.constraint(equalTo: view.centerXAnchor,constant:-20),
        buttonred.widthAnchor.constraint(equalToConstant: 50),

        //-------
        buttonblue.centerYAnchor.constraint(equalTo: buttonred.centerYAnchor),
        buttonblue.leadingAnchor.constraint(equalTo: view.centerXAnchor,constant:40),
        buttonblue.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
        buttonblue.widthAnchor.constraint(equalTo:buttonred.widthAnchor)

        ])
     }

  }
</code>```

So, I tried the following code to achieve by screen rotation i.e. two different  layouts in potrait and landscape views programmatically with the help of the following code:-

```<code>    import UIKit

    class NewViewController: UIViewController {
    override func viewDidLoad() {
    let buttonredlandscape = UIButton()
    buttonredlandscape.backgroundColor = UIColor.red
    let buttonbluelandscape = UIButton()
    buttonbluelandscape.backgroundColor = UIColor.blue
    let buttonredportrait = UIButton()
    buttonredportrait.backgroundColor = UIColor.red
    let buttonblueportrait = UIButton()
    buttonblueportrait.backgroundColor = UIColor.blue

    let landscapesmallview = UIView()
    let portraitsmallview = UIView()
    landscapesmallview.backgroundColor = UIColor.gray
    portraitsmallview.backgroundColor = UIColor.purple
    landscapesmallview.frame = view.frame
    portraitsmallview.frame = view.frame
    view.addSubview(landscapesmallview)
    view.addSubview(portraitsmallview)

    landscapesmallview.addSubview(buttonredlandscape)
    landscapesmallview.addSubview(buttonbluelandscape)
    portraitsmallview.addSubview(buttonredportrait)
    portraitsmallview.addSubview(buttonblueportrait)
    buttonredlandscape.translatesAutoresizingMaskIntoConstraints = false
    buttonbluelandscape.translatesAutoresizingMaskIntoConstraints = false
    buttonredportrait.translatesAutoresizingMaskIntoConstraints = false
    buttonblueportrait.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([

    buttonredlandscape.centerYAnchor.constraint(equalTo:landscapesmallview.centerYAnchor),
        buttonredlandscape.topAnchor.constraint(equalTo:landscapesmallview.topAnchor,constant:40),
        buttonredlandscape.trailingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:-20),
        buttonredlandscape.heightAnchor.constraint(equalTo: landscapesmallview.heightAnchor,constant:50),

        buttonbluelandscape.centerYAnchor.constraint(equalTo:buttonredlandscape.centerYAnchor),
        buttonbluelandscape.leadingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:40),
        buttonbluelandscape.trailingAnchor.constraint(equalTo: landscapesmallview.trailingAnchor,constant:-20),
        buttonbluelandscape.heightAnchor.constraint(equalTo: buttonredlandscape.heightAnchor),

        buttonredportrait.topAnchor.constraint(equalTo: portraitsmallview.topAnchor,constant: 200),
        buttonredportrait.centerXAnchor.constraint(equalTo: portraitsmallview.centerXAnchor),
        buttonredportrait.trailingAnchor.constraint(equalTo: portraitsmallview.trailingAnchor,constant:-20),
        buttonredportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor),

        buttonblueportrait.topAnchor.constraint(equalTo: buttonredportrait.bottomAnchor,constant: 40),
        buttonblueportrait.leadingAnchor.constraint(equalTo: buttonredportrait.leadingAnchor),
        buttonblueportrait.trailingAnchor.constraint(equalTo:buttonredportrait.trailingAnchor),
        buttonblueportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor)

        ])

    //-------

    func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
            portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
        } else if UIDevice.current.orientation.isPortrait {
            portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
            landscapesmallview.translatesAutoresizingMaskIntoConstraints = true

         }
      }

    }

  }
</code>```

which in potrait mode shows -

and which in landscape mode shows -

How to achieve what I want programmatically (see after edit 1) i.e. topmost 2  buttons to rearrange themselves programmatically every-time  the user rotates the device. Its not just the buttons. It can be labels, images, collectionview etc. or just anything. The upshot is that I want to achieve two layouts  in landscape and portrait modes programmatically.

Points to be noted :-

i) I want to use "NSLayoutConstraint.activate" because apple recommends it.

ii) If possible, I do not want to use stackview or containerview,  because there can be many more types of labels, buttons etc, but if there is no other way, then I will use it.

iii) Is my code DRY principle compliant ?

Also, guys, please, I do not deserve negative marks because,  as far as I know, this has not been asked before. I request you to remove negative marks and encourage me.

答:
How about you set a variable and set the color based on the value?</p>

```<code> import UIKit

  class OrientationViewController: UIViewController {

  var screenOrientation = ""

  override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {

        print("landscape")
        self.screenOrientation = "landscape"

    } else {

        print("portrait")
        self.screenOrientation = "portrait"

    }
  }
</code>```

```<code>if self.screenOrientation == "landscape" {
   self.yourView.backgroundColor = UIColor.//set color
}
else if self.screenOrientation == "portrait" {
   self.yourView.backgroundColor = UIColor.//set different color
}
else{
   self.yourView.backgroundColor = UIColor.//set default color
}

</code>```

Body:
This is part of a much bigger issue I  am having. I have simplified it for you. I want to programmatically change the background color of view on device orientation ?

The following code prints "landcape" and "portrait" in the debugging console every-tome I  rotate the device in the simulator :-

  import UIKit
  class OrientationViewController: UIViewController {
  override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        print("landscape")
    } else {
        print("portrait")
    }
  }
}

Though the following code does nothing :-

   import UIKit
   class AskitViewController: UIViewController {
    override func viewDidLoad() {
    let landscapesmallview = UIView()
    landscapesmallview.backgroundColor = .orange
   let portraitsmallview = UIView()
    portraitsmallview.backgroundColor = .purple
    view.addSubview(landscapesmallview)
    view.addSubview(portraitsmallview)

 func viewWillTransition(to size: CGSize, with coordinator:      UIViewControllerTransitionCoordinator) {
     if UIDevice.current.orientation.isLandscape {
        print("landscape")
    landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
     portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
    } else {
        print("potrait")
  portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
  landscapesmallview.translatesAutoresizingMaskIntoConstraints = true
        }
       }
      }
     }

I am using swift 4.2 and or 5, xcode 10.2
   So, how to programmatically change the background color of view every-time I rotate  the device ?

Please, any of you experts help me ?

edit 1:

I had told you'll in the beginning that it is a part of a bigger issue -

I have buttons inside a view which in potrait mode I want like this -

which is achieved by the following code -

//original potrait mode/////

    import UIKit
    class PotraitViewController: UIViewController {
    override func viewDidLoad() {
    let buttonred = UIButton()
    buttonred.backgroundColor = UIColor.red
    let buttonblue = UIButton()
    buttonblue.backgroundColor = UIColor.blue
    let landscapesmallview = UIView()
    view.addSubview(landscapesmallview)
    landscapesmallview.addSubview(buttonred)
    landscapesmallview.addSubview(buttonblue)
    buttonred.translatesAutoresizingMaskIntoConstraints = false
    buttonblue.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([

        buttonred.topAnchor.constraint(equalTo: view.topAnchor,constant: 200),
        buttonred.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        buttonred.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
        buttonred.widthAnchor.constraint(equalToConstant: 50),
        //-------
        buttonblue.topAnchor.constraint(equalTo: buttonred.bottomAnchor,constant: 40),
        buttonblue.leadingAnchor.constraint(equalTo: buttonred.leadingAnchor),
        buttonblue.trailingAnchor.constraint(equalTo:buttonred.trailingAnchor),
        buttonblue.widthAnchor.constraint(equalTo: buttonred.widthAnchor)

        ])
    }

 }

and in landscape mode  I want like this -

which is achieved by the following code -

// original lanscape mode/////

  import UIKit
  class LandscapeViewController: UIViewController {
   override func viewDidLoad() {
    let buttonred = UIButton()
    buttonred.backgroundColor = UIColor.red
    let buttonblue = UIButton()
    buttonblue.backgroundColor = UIColor.blue
    view.addSubview(buttonred)
    view.addSubview(buttonblue)
    buttonred.translatesAutoresizingMaskIntoConstraints = false
    buttonblue.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([

        buttonred.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        buttonred.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant:40),
        buttonred.trailingAnchor.constraint(equalTo: view.centerXAnchor,constant:-20),
        buttonred.widthAnchor.constraint(equalToConstant: 50),

        //-------
        buttonblue.centerYAnchor.constraint(equalTo: buttonred.centerYAnchor),
        buttonblue.leadingAnchor.constraint(equalTo: view.centerXAnchor,constant:40),
        buttonblue.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant:-20),
        buttonblue.widthAnchor.constraint(equalTo:buttonred.widthAnchor)

        ])
     }

  }

So, I tried the following code to achieve by screen rotation i.e. two different  layouts in potrait and landscape views programmatically with the help of the following code:-

    import UIKit

    class NewViewController: UIViewController {
    override func viewDidLoad() {
    let buttonredlandscape = UIButton()
    buttonredlandscape.backgroundColor = UIColor.red
    let buttonbluelandscape = UIButton()
    buttonbluelandscape.backgroundColor = UIColor.blue
    let buttonredportrait = UIButton()
    buttonredportrait.backgroundColor = UIColor.red
    let buttonblueportrait = UIButton()
    buttonblueportrait.backgroundColor = UIColor.blue

    let landscapesmallview = UIView()
    let portraitsmallview = UIView()
    landscapesmallview.backgroundColor = UIColor.gray
    portraitsmallview.backgroundColor = UIColor.purple
    landscapesmallview.frame = view.frame
    portraitsmallview.frame = view.frame
    view.addSubview(landscapesmallview)
    view.addSubview(portraitsmallview)

    landscapesmallview.addSubview(buttonredlandscape)
    landscapesmallview.addSubview(buttonbluelandscape)
    portraitsmallview.addSubview(buttonredportrait)
    portraitsmallview.addSubview(buttonblueportrait)
    buttonredlandscape.translatesAutoresizingMaskIntoConstraints = false
    buttonbluelandscape.translatesAutoresizingMaskIntoConstraints = false
    buttonredportrait.translatesAutoresizingMaskIntoConstraints = false
    buttonblueportrait.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([

    buttonredlandscape.centerYAnchor.constraint(equalTo:landscapesmallview.centerYAnchor),
        buttonredlandscape.topAnchor.constraint(equalTo:landscapesmallview.topAnchor,constant:40),
        buttonredlandscape.trailingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:-20),
        buttonredlandscape.heightAnchor.constraint(equalTo: landscapesmallview.heightAnchor,constant:50),

        buttonbluelandscape.centerYAnchor.constraint(equalTo:buttonredlandscape.centerYAnchor),
        buttonbluelandscape.leadingAnchor.constraint(equalTo: landscapesmallview.centerXAnchor,constant:40),
        buttonbluelandscape.trailingAnchor.constraint(equalTo: landscapesmallview.trailingAnchor,constant:-20),
        buttonbluelandscape.heightAnchor.constraint(equalTo: buttonredlandscape.heightAnchor),

        buttonredportrait.topAnchor.constraint(equalTo: portraitsmallview.topAnchor,constant: 200),
        buttonredportrait.centerXAnchor.constraint(equalTo: portraitsmallview.centerXAnchor),
        buttonredportrait.trailingAnchor.constraint(equalTo: portraitsmallview.trailingAnchor,constant:-20),
        buttonredportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor),

        buttonblueportrait.topAnchor.constraint(equalTo: buttonredportrait.bottomAnchor,constant: 40),
        buttonblueportrait.leadingAnchor.constraint(equalTo: buttonredportrait.leadingAnchor),
        buttonblueportrait.trailingAnchor.constraint(equalTo:buttonredportrait.trailingAnchor),
        buttonblueportrait.widthAnchor.constraint(equalTo: buttonredportrait.widthAnchor)

        ])

    //-------

    func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if UIDevice.current.orientation.isLandscape {
            landscapesmallview.translatesAutoresizingMaskIntoConstraints = false
            portraitsmallview.translatesAutoresizingMaskIntoConstraints = true
        } else if UIDevice.current.orientation.isPortrait {
            portraitsmallview.translatesAutoresizingMaskIntoConstraints = false
            landscapesmallview.translatesAutoresizingMaskIntoConstraints = true

         }
      }

    }

  }

which in potrait mode shows -

and which in landscape mode shows -

How to achieve what I want programmatically (see after edit 1) i.e. topmost 2  buttons to rearrange themselves programmatically every-time  the user rotates the device. Its not just the buttons. It can be labels, images, collectionview etc. or just anything. The upshot is that I want to achieve two layouts  in landscape and portrait modes programmatically.

Points to be noted :-

i) I want to use "NSLayoutConstraint.activate" because apple recommends it.

ii) If possible, I do not want to use stackview or containerview,  because there can be many more types of labels, buttons etc, but if there is no other way, then I will use it.

iii) Is my code DRY principle compliant ?

Also, guys, please, I do not deserve negative marks because,  as far as I know, this has not been asked before. I request you to remove negative marks and encourage me.

Body:
How about you set a variable and set the color based on the value?

 import UIKit

  class OrientationViewController: UIViewController {

  var screenOrientation = ""

  override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {

        print("landscape")
        self.screenOrientation = "landscape"

    } else {

        print("portrait")
        self.screenOrientation = "portrait"

    }
  }

if self.screenOrientation == "landscape" {
   self.yourView.backgroundColor = UIColor.//set color
}
else if self.screenOrientation == "portrait" {
   self.yourView.backgroundColor = UIColor.//set different color
}
else{
   self.yourView.backgroundColor = UIColor.//set default color
}


问:
Equivalent of ag-grid enterprise feature EnableRangeSelection (AngularJS) for cell copy
I'm using the free version of ag-grid with AngularJS , so I can't benefit from the EnableRangeSelection that comes with the enterprise version.

I mainly need this feature so that I can copy/paste multiple cells at once.

I would like to know if anyone has been able to have a range selection in the ag-grid free version by creating a custom function for that ?

Thanks !

答:
Ag-grid community version has a very basic cell(s) copy feature which allows you to select the text in each cell to copy to clipboard.

Using this gridOption - enableCellTextSelection : true

From the docs -

enableCellTextSelection    Set to true to be able to select the text within cells. Note: When this is set to true, the clipboard service is
  disabled. Default: false


问:
How can I make this while loop faster on a microcontroller button?
I am working with a micro controller that has a button A. When I press this button and hold it for 2 seconds, its value becomes 0 and the color turns either blue or green, when I release, its value goes back to 1 but the color stays the same unless it was clicked again and the color changes. The problem is, it shouldn't take someone 2 whole seconds to have to change the led light. What can I do to make the value (either 0 or 1) be read faster?

Here is a snippet of the code in the while loop.

```<code>
// here are the states for reference. Everything is either a 0 or a 1
const int BUTTON_PRESSED = 0;
const int BUTTON_UNPRESSED = 1;

const int GREEN_LED = 0;
const int BLUE_LED = 1;

    const struct timespec sleepTime = { 1, 0 };

    while (true) {
        Value_Type value;
        // this function get the input of button a when pressed
        GetValue(button_A_fd, &value);
        Log_Debug(
           "Button value (%d)\n", value);

        // Processing the button.

        //Turns LED ON; Button not pressed down
        if (value == BUTTON_UNPRESSED) {
            last_button_state = BUTTON_UNPRESSED;
        } else {

            // if last button state is 1 then now it is being pressed
            if (last_button_state == BUTTON_UNPRESSED) {
                // Flip LEDs
                if (active_led == BLUE_LED) {
                    active_led = GREEN_LED;
                }
                else if (active_led == GREEN_LED) {
                    active_led = BLUE_LED;
                }

                last_button_state = BUTTON_PRESSED;
                // sets the pointer to the 0 bit of the file to write
                lseek(fd_storage, 0, SEEK_SET);
                // write current active led to mutable storage and save
                write(fd_storage, &active_led, sizeof(active_led));
            }
        }
        // Blinking the active LED.
        // reading input only when pressed and turn off other led
        if (active_led == GREEN_LED) {
            // turn off blue led, then turn on green
            SetValue(blue_led_fd, Value_High);
            SetValue(green_led_fd, Value_Low);
            nanosleep(&sleepTime, NULL);
            SetValue(green_led_fd, Value_High);
            nanosleep(&sleepTime, NULL);
        }
        else if (active_led == BLUE_LED) {
            // turn off green led, then turn on blue
            SetValue(green_led_fd, Value_High);
            SetValue(blue_led_fd, Value_Low);
            nanosleep(&sleepTime, NULL);
            SetValue(blue_led_fd, Value_High);
            nanosleep(&sleepTime, NULL);
        }
    }
}

</code>```

I tried to put GetValue() in several parts of the code to see if it could maybe get a value faster but it did not work. How can I move from here? I hope I shared enough code to understand the problem. Thank you.

答:
Upon further inspection, I found these:

The above picture is linked from here , it is the spec sheet for your microcontroller.

You want to look at the "Board Pin Map section" from this link to match it with the spec sheet of the chip itself

Body:
I am working with a micro controller that has a button A. When I press this button and hold it for 2 seconds, its value becomes 0 and the color turns either blue or green, when I release, its value goes back to 1 but the color stays the same unless it was clicked again and the color changes. The problem is, it shouldn't take someone 2 whole seconds to have to change the led light. What can I do to make the value (either 0 or 1) be read faster?

Here is a snippet of the code in the while loop.

// here are the states for reference. Everything is either a 0 or a 1
const int BUTTON_PRESSED = 0;
const int BUTTON_UNPRESSED = 1;

const int GREEN_LED = 0;
const int BLUE_LED = 1;

    const struct timespec sleepTime = { 1, 0 };

    while (true) {
        Value_Type value;
        // this function get the input of button a when pressed
        GetValue(button_A_fd, &value);
        Log_Debug(
           "Button value (%d)\n", value);

        // Processing the button.

        //Turns LED ON; Button not pressed down
        if (value == BUTTON_UNPRESSED) {
            last_button_state = BUTTON_UNPRESSED;
        } else {

            // if last button state is 1 then now it is being pressed
            if (last_button_state == BUTTON_UNPRESSED) {
                // Flip LEDs
                if (active_led == BLUE_LED) {
                    active_led = GREEN_LED;
                }
                else if (active_led == GREEN_LED) {
                    active_led = BLUE_LED;
                }

                last_button_state = BUTTON_PRESSED;
                // sets the pointer to the 0 bit of the file to write
                lseek(fd_storage, 0, SEEK_SET);
                // write current active led to mutable storage and save
                write(fd_storage, &active_led, sizeof(active_led));
            }
        }
        // Blinking the active LED.
        // reading input only when pressed and turn off other led
        if (active_led == GREEN_LED) {
            // turn off blue led, then turn on green
            SetValue(blue_led_fd, Value_High);
            SetValue(green_led_fd, Value_Low);
            nanosleep(&sleepTime, NULL);
            SetValue(green_led_fd, Value_High);
            nanosleep(&sleepTime, NULL);
        }
        else if (active_led == BLUE_LED) {
            // turn off green led, then turn on blue
            SetValue(green_led_fd, Value_High);
            SetValue(blue_led_fd, Value_Low);
            nanosleep(&sleepTime, NULL);
            SetValue(blue_led_fd, Value_High);
            nanosleep(&sleepTime, NULL);
        }
    }
}

I tried to put GetValue() in several parts of the code to see if it could maybe get a value faster but it did not work. How can I move from here? I hope I shared enough code to understand the problem. Thank you.


问:
Module not found error in Jenkins while trying to run wdio from docker image
I am using webdriverio . My package.json is having all my dependency. I have created a docker image for my project throught Jenkins using a docker file. Now I am trying run the scripts from Jenkins. It is failing saying module not found. For example in config file I have used var json=require('cjson') . Same has been installed in docker image . But when  I run through Jenkins it fails saying module cjson not found</p>

答:
Build container on your local and try to run it from there and check:

**1. Is your dependency installation script running?

See if there are any error for specific module that's failing**

Best


问:
Logging of unit test result using AspectJ
I'm trying to log my test suite results using AspectJ. I'd like to 'inject' the results identification code after each @Test method in my code, so created an aspect with the following method:

```<code>  @After("execution(* *(..)) && @annotation(org.junit.Test)")
  public void afterTestMethod(JoinPoint joinPoint) {
      //identify test result
  }
</code>```

However, can't find how to retrieve the test method result (passed/failed/skipped).
Any suggestions?

Thanks!

答:
A) JUnit run listener

I am assuming that you build your project with something like Maven or Gradle and will show you a Maven example for a JUnit 4 RunListener:

In module test-tools you would add

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13</version>

  <scope>compile</scope>
</dependency>
```

<p>to your POM and then have something like this in <code>src/main/java/...</code>:</p>

<pre class="lang-java prettyprint-override"><code>package de.scrum_master.testing;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

public class ResultPrintingRunListener extends RunListener {
  @Override
  public void testRunStarted(Description description) {
    System.out.println("[RunStarted] description = " + description);
  }

  @Override
  public void testRunFinished(Result result) {
    System.out.println("[RunFinished] result = " + result);
    System.out.println("  run count = " + result.getRunCount());
    System.out.println("  failure count = " + result.getFailureCount());
    System.out.println("  assumption failure count = " + result.getAssumptionFailureCount());
    System.out.println("  ignored count = " + result.getIgnoreCount());
    System.out.println("  run time (ms) = " + result.getRunTime());
  }

  @Override
  public void testSuiteStarted(Description description) {
    System.out.println("[SuiteStarted] description = " + description);
  }

  @Override
  public void testSuiteFinished(Description description) {
    System.out.println("[SuiteFinished] description = " + description);
  }

  @Override
  public void testStarted(Description description) {
    System.out.println("[Started] description = " + description);
  }

  @Override
  public void testFinished(Description description) {
    System.out.println("[Finished] description = " + description);
  }

  @Override
  public void testFailure(Failure failure) {
    System.out.println("[Failure] failure = " + failure);
  }

  @Override
  public void testAssumptionFailure(Failure failure) {
    System.out.println("[AssumptionFailure] failure = " + failure);
  }

  @Override
  public void testIgnored(Description description) {
    System.out.println("[Ignored] description = " + description);
  }
}
</code>```

Instead of logging you would put your API calls in there at the appropriate places.

In your application test module you would add the test-tools module as a dependency and then configure your Maven Surefire/Failsafe plugins like this:

<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.22.2</version>
  <configuration>
    <properties>
      <property>
        <name>listener</name>
        <value>de.scrum_master.testing.ResultPrintingRunListener</value>
      </property>
    </properties>
  </configuration>
</plugin>
```

<p>If then you run a test like this in Maven, ...</p>

<pre class="lang-java prettyprint-override"><code>package de.scrum_master.agent.aspect;

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class MyTest {
  @Test
  public void one() {
    Assert.assertEquals("xander", "Alexander".substring(3));
  }

  @Test
  public void two() {
    Assert.assertEquals("Alex", "Alexander".substring(3));
  }

  @Test
  public void three() {
    Assert.assertEquals(11, 1 / 0);
  }

  @Test
  @Ignore
  public void four() {
    Assert.assertNull(null);
  }
}
</code>```

... Maven prints:

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[RunStarted] description = null
[INFO] Running de.scrum_master.agent.aspect.MyTest
[SuiteStarted] description = de.scrum_master.agent.aspect.MyTest
[Started] description = one(de.scrum_master.agent.aspect.MyTest)
[Finished] description = one(de.scrum_master.agent.aspect.MyTest)
[Started] description = two(de.scrum_master.agent.aspect.MyTest)
[Failure] failure = two(de.scrum_master.agent.aspect.MyTest): expected:<[Alex]> but was:<[xander]>
[Finished] description = two(de.scrum_master.agent.aspect.MyTest)
[Ignored] description = four(de.scrum_master.agent.aspect.MyTest)
[Started] description = three(de.scrum_master.agent.aspect.MyTest)
[Failure] failure = three(de.scrum_master.agent.aspect.MyTest): / by zero
[Finished] description = three(de.scrum_master.agent.aspect.MyTest)
[SuiteFinished] description = de.scrum_master.agent.aspect.MyTest
[ERROR] Tests run: 4, Failures: 1, Errors: 1, Skipped: 1, Time elapsed: 0.11 s <<< FAILURE! - in de.scrum_master.agent.aspect.MyTest
[ERROR] de.scrum_master.agent.aspect.MyTest.two  Time elapsed: 0.007 s  <<< FAILURE!
org.junit.ComparisonFailure: expected:<[Alex]> but was:<[xander]>
    at de.scrum_master.agent.aspect.MyTest.two(MyTest.java:31)

[ERROR] de.scrum_master.agent.aspect.MyTest.three  Time elapsed: 0.001 s  <<< ERROR!
java.lang.ArithmeticException: / by zero
    at de.scrum_master.agent.aspect.MyTest.three(MyTest.java:36)

[RunFinished] result = org.junit.runner.Result@79be0360
  run count = 3
  failure count = 2
  assumption failure count = 0
  ignored count = 1
  run time (ms) = 0
```

<h3>JUnit test watcher rule</h3>

<p>If you prefer something which is independent of a specific JUnit runner right inside your tests, create a base class like this using JUnit TestWatcher:</p>

<pre class="lang-java prettyprint-override"><code>package de.scrum_master.agent.aspect;

import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class TestBase {
  @Rule(order = Integer.MIN_VALUE)
  public TestWatcher testWatcher = new TestWatcher() {
    @Override
    protected void failed(Throwable e, Description description) {
      System.out.println("[TestWatcher failed] description = " + description +", e = " + e);
    }

    @Override
    protected void succeeded(Description description) {
      System.out.println("[TestWatcher succeeded] description = " + description);
    }
  };
}
</code>```

Then make all your test classes extends TestBase directly or indirectly. If you run the test, e.g. from an IDE, you see (shortened output, only test watcher log):

[TestWatcher succeeded] description = one(de.scrum_master.agent.aspect.MyTest)
[TestWatcher failed] description = two(de.scrum_master.agent.aspect.MyTest), e = org.junit.ComparisonFailure: expected:<[Alex]> but was:<[xander]>
[TestWatcher failed] description = three(de.scrum_master.agent.aspect.MyTest), e = java.lang.ArithmeticException: / by zero
```

<p>You see, there are fewer events in the test watcher, e.g. ignored tests are not reported.</p>

<p>As much as I love AspectJ (which is how I found this question), I think you should try configuring JUnit appropriately first and will probably be happy with it. If for whatever reason - please explain, if so - you still insist in an AOP solution, please let me know.</p>

<hr>

<h3>(C) Intercept JUnit tests directly</h3>

<p>Because you insisted:</p>

<pre class="lang-java prettyprint-override"><code>package de.scrum_master.aspectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class TestResultInterceptor {
  @AfterReturning(value = "execution(* *(..)) && @annotation(org.junit.Test)", returning = "result")
  public void allMethods(JoinPoint joinPoint, Object result) {
    System.out.println(joinPoint + " -> PASSED");
  }

  @AfterThrowing(value = "execution(* *(..)) && @annotation(org.junit.Test)", throwing = "throwable")
  public void allMethods(JoinPoint joinPoint, Throwable throwable) {
    System.out.println(joinPoint + " -> FAILED: " + throwable);
  }
}
</code>```

When running the JUnit test above in my IDE, the console log is:

execution(void de.scrum_master.testing.MyTest.one()) -> PASSED
execution(void de.scrum_master.testing.MyTest.two()) -> FAILED: org.junit.ComparisonFailure: expected:<[Alex]> but was:<[xander]>
execution(void de.scrum_master.testing.MyTest.three()) -> FAILED: java.lang.ArithmeticException: / by zero
```

I think you can take it from here.

Body:
I'm trying to log my test suite results using AspectJ. I'd like to 'inject' the results identification code after each @Test method in my code, so created an aspect with the following method:

  @After("execution(* *(..)) && @annotation(org.junit.Test)")
  public void afterTestMethod(JoinPoint joinPoint) {
      //identify test result
  }

However, can't find how to retrieve the test method result (passed/failed/skipped).
Any suggestions?

Thanks!

Body:
A) JUnit run listener

I am assuming that you build your project with something like Maven or Gradle and will show you a Maven example for a JUnit 4 RunListener:

In module test-tools you would add

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13</version>
  <!--
    We build something with the JUnit API, not just run a test,
    so scope 'test' is not enough here
  -->
  <scope>compile</scope>
</dependency>

to your POM and then have something like this in src/main/java/...:

package de.scrum_master.testing;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

public class ResultPrintingRunListener extends RunListener {
  @Override
  public void testRunStarted(Description description) {
    System.out.println("[RunStarted] description = " + description);
  }

  @Override
  public void testRunFinished(Result result) {
    System.out.println("[RunFinished] result = " + result);
    System.out.println("  run count = " + result.getRunCount());
    System.out.println("  failure count = " + result.getFailureCount());
    System.out.println("  assumption failure count = " + result.getAssumptionFailureCount());
    System.out.println("  ignored count = " + result.getIgnoreCount());
    System.out.println("  run time (ms) = " + result.getRunTime());
  }

  @Override
  public void testSuiteStarted(Description description) {
    System.out.println("[SuiteStarted] description = " + description);
  }

  @Override
  public void testSuiteFinished(Description description) {
    System.out.println("[SuiteFinished] description = " + description);
  }

  @Override
  public void testStarted(Description description) {
    System.out.println("[Started] description = " + description);
  }

  @Override
  public void testFinished(Description description) {
    System.out.println("[Finished] description = " + description);
  }

  @Override
  public void testFailure(Failure failure) {
    System.out.println("[Failure] failure = " + failure);
  }

  @Override
  public void testAssumptionFailure(Failure failure) {
    System.out.println("[AssumptionFailure] failure = " + failure);
  }

  @Override
  public void testIgnored(Description description) {
    System.out.println("[Ignored] description = " + description);
  }
}

Instead of logging you would put your API calls in there at the appropriate places.

In your application test module you would add the test-tools module as a dependency and then configure your Maven Surefire/Failsafe plugins like this:

<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.22.2</version>
  <configuration>
    <properties>
      <property>
        <name>listener</name>
        <value>de.scrum_master.testing.ResultPrintingRunListener</value>
      </property>
    </properties>
  </configuration>
</plugin>

If then you run a test like this in Maven, ...

package de.scrum_master.agent.aspect;

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class MyTest {
  @Test
  public void one() {
    Assert.assertEquals("xander", "Alexander".substring(3));
  }

  @Test
  public void two() {
    Assert.assertEquals("Alex", "Alexander".substring(3));
  }

  @Test
  public void three() {
    Assert.assertEquals(11, 1 / 0);
  }

  @Test
  @Ignore
  public void four() {
    Assert.assertNull(null);
  }
}

... Maven prints:

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[RunStarted] description = null
[INFO] Running de.scrum_master.agent.aspect.MyTest
[SuiteStarted] description = de.scrum_master.agent.aspect.MyTest
[Started] description = one(de.scrum_master.agent.aspect.MyTest)
[Finished] description = one(de.scrum_master.agent.aspect.MyTest)
[Started] description = two(de.scrum_master.agent.aspect.MyTest)
[Failure] failure = two(de.scrum_master.agent.aspect.MyTest): expected:<[Alex]> but was:<[xander]>
[Finished] description = two(de.scrum_master.agent.aspect.MyTest)
[Ignored] description = four(de.scrum_master.agent.aspect.MyTest)
[Started] description = three(de.scrum_master.agent.aspect.MyTest)
[Failure] failure = three(de.scrum_master.agent.aspect.MyTest): / by zero
[Finished] description = three(de.scrum_master.agent.aspect.MyTest)
[SuiteFinished] description = de.scrum_master.agent.aspect.MyTest
[ERROR] Tests run: 4, Failures: 1, Errors: 1, Skipped: 1, Time elapsed: 0.11 s <<< FAILURE! - in de.scrum_master.agent.aspect.MyTest
[ERROR] de.scrum_master.agent.aspect.MyTest.two  Time elapsed: 0.007 s  <<< FAILURE!
org.junit.ComparisonFailure: expected:<[Alex]> but was:<[xander]>
    at de.scrum_master.agent.aspect.MyTest.two(MyTest.java:31)

[ERROR] de.scrum_master.agent.aspect.MyTest.three  Time elapsed: 0.001 s  <<< ERROR!
java.lang.ArithmeticException: / by zero
    at de.scrum_master.agent.aspect.MyTest.three(MyTest.java:36)

[RunFinished] result = org.junit.runner.Result@79be0360
  run count = 3
  failure count = 2
  assumption failure count = 0
  ignored count = 1
  run time (ms) = 0

JUnit test watcher rule

If you prefer something which is independent of a specific JUnit runner right inside your tests, create a base class like this using JUnit TestWatcher:

package de.scrum_master.agent.aspect;

import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class TestBase {
  @Rule(order = Integer.MIN_VALUE)
  public TestWatcher testWatcher = new TestWatcher() {
    @Override
    protected void failed(Throwable e, Description description) {
      System.out.println("[TestWatcher failed] description = " + description +", e = " + e);
    }

    @Override
    protected void succeeded(Description description) {
      System.out.println("[TestWatcher succeeded] description = " + description);
    }
  };
}

Then make all your test classes extends TestBase directly or indirectly. If you run the test, e.g. from an IDE, you see (shortened output, only test watcher log):

[TestWatcher succeeded] description = one(de.scrum_master.agent.aspect.MyTest)
[TestWatcher failed] description = two(de.scrum_master.agent.aspect.MyTest), e = org.junit.ComparisonFailure: expected:<[Alex]> but was:<[xander]>
[TestWatcher failed] description = three(de.scrum_master.agent.aspect.MyTest), e = java.lang.ArithmeticException: / by zero

You see, there are fewer events in the test watcher, e.g. ignored tests are not reported.

As much as I love AspectJ (which is how I found this question), I think you should try configuring JUnit appropriately first and will probably be happy with it. If for whatever reason - please explain, if so - you still insist in an AOP solution, please let me know.

(C) Intercept JUnit tests directly

Because you insisted:

package de.scrum_master.aspectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class TestResultInterceptor {
  @AfterReturning(value = "execution(* *(..)) && @annotation(org.junit.Test)", returning = "result")
  public void allMethods(JoinPoint joinPoint, Object result) {
    System.out.println(joinPoint + " -> PASSED");
  }

  @AfterThrowing(value = "execution(* *(..)) && @annotation(org.junit.Test)", throwing = "throwable")
  public void allMethods(JoinPoint joinPoint, Throwable throwable) {
    System.out.println(joinPoint + " -> FAILED: " + throwable);
  }
}

When running the JUnit test above in my IDE, the console log is:

execution(void de.scrum_master.testing.MyTest.one()) -> PASSED
execution(void de.scrum_master.testing.MyTest.two()) -> FAILED: org.junit.ComparisonFailure: expected:<[Alex]> but was:<[xander]>
execution(void de.scrum_master.testing.MyTest.three()) -> FAILED: java.lang.ArithmeticException: / by zero

I think you can take it from here.


问:
How can a button click on a UserControl execute a method in the containing Window?
I have a UserControl, we'll call it myUC, that is one among several UserControls in the main window (myWindow) of my WPF application.  myUC contains a number of standard controls, one of them being a button, we'll call it myButton.

When I click myButton, I would like to execute myMethod(), which exists in the code-behind of myWindow.

The problem being that myUC doesn't have any idea that myWindow even exists, much less that myMethod exists.

How can I send the message: 'Hey, myWindow, wake up.  myButton on myUc was just clicked; please run myMethod'?

答:
The above is all well and good... but seems a bit convoluted to me...

My similar problem:
 I have a Window (MainWindow.xaml) with a UserControl (SurveyHeader.xaml) in it and inside that UserControl is another UserControl (GetSurveyByID.xaml). I have a private void in MainWindow.xaml that i want to run when a button (btnGetSurvey) is clicked in GetSurveyByID.xaml.

This one line solution worked quite well for me.

```<code>this.ucSurveyHeader.ucGetSurveyByID.btnGetSurvey.Click += new RoutedEventHandler(btnGetSurvey_Click);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The above is all well and good... but seems a bit convoluted to me...

My similar problem:
 I have a Window (MainWindow.xaml) with a UserControl (SurveyHeader.xaml) in it and inside that UserControl is another UserControl (GetSurveyByID.xaml). I have a private void in MainWindow.xaml that i want to run when a button (btnGetSurvey) is clicked in GetSurveyByID.xaml.

This one line solution worked quite well for me.

this.ucSurveyHeader.ucGetSurveyByID.btnGetSurvey.Click += new RoutedEventHandler(btnGetSurvey_Click);


问:
Minimal number of cuts of rectangle in squares
The task is to find minimal number of cuts of rectangle in squares. I wrote a recursive function to do so, but the point is to write it using dynamic programming. I wrote the matrix on the paper but still find it difficult to write a code.. Here a and b are dimensions of rectangle:

```<code>int minimalNumOfCuts(int a, int b)
{
    if (a==b) return 0;
    int result;
    if (a<b)
        result = 1+minimalNumOfCuts(b-a,a);//found a square with side a, so I add 1 and recurs on
    else result = 1+minimalNumOfCuts(a-b,b);//found a square with side b
    return result;
}
</code>```

For example, for rectangle 3x5 the function should return 3, which is the number of minimal cuts required to get one square with side 3, one with side 2, and two squares with sides of 1.

Here is how I think (if I use dynamic programming) the matrix should look, when I solve the subproblems (smaller rectangles). The column and row with zeroes is not needed.

答:
You go through the rectangle with an euclidean algorithm, which is kind of what you are trying there, and count the cuts, there are some possiblilities for a recursive function that could achieve this, here is a possible implementation passing a counter pointer as argument of the function to be changed in the inner recursions:

Live demo

```<code>#include <stdio.h>
#include <stdlib.h>

void minimalNumOfCuts(int side1, int side2, int *count);

int main() {
    int side1 = 3, side2 = 5, count = 0;

    minimalNumOfCuts(side1, side2, &count);
    printf("Height %d Length %d - %d cuts\n", side1, side2, count);

    return EXIT_SUCCESS;
}

void minimalNumOfCuts(int side1, int side2, int *count) {

    if (side1 == side2) {
        return;
    }

    if (side1 > side2) {
        side1 -= side2;
    }
    else {
        side2 -= side1;
    }
    (*count)++;
    minimalNumOfCuts(side1, side2, count); //recursive call
}
</code>```

Output:

```<code>Height 3 Length 5 - 3 cuts
</code>```

EDIT:

For your table just cycle through the values:

This sample counts the cuts from a rectangle with height ranging from 1 to 5 and length ranging from 1 to 4 using the same recursive function.

Live demo

```<code>#define MAX_HEIGHT 5
#define MAX_LENGHT 4

int main() {

    int count = 0;

    for (int i = 1; i < MAX_HEIGHT + 1; i++) {
        for (int j = 1; j < MAX_LENGHT + 1; j++) {
            minimalNumOfCuts(i, j, &count);
            printf("Height %d Length %d - %d cuts\n", i, j, count);
            count = 0;
        }
    }
    return EXIT_SUCCESS;
}
</code>```

Output:

```<code>Height 1 Length 1 - 0 cuts
Height 1 Length 2 - 1 cuts
Height 1 Length 3 - 2 cuts
Height 1 Length 4 - 3 cuts
Height 2 Length 1 - 1 cuts
Height 2 Length 2 - 0 cuts
Height 2 Length 3 - 2 cuts
Height 2 Length 4 - 1 cuts
Height 3 Length 1 - 2 cuts
Height 3 Length 2 - 2 cuts
Height 3 Length 3 - 0 cuts
Height 3 Length 4 - 3 cuts
Height 4 Length 1 - 3 cuts
Height 4 Length 2 - 1 cuts
Height 4 Length 3 - 3 cuts
Height 4 Length 4 - 0 cuts
Height 5 Length 1 - 4 cuts
Height 5 Length 2 - 3 cuts
Height 5 Length 3 - 3 cuts
Height 5 Length 4 - 4 cuts
</code>```

Here is a nice graphic demonstration where you can check the results.

Note that there are some imprecisions in your table, for instance, a rectangle with sides 3 and 4 will need only 3 cuts.

Body:
The task is to find minimal number of cuts of rectangle in squares. I wrote a recursive function to do so, but the point is to write it using dynamic programming. I wrote the matrix on the paper but still find it difficult to write a code.. Here a and b are dimensions of rectangle:

int minimalNumOfCuts(int a, int b)
{
    if (a==b) return 0;
    int result;
    if (a<b)
        result = 1+minimalNumOfCuts(b-a,a);//found a square with side a, so I add 1 and recurs on
    else result = 1+minimalNumOfCuts(a-b,b);//found a square with side b
    return result;
}

For example, for rectangle 3x5 the function should return 3, which is the number of minimal cuts required to get one square with side 3, one with side 2, and two squares with sides of 1.

Here is how I think (if I use dynamic programming) the matrix should look, when I solve the subproblems (smaller rectangles). The column and row with zeroes is not needed.

Body:
You go through the rectangle with an euclidean algorithm, which is kind of what you are trying there, and count the cuts, there are some possiblilities for a recursive function that could achieve this, here is a possible implementation passing a counter pointer as argument of the function to be changed in the inner recursions:

Live demo

#include <stdio.h>
#include <stdlib.h>

void minimalNumOfCuts(int side1, int side2, int *count);

int main() {
    int side1 = 3, side2 = 5, count = 0;

    minimalNumOfCuts(side1, side2, &count);
    printf("Height %d Length %d - %d cuts\n", side1, side2, count);

    return EXIT_SUCCESS;
}

void minimalNumOfCuts(int side1, int side2, int *count) {

    if (side1 == side2) {
        return;
    }

    if (side1 > side2) {
        side1 -= side2;
    }
    else {
        side2 -= side1;
    }
    (*count)++;
    minimalNumOfCuts(side1, side2, count); //recursive call
}

Output:

Height 3 Length 5 - 3 cuts

EDIT:

For your table just cycle through the values:

This sample counts the cuts from a rectangle with height ranging from 1 to 5 and length ranging from 1 to 4 using the same recursive function.

Live demo

#define MAX_HEIGHT 5
#define MAX_LENGHT 4

int main() {

    int count = 0;

    for (int i = 1; i < MAX_HEIGHT + 1; i++) {
        for (int j = 1; j < MAX_LENGHT + 1; j++) {
            minimalNumOfCuts(i, j, &count);
            printf("Height %d Length %d - %d cuts\n", i, j, count);
            count = 0;
        }
    }
    return EXIT_SUCCESS;
}

Output:

Height 1 Length 1 - 0 cuts
Height 1 Length 2 - 1 cuts
Height 1 Length 3 - 2 cuts
Height 1 Length 4 - 3 cuts
Height 2 Length 1 - 1 cuts
Height 2 Length 2 - 0 cuts
Height 2 Length 3 - 2 cuts
Height 2 Length 4 - 1 cuts
Height 3 Length 1 - 2 cuts
Height 3 Length 2 - 2 cuts
Height 3 Length 3 - 0 cuts
Height 3 Length 4 - 3 cuts
Height 4 Length 1 - 3 cuts
Height 4 Length 2 - 1 cuts
Height 4 Length 3 - 3 cuts
Height 4 Length 4 - 0 cuts
Height 5 Length 1 - 4 cuts
Height 5 Length 2 - 3 cuts
Height 5 Length 3 - 3 cuts
Height 5 Length 4 - 4 cuts

Here is a nice graphic demonstration where you can check the results.

Note that there are some imprecisions in your table, for instance, a rectangle with sides 3 and 4 will need only 3 cuts.


问:
how to make file path as a global variable in python?
I've been getting this error NameError: name 'filep' is not defined i need to make filep as a file path. but every time i run my code i always get this error.

i need to make the filep as a module variable instead of a parameter as well as menulist.

```<code>import csv

filep= # filepath
menulist = [] #global scope

def menu_List():

    global menulist
    menulist = []  # store items
    try:
        with open(filep) as f:  # read file
            reader = f.readlines()
            next(reader, None) #skip the header

            for row in reader:
                row[2] = int(row[2].strip()) #convert string to int
                row[1] = float(row[1].strip()) #convert string to float
                if row[2] > 100 and row[2] < 200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Variable not set")

    menulist.sort(key=lambda x: x[-1])

menu_List()
</code>```

答:
You do not need global variables here, your function should accept the path as an argument and return the menu list.

```<code>import csv

def menu_List(filep):

    menulist = []  # store items
    try:
        with open(filep) as f:  # read file
            reader = f.readlines()
            next(reader, None) #skip the header

            for row in reader:
                row[2] = int(row[2].strip()) #convert string to int
                row[1] = float(row[1].strip()) #convert string to float
                if row[2] > 100 and row[2] < 200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Variable not set")

    menulist.sort(key=lambda x: x[-1])
    return menulist

menulist = menu_List("a/path/goes/here")
</code>```

Unrelated to your question, you can skip the header like you did or like this:

```<code>reader = f.readlines()
for row in reader[1:]: # skip the first line.
    ...
</code>```

Body:
I've been getting this error NameError: name 'filep' is not defined i need to make filep as a file path. but every time i run my code i always get this error.

i need to make the filep as a module variable instead of a parameter as well as menulist.

import csv

filep= # filepath
menulist = [] #global scope

def menu_List():

    global menulist
    menulist = []  # store items
    try:
        with open(filep) as f:  # read file
            reader = f.readlines()
            next(reader, None) #skip the header

            for row in reader:
                row[2] = int(row[2].strip()) #convert string to int
                row[1] = float(row[1].strip()) #convert string to float
                if row[2] > 100 and row[2] < 200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Variable not set")

    menulist.sort(key=lambda x: x[-1])

menu_List()

Body:
You do not need global variables here, your function should accept the path as an argument and return the menu list.

import csv

def menu_List(filep):

    menulist = []  # store items
    try:
        with open(filep) as f:  # read file
            reader = f.readlines()
            next(reader, None) #skip the header

            for row in reader:
                row[2] = int(row[2].strip()) #convert string to int
                row[1] = float(row[1].strip()) #convert string to float
                if row[2] > 100 and row[2] < 200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Variable not set")

    menulist.sort(key=lambda x: x[-1])
    return menulist

menulist = menu_List("a/path/goes/here")

Unrelated to your question, you can skip the header like you did or like this:

reader = f.readlines()
for row in reader[1:]: # skip the first line.
    ...