问:
Jest testing the same promise response in different types each time
How do I properly test the same promise response which can be in different type ?

For example, when fetching a collection of items from Cloud Firestore database, response is in a type of an array, but there is a way to interact with a response as it was in a type of an object. Here is the code:

```<code>// ...
await Database.collection('products').select('published').get().then(snapshot => {
  snapshot.forEach(doc => { // <---- HERE snapshot IS AN ARRAY
    if (doc.data().published) {
      // ...
    }
  })
  console.log(snapshot.docs.length) // <---- HERE snapshot IS AN OBJECT. HOW ?
  console.log(snapshot.size) // IT'S THE SAME AS snapshot.docs.length
})
// ...
</code>```

I'm trying to test it by returning a value differently after each call, but it's now working, I'm getting an error:  TypeError: Cannot read property 'length' of undefined:

```<code>jest.doMock('@google-cloud/firestore', () => class {
  constructor () {
    this.collection = jest.fn().mockImplementation((collectionName) => {
      if (collectionName === 'products') {
        return {
          select: () => ({
            get: jest.fn().mockResolvedValueOnce([ // <--- AN ARRAY
              {
                data: () => {
                  return {
                    published: false
                  }
                }
              }
            ]).mockResolvedValueOnce({ // <---- AN OBJECT
              docs: () => []
            })
          }),
          limit: () => ({ get: async () => ({ empty: true }) })
        }
      }
    })
  }
})
</code>```

What's wrong here ? What should I use among all those mockings ?:

mockImplementation

mockImplementationOnce

mockResolvedValue

mockResolvedValueOnce

mockReturnValue

mockReturnValueOnce

答:
You don't need to use class to create test doubles. It makes things complicated. Just use the JS plain object data type - Array to make the query snapshot of firestore. Use Object to make the query document snapshot.

You can add custom properties to the JS array such as snapshot.docs and snapshot.size.

E.g.

index.ts:

```<code>import { Firestore } from '@google-cloud/firestore';

export async function main() {
  const Database = new Firestore();
  await Database.collection('products')
    .select('published')
    .get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        if (doc.data().published) {
          console.log(doc.data());
        }
      });
      console.log(snapshot.docs.length);
      console.log(snapshot.size);
    });
}
</code>```

index.test.ts:

```<code>describe('71058297', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  test('should pass', async () => {
    const mDocument1 = { data: jest.fn(() => ({ published: true, name: 'steam deck' })) };
    const mQuerySnapshot: any = [mDocument1];
    mQuerySnapshot.docs = mQuerySnapshot;
    mQuerySnapshot.size = mQuerySnapshot.docs.length;
    const mFirestore = {
      collection: jest.fn().mockReturnThis(),
      select: jest.fn().mockReturnThis(),
      get: jest.fn().mockResolvedValueOnce(mQuerySnapshot),
    };
    const MockFireStore = jest.fn(() => mFirestore);
    jest.doMock('@google-cloud/firestore', () => ({ Firestore: MockFireStore }));
    const { main } = require('./');
    await main();
    expect(MockFireStore).toBeCalledTimes(1);
    expect(mFirestore.collection).toBeCalledWith('products');
    expect(mFirestore.select).toBeCalledWith('published');
    expect(mFirestore.get).toBeCalledTimes(1);
    expect(mDocument1.data).toBeCalledTimes(2);
  });
});
</code>```

Test result:

 PASS  stackoverflow/71058297/index.test.ts
  71058297
    ✓ should pass (24 ms)

  console.log
    { published: true, name: 'steam deck' }

      at stackoverflow/71058297/index.ts:33:17
          at Array.forEach (<anonymous>)

  console.log
    1

      at stackoverflow/71058297/index.ts:36:13

  console.log
    1

      at stackoverflow/71058297/index.ts:37:13

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.595 s, estimated 2 s
```

Body:
How do I properly test the same promise response which can be in different type ?

For example, when fetching a collection of items from Cloud Firestore database, response is in a type of an array, but there is a way to interact with a response as it was in a type of an object. Here is the code:

// ...
await Database.collection('products').select('published').get().then(snapshot => {
  snapshot.forEach(doc => { // <---- HERE snapshot IS AN ARRAY
    if (doc.data().published) {
      // ...
    }
  })
  console.log(snapshot.docs.length) // <---- HERE snapshot IS AN OBJECT. HOW ?
  console.log(snapshot.size) // IT'S THE SAME AS snapshot.docs.length
})
// ...

I'm trying to test it by returning a value differently after each call, but it's now working, I'm getting an error:  TypeError: Cannot read property 'length' of undefined:

jest.doMock('@google-cloud/firestore', () => class {
  constructor () {
    this.collection = jest.fn().mockImplementation((collectionName) => {
      if (collectionName === 'products') {
        return {
          select: () => ({
            get: jest.fn().mockResolvedValueOnce([ // <--- AN ARRAY
              {
                data: () => {
                  return {
                    published: false
                  }
                }
              }
            ]).mockResolvedValueOnce({ // <---- AN OBJECT
              docs: () => []
            })
          }),
          limit: () => ({ get: async () => ({ empty: true }) })
        }
      }
    })
  }
})

What's wrong here ? What should I use among all those mockings ?:

mockImplementation

mockImplementationOnce

mockResolvedValue

mockResolvedValueOnce

mockReturnValue

mockReturnValueOnce

Body:
You don't need to use class to create test doubles. It makes things complicated. Just use the JS plain object data type - Array to make the query snapshot of firestore. Use Object to make the query document snapshot.

You can add custom properties to the JS array such as snapshot.docs and snapshot.size.

E.g.

index.ts:

import { Firestore } from '@google-cloud/firestore';

export async function main() {
  const Database = new Firestore();
  await Database.collection('products')
    .select('published')
    .get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        if (doc.data().published) {
          console.log(doc.data());
        }
      });
      console.log(snapshot.docs.length);
      console.log(snapshot.size);
    });
}

index.test.ts:

describe('71058297', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  test('should pass', async () => {
    const mDocument1 = { data: jest.fn(() => ({ published: true, name: 'steam deck' })) };
    const mQuerySnapshot: any = [mDocument1];
    mQuerySnapshot.docs = mQuerySnapshot;
    mQuerySnapshot.size = mQuerySnapshot.docs.length;
    const mFirestore = {
      collection: jest.fn().mockReturnThis(),
      select: jest.fn().mockReturnThis(),
      get: jest.fn().mockResolvedValueOnce(mQuerySnapshot),
    };
    const MockFireStore = jest.fn(() => mFirestore);
    jest.doMock('@google-cloud/firestore', () => ({ Firestore: MockFireStore }));
    const { main } = require('./');
    await main();
    expect(MockFireStore).toBeCalledTimes(1);
    expect(mFirestore.collection).toBeCalledWith('products');
    expect(mFirestore.select).toBeCalledWith('published');
    expect(mFirestore.get).toBeCalledTimes(1);
    expect(mDocument1.data).toBeCalledTimes(2);
  });
});

Test result:

 PASS  stackoverflow/71058297/index.test.ts
  71058297
    ✓ should pass (24 ms)

  console.log
    { published: true, name: 'steam deck' }

      at stackoverflow/71058297/index.ts:33:17
          at Array.forEach (<anonymous>)

  console.log
    1

      at stackoverflow/71058297/index.ts:36:13

  console.log
    1

      at stackoverflow/71058297/index.ts:37:13

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.595 s, estimated 2 s


来源: stackexchange

问:
Create separate object of unique keys from array of object, JavaScript
How can we make separate objects of unique keys?
Below is the sample array:

```<code>var arr = [
  {"name": "john"},
  {"email": "john@gmail.com"},
  {"phone": "2222222"},
  {"name": "jack"},
  {"email":"jack@gmail.com"},
  {"phone":"2222222333"}
]
</code>```

Output:

```<code>[
    {
        {"name" :"john"},
        {"email": "john@gmail.com"},
        {"phone": "2222222"}
    },
    {
        {"name": "jack"},
        {"email": "jack@gmail.com"},
        {"phone": "2222222333"}
    }
]
</code>```

答:
I suppose you are looking for that ?

const data =
  [ { name  : 'john'           }
  , { email : 'john@gmail.com' }
  , { phone : '2222222'        }
  , { name  : 'jack'           }
  , { email : 'jack@gmail.com' }
  , { phone : '2222222333'     }
  ]
const result = data.reduce((w,row,i) =>
  {
  let [key,val] = Object.entries(row)[0]

  if (!i || w.el.hasOwnProperty(key) )
    {
    w.el = { [key]: val }
    w.res.push(w.el)
    }
  else
    w.el[key] = val

  return w
  }, { res:[], el:null } ).res

console.log( result )```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100%!important;top:0 }</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can we make separate objects of unique keys?
Below is the sample array:

var arr = [
  {"name": "john"},
  {"email": "john@gmail.com"},
  {"phone": "2222222"},
  {"name": "jack"},
  {"email":"jack@gmail.com"},
  {"phone":"2222222333"}
]

Output:

[
    {
        {"name" :"john"},
        {"email": "john@gmail.com"},
        {"phone": "2222222"}
    },
    {
        {"name": "jack"},
        {"email": "jack@gmail.com"},
        {"phone": "2222222333"}
    }
]

Body:
I suppose you are looking for that ?

const data =
  [ { name  : 'john'           }
  , { email : 'john@gmail.com' }
  , { phone : '2222222'        }
  , { name  : 'jack'           }
  , { email : 'jack@gmail.com' }
  , { phone : '2222222333'     }
  ]
const result = data.reduce((w,row,i) =>
  {
  let [key,val] = Object.entries(row)[0]

  if (!i || w.el.hasOwnProperty(key) )
    {
    w.el = { [key]: val }
    w.res.push(w.el)
    }
  else
    w.el[key] = val

  return w
  }, { res:[], el:null } ).res

console.log( result )

.as-console-wrapper {max-height: 100%!important;top:0 }


问:
Inserting increment for each unique value in sql
I've been tasked with a SQL problem that is outside of the limited scope of sql knowledge that I have. I have the following problem.

I have a table that currently looks like this:

```<code> widgets
---------
    a
    a
    a
    b
    b
    c
    d
    d
    d
</code>```

I would like to have another table that has each unique value incrementally numbered... Like so:

```<code>widgets  | widget_id
--------- ----------
    a    |    1
    a    |    1
    a    |    1
    b    |    2
    b    |    2
    c    |    3
    d    |    4
    d    |    4
    d    |    4
</code>```

I'm not sure how this would be done with an insert statement?

答:
Well, it wouldn't be done with a insert statement.

create a temp table with an auto_increment id and the distinct widget.

Then join the widget table to the temp table, and update the widget with the temp table's id.

What you're doing here, is normalizing your data. Once you have a table of (distinct widget, id), you'd then have any other table that needed to refer to a widget instead refer to the widget id this generates.

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Body:
I've been tasked with a SQL problem that is outside of the limited scope of sql knowledge that I have. I have the following problem.

I have a table that currently looks like this:

 widgets
---------
    a
    a
    a
    b
    b
    c
    d
    d
    d

I would like to have another table that has each unique value incrementally numbered... Like so:

widgets  | widget_id
--------- ----------
    a    |    1
    a    |    1
    a    |    1
    b    |    2
    b    |    2
    c    |    3
    d    |    4
    d    |    4
    d    |    4

I'm not sure how this would be done with an insert statement?

OwnerDisplayName: tpdi


问:
How to keep circle in sync with div
In the attached image below, I want to recreate the "1" circle to the left of the profile box. I'm currently trying to use CSS positioning to get it like the image above, but whenever I shrink my computer screen, the circle doesn't move with the profile box. I'm not quite sure how to fix it. I've attached my code below the image.

body{
    width: 100%;
}

.wrapper {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    width: 80%;
    margin: auto;
    height: 100%;
}

.Ranking{
    position: absolute;
    left: 20px;
    top: 10%;
    transform: translateY(-50%);
    background: #000;
    color: #fff;
    height: 52px;
    width: 52px;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 1;
    padding-top: 4px;
    transition: background-color .25s linear .5s;
    font-family: "Decima";
    font-size: 30px;
    line-height: 30px;
    color: #f0f0f0;
    font-weight: 300;
}
.Description{
    flex:1;
    background-color: blue;
    grid-column: 2/5;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel = "stylesheet" href="styles.css">
</head>
<body>
    <div class="wrapper">
        <div class="Ranking"></div>
        <div class="Name">One</div>
        <div class="Summary">Summary: <br>He really hits, with a LF fit</div>
        <div class="Level">Highest Level: A+ <br> Age: 21</div>
        <div class="Body">Height: 6'1" <br> Weight: 215 lbs</div>
        <div class="Profile"><img src="images/Dustin Harris.jfif"> </div>
        <div class="Description">Five</div>
      </div>

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

答:
There is a CSS element called @media which will come helpful to you

```<code>@media screen (min-width: 800px) {
.container {
/* position and any property of the element according the small screen viewport*/
   }
}
</code>```

800px is the screen size under which the screen become reactive.

Title: How to keep circle in sync with div

Body:
In the attached image below, I want to recreate the "1" circle to the left of the profile box. I'm currently trying to use CSS positioning to get it like the image above, but whenever I shrink my computer screen, the circle doesn't move with the profile box. I'm not quite sure how to fix it. I've attached my code below the image.

body{
    width: 100%;
}

.wrapper {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    width: 80%;
    margin: auto;
    height: 100%;
}

.Ranking{
    position: absolute;
    left: 20px;
    top: 10%;
    transform: translateY(-50%);
    background: #000;
    color: #fff;
    height: 52px;
    width: 52px;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 1;
    padding-top: 4px;
    transition: background-color .25s linear .5s;
    font-family: "Decima";
    font-size: 30px;
    line-height: 30px;
    color: #f0f0f0;
    font-weight: 300;
}
.Description{
    flex:1;
    background-color: blue;
    grid-column: 2/5;

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel = "stylesheet" href="styles.css">

One

Summary:
He really hits, with a LF fit

Highest Level: A+
 Age: 21

Height: 6'1"
 Weight: 215 lbs

Five

Body:
There is a CSS element called @media which will come helpful to you

@media screen (min-width: 800px) {
.container {
/* position and any property of the element according the small screen viewport*/
   }
}

800px is the screen size under which the screen become reactive.


问:
Creating new jQuery object.create(newobj) 2x overwrites initial object
I'm trying to add new
 elements to an existing mobile menu, and this script works, except that the second Object.create(x) overwrites the already-appended first object. I'm very confused why that is. I'm sure I'm missing something stupid.

The script is getting the text and url from two different  tags, i.e., #c_top-nav-link-01 and #c_top-nav-link-02and trying to make new
 tags with that information.

The first if statement generates a new
 object that then appends to the
 I'm targeting, but when the second if statement runs, rather than appending a second li element with new properties, it simply replaces the first, already-appended
 element.

Thoughts? Anything obvious I'm missing?

```<code>    ;(function ( $ ) {
    $( document ).ready( function () {
        $( '.lia-slide-out-nav-menu' ).click( function ( e ) {
            console.log( 'clicked' );
            let mobileNav = $( "ul" ).first();

            const newLI = {
                newNavItem : $( '<li class="some-icon"></li>' ),
                newAnchor  : $( '<a class="some-link" href="#" title="#"></a>' ),
                newIconItem: $( '<span class="circle-icon-left" role="img" aria-label="Category"></span>' ),
                newTextItem: $( '<span class="item-text"></span>' ),
                newNavRight: $( '<span class="chevron-icon-right" role="img" aria-label="click to open this category"></span>' )
            }

            if ( $( "#c_top-nav-link-01" ) ) {

                let firstLI = Object.create( newLI );
                let link01 = $( "#c_top-nav-link-01" );
                link01.text = link01.text();
                link01.url = link01.prop( "href" );
                console.log( 'link01.text', link01.text );
                firstLI.newAnchor.prop( "href", link01.url );
                firstLI.newTextItem.text( link01.text );
                firstLI.newAnchor.append( [firstLI.newIconItem, firstLI.newTextItem, firstLI.newNavRight] );

                firstLI.newNavItem.append( firstLI.newAnchor );
                mobileNav.append( firstLI.newNavItem );
            }

            if ( $( "#c_top-nav-link-02" ) ) {

                let secondLI = Object.create( newLI );
                let link02 = $( "#c_top-nav-link-02" );
                link02.text = link02.text();
                link02.url = link02.prop( "href" );
                console.log( 'link02.text', link02.text );
                secondLI.newAnchor.prop( "href", link02.url );
                secondLI.newTextItem.text( link02.text );
                secondLI.newAnchor.append( [secondLI.newIconItem, secondLI.newTextItem, secondLI.newNavRight] );
                secondLI.newNavItem.append( secondLI.newAnchor );
                mobileNav.append( secondLI.newNavItem );
            }

        } );

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

The target is a dynamically generated unordered list that I do not have the ability to tap into and add these list items to the dynamic generation, i.e.,

```<code><ul>
    <li>item one</li>
    <li>item two</li>
    <li>item three</li>
</ul>
</code>```

I just want to add the new
 items to the list after "item three"

答:
Consider the following.

$(function() {
  function newLi(props, target) {
    var item = $("
", {
      class: props.class
    });
    if (target != undefined) {
      item.appendTo(target);
    }
    $("", props.link).appendTo(item);
    $("", props.icon).appendTo($("a", item));
    $("", props.text).html(props.text.content).appendTo($("a", item));
    return item;
  }

  $('.lia-slide-out-nav-menu').click(function(e) {
    console.log('clicked');
    var mobileNav = $("ul").first();

    if ($("#c_top-nav-link-01").length) {
      newLi({
        class: "some-icon",
        link: {
          class: "some-link",
          href: $("#c_top-nav-link-01").attr("href"),
          title: "#"
        },
        icon: {
          class: "circle-icon-left",
          role: "img",
          "aria-label": "Category"
        },
        text: {
          class: "item-text",
          content: $("#c_top-nav-link-01").text()
        }
      }, mobileNav);
    }

    if ($("#c_top-nav-link-02").length) {
      newLi({
        class: "some-icon",
        link: {
          class: "some-link",
          href: $("#c_top-nav-link-02").attr("href"),
          title: "#"
        },
        icon: {
          class: "circle-icon-left",
          role: "img",
          "aria-label": "Category"
        },
        text: {
          class: "item-text",
          content: $("#c_top-nav-link-02").text()
        }
      }, mobileNav);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="lia-slide-out-nav-menu">...</div>
<div class="slide-out-menu-links">
  <ul>
    <li>item one</li>
    <li>item two</li>
    <li>item three</li>
  </ul>
</div>
Link 1
Link 2</code>```

You can also use .clone() to clone the a element like so:

```<code>var newLink = $("#c_top-nav-link-01").clone();
</code>```

You just have to remember to adjust the ID attribute before appending it.

This example performs a similar function, yet it builds out more structure. You could do this with a <template> too if you wanted. it would give you the HTML Structure and then you could copy it as needed and populate it.

Your if statements would always be true the way you were using them. If you want to check if an element with that selector exists, you need to call the length attribute. This will return 0 if no elements exist or 1 or higher. 0 will equate to false and 1 or more will equate to true

Body:
I'm trying to add new
 elements to an existing mobile menu, and this script works, except that the second Object.create(x) overwrites the already-appended first object. I'm very confused why that is. I'm sure I'm missing something stupid.

The script is getting the text and url from two different  tags, i.e., #c_top-nav-link-01 and #c_top-nav-link-02and trying to make new
 tags with that information.

The first if statement generates a new
 object that then appends to the
 I'm targeting, but when the second if statement runs, rather than appending a second li element with new properties, it simply replaces the first, already-appended
 element.

Thoughts? Anything obvious I'm missing?

    ;(function ( $ ) {
    $( document ).ready( function () {
        $( '.lia-slide-out-nav-menu' ).click( function ( e ) {
            console.log( 'clicked' );
            let mobileNav = $( "ul" ).first();

            const newLI = {
                newNavItem : $( '

' ),
                newAnchor  : $( '' ),
                newIconItem: $( '' ),
                newTextItem: $( '' ),
                newNavRight: $( '' )
            }

            if ( $( "#c_top-nav-link-01" ) ) {

                let firstLI = Object.create( newLI );
                let link01 = $( "#c_top-nav-link-01" );
                link01.text = link01.text();
                link01.url = link01.prop( "href" );
                console.log( 'link01.text', link01.text );
                firstLI.newAnchor.prop( "href", link01.url );
                firstLI.newTextItem.text( link01.text );
                firstLI.newAnchor.append( [firstLI.newIconItem, firstLI.newTextItem, firstLI.newNavRight] );

                firstLI.newNavItem.append( firstLI.newAnchor );
                mobileNav.append( firstLI.newNavItem );
            }

            if ( $( "#c_top-nav-link-02" ) ) {

                let secondLI = Object.create( newLI );
                let link02 = $( "#c_top-nav-link-02" );
                link02.text = link02.text();
                link02.url = link02.prop( "href" );
                console.log( 'link02.text', link02.text );
                secondLI.newAnchor.prop( "href", link02.url );
                secondLI.newTextItem.text( link02.text );
                secondLI.newAnchor.append( [secondLI.newIconItem, secondLI.newTextItem, secondLI.newNavRight] );
                secondLI.newNavItem.append( secondLI.newAnchor );
                mobileNav.append( secondLI.newNavItem );
            }

        } );

    } );
})(jQuery );

The target is a dynamically generated unordered list that I do not have the ability to tap into and add these list items to the dynamic generation, i.e.,

item one

item two

item three

I just want to add the new
 items to the list after "item three"

Body:
Consider the following.

$(function() {
  function newLi(props, target) {
    var item = $("<li>", {
      class: props.class
    });
    if (target != undefined) {
      item.appendTo(target);
    }
    $("<a>", props.link).appendTo(item);
    $("<span>", props.icon).appendTo($("a", item));
    $("<span>", props.text).html(props.text.content).appendTo($("a", item));
    return item;
  }

  $('.lia-slide-out-nav-menu').click(function(e) {
    console.log('clicked');
    var mobileNav = $("ul").first();

    if ($("#c_top-nav-link-01").length) {
      newLi({
        class: "some-icon",
        link: {
          class: "some-link",
          href: $("#c_top-nav-link-01").attr("href"),
          title: "#"
        },
        icon: {
          class: "circle-icon-left",
          role: "img",
          "aria-label": "Category"
        },
        text: {
          class: "item-text",
          content: $("#c_top-nav-link-01").text()
        }
      }, mobileNav);
    }

    if ($("#c_top-nav-link-02").length) {
      newLi({
        class: "some-icon",
        link: {
          class: "some-link",
          href: $("#c_top-nav-link-02").attr("href"),
          title: "#"
        },
        icon: {
          class: "circle-icon-left",
          role: "img",
          "aria-label": "Category"
        },
        text: {
          class: "item-text",
          content: $("#c_top-nav-link-02").text()
        }
      }, mobileNav);
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="lia-slide-out-nav-menu">...</div>
<div class="slide-out-menu-links">
  <ul>
    <li>item one</li>
    <li>item two</li>
    <li>item three</li>
  </ul>
</div>
<a id="c_top-nav-link-01" href="page1.htm">Link 1</a>
<a id="c_top-nav-link-02" href="page2.htm">Link 2</a>

You can also use .clone() to clone the a element like so:

var newLink = $("#c_top-nav-link-01").clone();

You just have to remember to adjust the ID attribute before appending it.

This example performs a similar function, yet it builds out more structure. You could do this with a <template> too if you wanted. it would give you the HTML Structure and then you could copy it as needed and populate it.

Your if statements would always be true the way you were using them. If you want to check if an element with that selector exists, you need to call the length attribute. This will return 0 if no elements exist or 1 or higher. 0 will equate to false and 1 or more will equate to true


问:
Put reaction to bot message
```<code>// Embeds
client.on("messageCreate", message => {
  if(message.content == "sendtest") {
    let embed = new Discord.MessageEmbed()
    // Top
    .setAuthor("Informacja systemowa", "https://cdn.discordapp.com/attachments/933289723252850729/940680716574933022/Wymiar_Logo_kopia.png")
    .setTitle("Informacja")
    .setDescription("Test")
    // Settings
    .setColor("BLURPLE")
    // Field
    .addField("***Strona naszego serwera:***", "www.ViceMTA.pl", true)
    .addField("***Adress IP:***", "188.165.19.26:22018", true)
    // Zawartosc
    .setImage("https://cdn.discordapp.com/attachments/933289723252850729/940681715335184495/Banner.gif?size=69")
    // Copyright
    .setFooter(" \nVice MTA 2.0 © 2021 - 2023")
    message.channel.send({embeds : [ embed ]})
    //message.channel.send("|| @everyone ||")
  }
})
</code>```

How to make the bot add a reaction to its message?
As I have already tried in many ways and I can not cope with it, I am asking for effective help. I am a beginner

答:
just store when you send your embed in variable like that

const msg = await message.channel.send({ embeds: [embed] })
```
<p>then to react it use</p>
<pre class="lang-js prettyprint-override"><code>await msg.react('')
</code>```

Title: Put reaction to bot message

Body:
// Embeds
client.on("messageCreate", message => {
  if(message.content == "sendtest") {
    let embed = new Discord.MessageEmbed()
    // Top
    .setAuthor("Informacja systemowa", "https://cdn.discordapp.com/attachments/933289723252850729/940680716574933022/Wymiar_Logo_kopia.png")
    .setTitle("Informacja")
    .setDescription("Test")
    // Settings
    .setColor("BLURPLE")
    // Field
    .addField("***Strona naszego serwera:***", "www.ViceMTA.pl", true)
    .addField("***Adress IP:***", "188.165.19.26:22018", true)
    // Zawartosc
    .setImage("https://cdn.discordapp.com/attachments/933289723252850729/940681715335184495/Banner.gif?size=69")
    // Copyright
    .setFooter(" \nVice MTA 2.0 © 2021 - 2023")
    message.channel.send({embeds : [ embed ]})
    //message.channel.send("|| @everyone ||")
  }
})

How to make the bot add a reaction to its message?
As I have already tried in many ways and I can not cope with it, I am asking for effective help. I am a beginner

Body:
just store when you send your embed in variable like that

const msg = await message.channel.send({ embeds: [embed] })

then to react it use

await msg.react('')


问:
How can I migrate test cases with shared steps from TFS to Azure DevOps?
How can I migrate test cases with shared steps and shared parameters from TFS to Azure DevOps? I could migrate test cases but they didn't include the shared steps and shared parameters.</p>

答:
User this tool: https://marketplace.visualstudio.com/items?itemName=nkdagility.vsts-sync-migration

In the configuration.json file update below code, it will migrate test cases along with Shared steps and shared parameters

"WIQLQueryBit": "AND  [Microsoft.VSTS.Common.ClosedDate] = '' AND [System.WorkItemType] IN ('Test Case','Test Suite','Shared Steps','Shared Parameter')",


问:
How to set value if object exists - if not intialize and set object in javascript?
I have the following result:

```<code>const mainResult = { result: 1234}
</code>```

I have the following also:

```<code>const allResults = {};
</code>```

I want to set allResults.results.mainResult = mainResult;

However I won't know if allResults.results exists or not.  How do I create allResults.results as an object if it doesn't exist and set it to mainResults - or just set it if allResults.results.mainResults exists?

Is there a way to do this in one line?

答:
I don't know whether there is a genuine one-line solution, but I have a forced one-line solution, which is the combination of Logical nullish assignment (??=) and Logical AND (&&) operator

const mainResult = { result: 1234 }
const allResults = {};

(allResults.results ??= {}) && (allResults.results.mainResult = mainResult)

console.log(allResults)```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const mainResult = { result: 1234 }
const allResults = { results: { otherResult: 5678 } };

(allResults.results ??= {}) && (allResults.results.mainResult = mainResult)

console.log(allResults)</code>```

As @Bergi suggested, we could make it shorter

const mainResult = { result: 1234 }
const allResults = {};

(allResults.results ??= {}).mainResult = mainResult

console.log(allResults)```

Body:
I have the following result:

const mainResult = { result: 1234}

I have the following also:

const allResults = {};

I want to set allResults.results.mainResult = mainResult;

However I won't know if allResults.results exists or not.  How do I create allResults.results as an object if it doesn't exist and set it to mainResults - or just set it if allResults.results.mainResults exists?

Is there a way to do this in one line?

Body:
I don't know whether there is a genuine one-line solution, but I have a forced one-line solution, which is the combination of Logical nullish assignment (??=) and Logical AND (&&) operator

const mainResult = { result: 1234 }
const allResults = {};

(allResults.results ??= {}) && (allResults.results.mainResult = mainResult)

console.log(allResults)

const mainResult = { result: 1234 }
const allResults = { results: { otherResult: 5678 } };

(allResults.results ??= {}) && (allResults.results.mainResult = mainResult)

console.log(allResults)

As @Bergi suggested, we could make it shorter

const mainResult = { result: 1234 }
const allResults = {};

(allResults.results ??= {}).mainResult = mainResult

console.log(allResults)


问:
C: How can I create a 2d array that hold 2d arrays?
for example I have generated a "zone" of 1s and 0s in a 2x2 2d array . But i need to store 9 of these zones to access whenever from another 3x3 2d array "map". The zone arrays are randomly generated and need to stay the same once added to the 2d map array, so that I could "leave" a zone and come back and itd be the same. Kinda like an ASCII game

such that

```<code>int zone[2][2];
// fill zone array
int map[3][3];
map[0][0] = zone;
</code>```

答:
I think to make it simple you can use struct in c. It will be easier to manage and modify it with struct

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

struct Zone {
    int zone[2][2];
};

int main()
{
    struct Zone map[3][3];
    struct Zone zone1;
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            zone1.zone[i][j] = i + j; // putting some values for example
        }
    }
    map[0][0] = zone1;
}

</code>```

Body:
for example I have generated a "zone" of 1s and 0s in a 2x2 2d array . But i need to store 9 of these zones to access whenever from another 3x3 2d array "map". The zone arrays are randomly generated and need to stay the same once added to the 2d map array, so that I could "leave" a zone and come back and itd be the same. Kinda like an ASCII game

such that

int zone[2][2];
// fill zone array
int map[3][3];
map[0][0] = zone;

Body:
I think to make it simple you can use struct in c. It will be easier to manage and modify it with struct

#include <stdio.h>

struct Zone {
    int zone[2][2];
};

int main()
{
    struct Zone map[3][3];
    struct Zone zone1;
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            zone1.zone[i][j] = i + j; // putting some values for example
        }
    }
    map[0][0] = zone1;
}


问:
chrome send post request can't get request body
I send a post request to windows local service(c#) at http://127.0.0.1:13728.
When i open the website at chrome, my local service can't get request body.
Windows service code:

```<code>string recData = new StreamReader(request.InputStream).ReadToEnd();
</code>```

request:

request

request payload

The recData is null or empty.
When i open it at ie or other browser, it works fine.
The Chrome works fine before. But recently it suddenly doesn't work.
I searched a lot , but can't figure out why.

Please help.Thx.

答:
I find out why.
Because chrome 98 update, when request a private network, the browser will send a preflight first. But my local service ignore the preflight request and don't return anything. The preflight request status is always pending，so the really request don't send.

check this:
Private Network Access: introducing preflights

Body:
I send a post request to windows local service(c#) at http://127.0.0.1:13728.
When i open the website at chrome, my local service can't get request body.
Windows service code:

string recData = new StreamReader(request.InputStream).ReadToEnd();

request:

request

request payload

The recData is null or empty.
When i open it at ie or other browser, it works fine.
The Chrome works fine before. But recently it suddenly doesn't work.
I searched a lot , but can't figure out why.

Please help.Thx.


问:
Forward body from request to another url
I am wondering if someone might be able to help figure out how to pass a post body to another endpoint with cloudflare workers?
I am trying to get the incoming request post to post to url.</p>
```<code>const url = 'https://webhook.site/#!/b2f75ce2-7b9e-479a-b6f0-8934a89a3f3d'
const body = {
  results: ['default data to send'],
  errors: null,
  msg: 'I sent this to the fetch',
}

/**
 * gatherResponse awaits and returns a response body as a string.
 * Use await gatherResponse(..) in an async function to get the response body
 * @param {Response} response
 */
async function gatherResponse(response) {
  const { headers } = response
  const contentType = headers.get('content-type') || ''
  if (contentType.includes('application/json')) {
    return JSON.stringify(await response.json())
  } else if (contentType.includes('application/text')) {
    return response.text()
  } else if (contentType.includes('text/html')) {
    return response.text()
  } else {
    return response.text()
  }
}

async function handleRequest() {
  const init = {
    body: JSON.stringify(body),
    method: 'POST',
    headers: {
      'content-type': 'application/json;charset=UTF-8',
    },
  }
  const response = await fetch(url, init)
  const results = await gatherResponse(response)
  return new Response(results, init)
}
addEventListener('fetch', (event) => {
  return event.respondWith(handleRequest())
})
</code>```

答:
I created a worker at https://tight-art-0743.ctohm.workers.dev/, which basically forwards your POST request's body to a public requestbin. You can check what is it receiving at: https://requestbin.com/r/en5k768mcp4x9/24tqhPJw86mt2WjKRMbmt75FMH9

```<code>addEventListener("fetch", (event) => {
  event.respondWith(
    handleRequest(event.request).catch(
      (err) => new Response(err.stack, { status: 500 })
    )
  );
});

async function handleRequest(request) {
  let {method,headers}=request,
      url=new URL(request.url)
  // methods other than POST will return early
  if(method!=='POST') return new Response(`Your request method was ${method}`);

  const forwardRequest=new Request("https://en5k768mcp4x9.x.pipedream.net/", request)
  forwardRequest.headers.set('X-Custom-Header','hey!')
  return fetch(forwardRequest)
}
</code>```

You can see it working with a simple CURL request

```<code>curl --location --request POST 'https://tight-art-0743.ctohm.workers.dev/' \
--header 'Content-Type: application/json' \
--data-raw '{"environment": {"name": "Sample Environment Name (required)"}}'
</code>```

Two things worth noting, in the worker's code:

I'm passing the original request as the init parameter, through which original headers and body are transparently forwarded to the requestbin, also allowing for some extra header manipulation if neeeded.

In this example I'm not actually doing anything with the request body. Therefore there's no need to await it. You just connect incoming and outgoing streams and let them deal with each other.

Another example: let's add a /csv route. Requests starting with /csv will not forward your POST body. Instead they will download a remote CSV attachment and POST it to the requestbin. Again, we aren't awaiting for the actual CSV contents. We pass a handle to the response body to the forwarding request

```<code>async function handleRequest(request) {
  let {method,headers}=request,
    url=new URL(request.url)
  if(method!=='POST')     return new Response(`Your request method was ${method}`);

  const forwardRequest=new Request("https://en5k768mcp4x9.x.pipedream.net/",request)
  if(url.pathname.includes('/csv')) {
    const remoteSource=`https://cdn.wsform.com/wp-content/uploads/2018/09/country_full.csv`,
          remoteResponse=await fetch(remoteSource)
    return fetch(forwardRequest,{body:remoteResponse.body})
  }
  forwardRequest.headers.set('X-Custom-Header','hey!')
  return fetch(forwardRequest)
}
</code>```

While your code should theoretically work, the fact that you're unwrapping the response means your worker could be aborted due to hitting time limits, or CPU, or memory. On the contrary, when using the streams based approach,
your worker's execution finishes as soon as it returns the forwarding fetch. Even if the outgoing POST is still running, this isn't subject to CPU or time limits.

Body:
I am wondering if someone might be able to help figure out how to pass a post body to another endpoint with cloudflare workers?
I am trying to get the incoming request post to post to url.

const url = 'https://webhook.site/#!/b2f75ce2-7b9e-479a-b6f0-8934a89a3f3d'
const body = {
  results: ['default data to send'],
  errors: null,
  msg: 'I sent this to the fetch',
}

/**
 * gatherResponse awaits and returns a response body as a string.
 * Use await gatherResponse(..) in an async function to get the response body
 * @param {Response} response
 */
async function gatherResponse(response) {
  const { headers } = response
  const contentType = headers.get('content-type') || ''
  if (contentType.includes('application/json')) {
    return JSON.stringify(await response.json())
  } else if (contentType.includes('application/text')) {
    return response.text()
  } else if (contentType.includes('text/html')) {
    return response.text()
  } else {
    return response.text()
  }
}

async function handleRequest() {
  const init = {
    body: JSON.stringify(body),
    method: 'POST',
    headers: {
      'content-type': 'application/json;charset=UTF-8',
    },
  }
  const response = await fetch(url, init)
  const results = await gatherResponse(response)
  return new Response(results, init)
}
addEventListener('fetch', (event) => {
  return event.respondWith(handleRequest())
})

Body:
I created a worker at https://tight-art-0743.ctohm.workers.dev/, which basically forwards your POST request's body to a public requestbin. You can check what is it receiving at: https://requestbin.com/r/en5k768mcp4x9/24tqhPJw86mt2WjKRMbmt75FMH9

addEventListener("fetch", (event) => {
  event.respondWith(
    handleRequest(event.request).catch(
      (err) => new Response(err.stack, { status: 500 })
    )
  );
});

async function handleRequest(request) {
  let {method,headers}=request,
      url=new URL(request.url)
  // methods other than POST will return early
  if(method!=='POST') return new Response(`Your request method was ${method}`);

  const forwardRequest=new Request("https://en5k768mcp4x9.x.pipedream.net/", request)
  forwardRequest.headers.set('X-Custom-Header','hey!')
  return fetch(forwardRequest)
}

You can see it working with a simple CURL request

curl --location --request POST 'https://tight-art-0743.ctohm.workers.dev/' \
--header 'Content-Type: application/json' \
--data-raw '{"environment": {"name": "Sample Environment Name (required)"}}'

Two things worth noting, in the worker's code:

I'm passing the original request as the init parameter, through which original headers and body are transparently forwarded to the requestbin, also allowing for some extra header manipulation if neeeded.

In this example I'm not actually doing anything with the request body. Therefore there's no need to await it. You just connect incoming and outgoing streams and let them deal with each other.

Another example: let's add a /csv route. Requests starting with /csv will not forward your POST body. Instead they will download a remote CSV attachment and POST it to the requestbin. Again, we aren't awaiting for the actual CSV contents. We pass a handle to the response body to the forwarding request

async function handleRequest(request) {
  let {method,headers}=request,
    url=new URL(request.url)
  if(method!=='POST')     return new Response(`Your request method was ${method}`);

  const forwardRequest=new Request("https://en5k768mcp4x9.x.pipedream.net/",request)
  if(url.pathname.includes('/csv')) {
    const remoteSource=`https://cdn.wsform.com/wp-content/uploads/2018/09/country_full.csv`,
          remoteResponse=await fetch(remoteSource)
    return fetch(forwardRequest,{body:remoteResponse.body})
  }
  forwardRequest.headers.set('X-Custom-Header','hey!')
  return fetch(forwardRequest)
}

While your code should theoretically work, the fact that you're unwrapping the response means your worker could be aborted due to hitting time limits, or CPU, or memory. On the contrary, when using the streams based approach,
your worker's execution finishes as soon as it returns the forwarding fetch. Even if the outgoing POST is still running, this isn't subject to CPU or time limits.


问:
Can't resolve @babel/runtime/helpers/esm* in react-window
I'm using the react-window ^1.8.6 version ( under my dependencies). When I try to yarn build my project, I'm getting the following errors.

ERROR in ./node_modules/react-window/dist/index.esm.js
Module not found: Error: Can't resolve '@babel/runtime/helpers/esm/assertThisInitialized' in '/Users/xxxxxx/Workspace/xxxxx/component-library/node_modules/react-window/dist'
@ ./node_modules/react-window/dist/index.esm.js 3:0-86 160:60-82 160:83-105 164:18-40 164:41-63 1066:60-82 1066:83-105 1070:18-40 1070:41-63
@ ./src/components/PDFViewer/Viewer.tsx
@ ./src/components/PDFViewer/PDFViewer.tsx
@ ./src/components/PDFViewer/index.ts
@ ./src/components/DocumentViewer/DocumentViewer.tsx
@ ./src/components/DocumentViewer/index.ts
@ ./src/index.ts

Full set as below

yarn version 1.22.17

npm version 8.1.2

node version v16.13.2

webpack version ^4.44.1

My Webpack config looks like

```<code>const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry: './src/index.ts',
    mode: 'production',
    output: {
        path: path.resolve(__dirname, 'lib'),
        filename: 'the-component-library.js',
        libraryTarget: 'umd',
        globalObject: 'this',
        library: 'theComponentLibrary',
    },
    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/,
                exclude: /(node_modules|bower_components)/,
                use: ['ts-loader'],
            },
            {
                test: /\.(scss|css)$/,
                use: ['style-loader', 'css-loader', 'sass-loader'],
            },
            {
                test: /\.svg$/,
                use: ['@svgr/webpack'],
            },
            {
                test: /\.(gif)$/i,
                use: [
                    {
                        loader: 'file-loader',
                    },
                ],
            },
        ],
    },
    externals: [
        {
            react: 'react',
        },
        '@material-ui/core',
        '@material-ui/lab',
        /@material-ui\/core\/*./,
        /@material-ui\/lab\/*./,
        'react-simple-gestures',
        'react-dropzone',
    ],
    resolve: {
        extensions: ['.ts', '.tsx'],
    },
    plugins: [
        // Ignore all locale files of day.js
        new webpack.IgnorePlugin(/^\.\/locale$/),
    ],
};
</code>```

How can I resolve this issue?

答: Oh, I could resolve the issue by changing the Webpack config as below

Body:
I'm using the react-window ^1.8.6 version ( under my dependencies). When I try to yarn build my project, I'm getting the following errors.

ERROR in ./node_modules/react-window/dist/index.esm.js
Module not found: Error: Can't resolve '@babel/runtime/helpers/esm/assertThisInitialized' in '/Users/xxxxxx/Workspace/xxxxx/component-library/node_modules/react-window/dist'
@ ./node_modules/react-window/dist/index.esm.js 3:0-86 160:60-82 160:83-105 164:18-40 164:41-63 1066:60-82 1066:83-105 1070:18-40 1070:41-63
@ ./src/components/PDFViewer/Viewer.tsx
@ ./src/components/PDFViewer/PDFViewer.tsx
@ ./src/components/PDFViewer/index.ts
@ ./src/components/DocumentViewer/DocumentViewer.tsx
@ ./src/components/DocumentViewer/index.ts
@ ./src/index.ts

Full set as below

yarn version 1.22.17

npm version 8.1.2

node version v16.13.2

webpack version ^4.44.1

My Webpack config looks like

const path = require('path');
const webpack = require('webpack');

module.exports = {
    entry: './src/index.ts',
    mode: 'production',
    output: {
        path: path.resolve(__dirname, 'lib'),
        filename: 'the-component-library.js',
        libraryTarget: 'umd',
        globalObject: 'this',
        library: 'theComponentLibrary',
    },
    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/,
                exclude: /(node_modules|bower_components)/,
                use: ['ts-loader'],
            },
            {
                test: /\.(scss|css)$/,
                use: ['style-loader', 'css-loader', 'sass-loader'],
            },
            {
                test: /\.svg$/,
                use: ['@svgr/webpack'],
            },
            {
                test: /\.(gif)$/i,
                use: [
                    {
                        loader: 'file-loader',
                    },
                ],
            },
        ],
    },
    externals: [
        {
            react: 'react',
        },
        '@material-ui/core',
        '@material-ui/lab',
        /@material-ui\/core\/*./,
        /@material-ui\/lab\/*./,
        'react-simple-gestures',
        'react-dropzone',
    ],
    resolve: {
        extensions: ['.ts', '.tsx'],
    },
    plugins: [
        // Ignore all locale files of day.js
        new webpack.IgnorePlugin(/^\.\/locale$/),
    ],
};

How can I resolve this issue?


问:
Git branch and ls
I'm not sure if this is the right place to ask this, please redirect me if not.

I'm new to git and while learning it I stumbled upon this.
How does git branch branchName and 'ls' work with each other.
For eg:
If I have a master and test branch and test branch has an extra testFile when compared to master branch.
Now, while in the master branch, if I ls, I'll wont see the testFile but after switching to the test branch and ls, I'll see the testFile

```<code>kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git branch
  master
* test
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git checkout master
M   editor/editor_parts/syntax/operator_syntax.js
Switched to branch 'master'
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ ls
cgi-bin     index.php                    misc           underConstruction
editor      jquery-1.5.2.min.js          php.php        userManage
fileManage  jquery-ui-1.8.11.custom.css  projectManage  userPages
images      login                        test.php
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git checkout test
M   editor/editor_parts/syntax/operator_syntax.js
Switched to branch 'test'
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ ls
cgi-bin     index.php                    misc           test.php
editor      jquery-1.5.2.min.js          php.php        underConstruction
fileManage  jquery-ui-1.8.11.custom.css  projectManage  userManage
images      login                        testFile.txt   userPages
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$
</code>```

But pwd from both branches shows the same location.

So, how does switching branches change the output of ls ( which as I understand is a function of linux) ?

答:
Git, unlike in SVN what you know keeps branches in different directories, keeps only the current working branch in the repository directory.

All the branches (Actually, all the objects) are stored inside the '.git' folder in the root of the repo and only the files belonging to the specific branch are present while you have checked out a specific branch. (and those files that are not added to the repo)

ContentLicense: CC BY-SA 3.0

Title: Git branch and ls

Body:
I'm not sure if this is the right place to ask this, please redirect me if not.

I'm new to git and while learning it I stumbled upon this.
How does git branch branchName and 'ls' work with each other.
For eg:
If I have a master and test branch and test branch has an extra testFile when compared to master branch.
Now, while in the master branch, if I ls, I'll wont see the testFile but after switching to the test branch and ls, I'll see the testFile

kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git branch
  master
* test
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git checkout master
M   editor/editor_parts/syntax/operator_syntax.js
Switched to branch 'master'
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ ls
cgi-bin     index.php                    misc           underConstruction
editor      jquery-1.5.2.min.js          php.php        userManage
fileManage  jquery-ui-1.8.11.custom.css  projectManage  userPages
images      login                        test.php
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git checkout test
M   editor/editor_parts/syntax/operator_syntax.js
Switched to branch 'test'
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ ls
cgi-bin     index.php                    misc           test.php
editor      jquery-1.5.2.min.js          php.php        underConstruction
fileManage  jquery-ui-1.8.11.custom.css  projectManage  userManage
images      login                        testFile.txt   userPages
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$

But pwd from both branches shows the same location.

So, how does switching branches change the output of ls ( which as I understand is a function of linux) ?


问:
Android Studio 3.1.3 - Unresolved reference: R - Kotlin
I am new to kotlin, i have converted some code from java but it seems like there's something wrong, The R in findViewById(R.id.my_id) is highlighted in red and it shows this message : "Unresolved reference: R".. I've been looking for a solution but i seem not to figure it out, So what should i do?
Here's a screenshot :

答: I had same problem while using auto-manifest plugin. Adding AndroidManifest.xml explicitly solved the problem to me.


问:
editing git patch gives "Your edited hunk does not apply"
I'm adding a file interactively:

```<code>git add ../../template/panels/panel-reports.php -p
diff --git a/template/panels/panel-reports.php b/template/panels/panel-reports.php
index 5482228..48d2901 100644
--- a/template/panels/panel-reports.php
+++ b/template/panels/panel-reports.php
@@ -214,6 +214,8 @@

                        <a class="addCategory"></a>
                        <a class="removeCategory"></a>
+                       <a class="addDocument"></a>
+                       <a class="checkTool"></a>

                        <div class="categoriesList"></div>
                        <div class="documentsList"></div>
Stage this hunk [y,n,q,a,d,/,e,?]? e
</code>```

ps: those are the only modified lines here

I want to remove

```<code>+                       <a class="checkTool"></a>
</code>```

so I edit like this:

```<code># Manual hunk edit mode -- see bottom for a quick guide
@@ -214,6 +214,7 @@

                                                <a class="addCategory"></a>
                                                <a class="removeCategory"></a>
+                                               <a class="addDocument"></a>

                                                <div class="categoriesList"></div>
                                                <div class="documentsList"></div>
# ---
# To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.
</code>```

and git refused it:

```<code>error: patch failed: template/panels/panel-reports.php:214
error: template/panels/panel-reports.php: patch does not apply
Your edited hunk does not apply. Edit again (saying "no" discards!) [y/n]?
</code>```

To me I don't see any error or ambiguity in what I wrote, so where Am I wrong?

答:
My up to date version Git, 2.33.1.windows.1, git add -p  does not have a subcommand s, so I used e.

Error Your edited hunk does not apply is because I misunderstood its bottom hints:

```<code># To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.
</code>```

https://git-scm.com/docs/git-add#_editing_patches
gives a more detailed introduction:

added content

Added content is represented by lines beginning with "+". You can prevent staging any addition lines by deleting them. (delete lines, not "+" mark. )

removed content

Removed content is represented by lines beginning with "-". You can prevent staging their removal by converting the "-" to a " " (space).  (replace "-" mark with a " " space mark)

modified content

Modified content is represented by "-" lines (removing the old content) followed by "+" lines (adding the replacement content). You can prevent staging the modification by converting "-" lines to " ", and removing "+" lines. Beware that modifying only half of the pair is likely to introduce confusing changes to the index. (combination of the former two)

And nothing else! no need to modify numbers between @@ @@,

Body:
I'm adding a file interactively:

git add ../../template/panels/panel-reports.php -p
diff --git a/template/panels/panel-reports.php b/template/panels/panel-reports.php
index 5482228..48d2901 100644
--- a/template/panels/panel-reports.php
+++ b/template/panels/panel-reports.php
@@ -214,6 +214,8 @@

+
+

Stage this hunk [y,n,q,a,d,/,e,?]? e

ps: those are the only modified lines here

I want to remove

+

so I edit like this:

# Manual hunk edit mode -- see bottom for a quick guide
@@ -214,6 +214,7 @@

+

# ---
# To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.

and git refused it:

error: patch failed: template/panels/panel-reports.php:214
error: template/panels/panel-reports.php: patch does not apply
Your edited hunk does not apply. Edit again (saying "no" discards!) [y/n]?

To me I don't see any error or ambiguity in what I wrote, so where Am I wrong?

Body:
My up to date version Git, 2.33.1.windows.1, git add -p  does not have a subcommand s, so I used e.

Error Your edited hunk does not apply is because I misunderstood its bottom hints:

# To remove '-' lines, make them ' ' lines (context).
# To remove '+' lines, delete them.
# Lines starting with # will be removed.

https://git-scm.com/docs/git-add#_editing_patches
gives a more detailed introduction:

added content

Added content is represented by lines beginning with "+". You can prevent staging any addition lines by deleting them. (delete lines, not "+" mark. )

removed content

Removed content is represented by lines beginning with "-". You can prevent staging their removal by converting the "-" to a " " (space).  (replace "-" mark with a " " space mark)

modified content

Modified content is represented by "-" lines (removing the old content) followed by "+" lines (adding the replacement content). You can prevent staging the modification by converting "-" lines to " ", and removing "+" lines. Beware that modifying only half of the pair is likely to introduce confusing changes to the index. (combination of the former two)

And nothing else! no need to modify numbers between @@ @@,


问:
one onChange input, wrongly modifies other three tags content
I have the next state:

```<code>const [social_networks, setSocial_networks] = useState([
    {
      social_account_type: "personal",
      social_network: "linkedin",
      handle: "",
      content: ""
    },
    {
      social_account_type: "company",
      social_network: "twitter",
      handle: "",
      content: ""
    },
    {
      social_account_type: "personal",
      social_network: "webpage",
      handle: "",
      content: ""
    }
])
</code>```

In the parent component I declare the function:

```<code>const handleInputChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...social_networks];
    list[index][name] = value;
    setSocial_networks(list);
  };
</code>```

Set this to the children in the next code:

```<code>social_networks.map((social_network, idx) => {
                                  if (social_network.social_account_type == "personal") return <div key={idx}><AccountsPill handle={social_network.handle} social={social_network.social_network} content={social_network.handle} index={idx} handleInputChange={handleInputChange} />  </div>
                                })
</code>```

And into my child component I have the next code:

```<code><div className="row m-0">
    <div className="svg-container col-md-1">
        <BrowserIcon color="#868E96" />
    </div>
    <input type="text" className="col-md-11 set-account-input" placeholder=
    {"www."+props.social+".com"} name="handle" id="handle" defaultValue={props.handle}
    onChange={e => props.handleInputChange(e, props.index)} />
</div>
<div className="row m-0">
       <div className="svg-container col-md-1">
           <AtIcon color="#868E96" />
       </div>
       <input type="text" className="col-md-11 set-account-input" placeholder="MyUsername"
       name="content" id="content" defaultValue={props.content} onChange={e =>
       props.handleInputChange(e, props.index)} />
</div>
</code>```

The page show me like that:
after rendering frontpage

When I change the input.Content works fine:
input.name=content change

But, if I change the input.name=handle , change the other input too:
input.name=handle change

I tried to make two differents handleChange functions, change the props.name, add the props.id, but does'nt works yet.

答:
I think your problem is that const list = [...social_networks]; shallow copies the state array, so it's really just an array of the original state objects. Try instead:

```<code>const handleInputChange = (e, index) => {
  const { name, value } = e.target;
  const list = social_networks.map((social, i)=>{
    if(index === i){
      return {...social, [name]: value}
    }
    return {...social}
  })
  setSocial_networks(list);
};
</code>```

Body:
I have the next state:

const [social_networks, setSocial_networks] = useState([
    {
      social_account_type: "personal",
      social_network: "linkedin",
      handle: "",
      content: ""
    },
    {
      social_account_type: "company",
      social_network: "twitter",
      handle: "",
      content: ""
    },
    {
      social_account_type: "personal",
      social_network: "webpage",
      handle: "",
      content: ""
    }
])

In the parent component I declare the function:

const handleInputChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...social_networks];
    list[index][name] = value;
    setSocial_networks(list);
  };

Set this to the children in the next code:

social_networks.map((social_network, idx) => {
                                  if (social_network.social_account_type == "personal") return
<AccountsPill handle={social_network.handle} social={social_network.social_network} content={social_network.handle} index={idx} handleInputChange={handleInputChange} />

                                })

And into my child component I have the next code:

        <BrowserIcon color="#868E96" />

    <input type="text" className="col-md-11 set-account-input" placeholder=
    {"www."+props.social+".com"} name="handle" id="handle" defaultValue={props.handle}
    onChange={e => props.handleInputChange(e, props.index)} />

           <AtIcon color="#868E96" />

       <input type="text" className="col-md-11 set-account-input" placeholder="MyUsername"
       name="content" id="content" defaultValue={props.content} onChange={e =>
       props.handleInputChange(e, props.index)} />

The page show me like that:
after rendering frontpage

When I change the input.Content works fine:
input.name=content change

But, if I change the input.name=handle , change the other input too:
input.name=handle change

I tried to make two differents handleChange functions, change the props.name, add the props.id, but does'nt works yet.

Body:
I think your problem is that const list = [...social_networks]; shallow copies the state array, so it's really just an array of the original state objects. Try instead:

const handleInputChange = (e, index) => {
  const { name, value } = e.target;
  const list = social_networks.map((social, i)=>{
    if(index === i){
      return {...social, [name]: value}
    }
    return {...social}
  })
  setSocial_networks(list);
};


问:
mat tree parent without children
How can i display parent that has no children, as parent with children? i want parent without children has same design as parent with children.
stackblitz</p>
```<code>interface FoodNode {
  name: string;
  children?: FoodNode[];
}

const TREE_DATA: FoodNode[] = [
  {
    name: 'Fruit',
    children: [{name: 'Apple'}, {name: 'Banana'}, {name: 'Fruit loops'}],
  },
  {
    name: 'Vegetables',
    children: [
      {
        name: 'Green',
        children: [{name: 'Broccoli'}, {name: 'Brussels sprouts'}],
      },
      {
        name: 'Orange',
        children: [{name: 'Pumpkins'}, {name: 'Carrots'}],
      },
    ],
  },
  {
    name: 'testing',
  },
];

  treeControl = new NestedTreeControl<FoodNode>(node => node.children);
  dataSource = new MatTreeNestedDataSource<FoodNode>();

  constructor() {
    this.dataSource.data = TREE_DATA;
  }

  hasChild = (_: number, node: FoodNode) => !!node.children && node.children.length > 0;
</code>```

答:
Do you then mean like... a regular list then? https://material.angular.io/components/list/overview

Nesting parent-child creates all the relations for how the tree is rendered e.g if there is no child, how do we know how to indent tree items? Or how do we know which element should be collapsible etc. If you want to keep same appearance and functioning, but because of data structure (nested arrays and object) you'd like to avoid tree structure I would suggest to take your time and get familiar how to use such a data structure - no point in reinventing the wheel.

Title: mat tree parent without children

Body:
How can i display parent that has no children, as parent with children? i want parent without children has same design as parent with children.
stackblitz

interface FoodNode {
  name: string;
  children?: FoodNode[];
}

const TREE_DATA: FoodNode[] = [
  {
    name: 'Fruit',
    children: [{name: 'Apple'}, {name: 'Banana'}, {name: 'Fruit loops'}],
  },
  {
    name: 'Vegetables',
    children: [
      {
        name: 'Green',
        children: [{name: 'Broccoli'}, {name: 'Brussels sprouts'}],
      },
      {
        name: 'Orange',
        children: [{name: 'Pumpkins'}, {name: 'Carrots'}],
      },
    ],
  },
  {
    name: 'testing',
  },
];

  treeControl = new NestedTreeControl<FoodNode>(node => node.children);
  dataSource = new MatTreeNestedDataSource<FoodNode>();

  constructor() {
    this.dataSource.data = TREE_DATA;
  }

  hasChild = (_: number, node: FoodNode) => !!node.children && node.children.length > 0;


问:
How To Fix UI in Unity
I would like my UI to be like the first picture, but when I expand it, it turns out like the second picture. How can I fix this?

答: I set my aspect ratio to a fixed one (16:9) and changed the UI Scale Mode to scale with screen size, the match slider below (for resolution) to .5, which seemed to do the trick</p>

Title: How To Fix UI in Unity


问:
how to pass dynamic URL to curl in php - getting error 1
I'm trying to pass a $url to curl using a function.
the URL is built with a variable in it in the following method:

```<code>a.php // main page, include (a.php, b.php)
b.php // dynamic string function
c.php // curl function
</code>```

I build a dynamic string successfully using sessions data // $_SESSION["input"]
myDynamicstringfunction set a string by multiple sessions input values.

```<code>$dval = myDynamicstringfunction();
echo $dval;
// render correctly to: "-e5 -g6 -g7"
</code>```

the $dval value is a string that resolve as expected. the $url is:

```<code>$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 $dval";
</code>```

The $url is render correctly with the

```<code>echo $url;
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";
</code>```

I pass the $url to the curl function using:

```<code>$r = mycUrlfunction($url);
</code>```

The curl function I use:

```<code>function singleRequest($url){
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
$curly = curl_exec($ch);
if ($curly == FALSE){
    die("cURL Error: " . curl_error($ch));
}

$result = json_decode($curly, true);

// close cURL resource, and free up system resources
curl_close($ch);

echo '```';
return ($result);
}
```
<p>The above get me an error (curl 1) - CURLE_UNSUPPORTED_PROTOCOL (1)</p>
<p>I have tried many things to get the $url to work with no success.
if I set the $url value manually without the $dval variable like this:</p>
```$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";
```

The code works just fine and I get the correct results from the API call.
I tried using different quotes, {}, [], encoding to ASCII, vprintf(), and other solutions with no success.

答:
the problem was with constructing the dynamic variable $dynamicstring of the URL
initially used

```<code>$dynamicstring= "-a" . $_SESSION["a"]." -b".$_SESSION['b']." -c".$_SESSION['c']." -d".$_SESSION['d']."<br>";
</code>```

this have a few problems

when using echo it render the expected output correctly

it have a "
" at the end

it have the wrong structure

the correct way to construct the $dynamicstring is to use {}

```<code>$dynamicstring= "-a{$_SESSION["a"]} -b{$_SESSION['b']} -c{$_SESSION['c']} -d{$_SESSION['d']}";
</code>```

Body:
I'm trying to pass a $url to curl using a function.
the URL is built with a variable in it in the following method:

a.php // main page, include (a.php, b.php)
b.php // dynamic string function
c.php // curl function

I build a dynamic string successfully using sessions data // $_SESSION["input"]
myDynamicstringfunction set a string by multiple sessions input values.

$dval = myDynamicstringfunction();
echo $dval;
// render correctly to: "-e5 -g6 -g7"

the $dval value is a string that resolve as expected. the $url is:

$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 $dval";

The $url is render correctly with the

echo $url;
$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";

I pass the $url to the curl function using:

$r = mycUrlfunction($url);

The curl function I use:

function singleRequest($url){
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
$curly = curl_exec($ch);
if ($curly == FALSE){
    die("cURL Error: " . curl_error($ch));
}

$result = json_decode($curly, true);

// close cURL resource, and free up system resources
curl_close($ch);

echo '
';
return ($result);
}

The above get me an error (curl 1) - CURLE_UNSUPPORTED_PROTOCOL (1)

I have tried many things to get the $url to work with no success.
if I set the $url value manually without the $dval variable like this:

$url = "https://someurl.com/a/b?dc=-cv1.5 -a1 -b2 -c3 -d4 -e5 -g6 -g7";

The code works just fine and I get the correct results from the API call.
I tried using different quotes, {}, [], encoding to ASCII, vprintf(), and other solutions with no success.

Body:
the problem was with constructing the dynamic variable $dynamicstring of the URL
initially used

$dynamicstring= "-a" . $_SESSION["a"]." -b".$_SESSION['b']." -c".$_SESSION['c']." -d".$_SESSION['d']."<br>";

this have a few problems

when using echo it render the expected output correctly

it have a "<br>" at the end

it have the wrong structure

the correct way to construct the $dynamicstring is to use {}

$dynamicstring= "-a{$_SESSION["a"]} -b{$_SESSION['b']} -c{$_SESSION['c']} -d{$_SESSION['d']}";


问:
How to solve Invalid Hook Call error when using Material UI?
I'm new at coding and I'm having the following error when adding a MaterialUI Icon

```<code>import PersonIcon from '@mui/icons-material/Person';

function Header() {
    return (

<div>
<PersonIcon />
<h2>Header file</h2>

</div>

    );
}

export default Header;

</code>```

When adding  I get the following error:

Please notice that I have installed MaterialUI Core and also MaterialUI Icons
When not adding  everything works fine

答:
Try this

```<code>npm uninstall @material-ui/core @material-ui/icons
</code>```

Then

```<code>npm i @material-ui/core @material-ui/icons
</code>```

Restart the React server

```<code>npm start
// OR
yarn start
</code>```

Let me know if it works, Good Luck

Body:
I'm new at coding and I'm having the following error when adding a MaterialUI Icon

import PersonIcon from '@mui/icons-material/Person';

function Header() {
    return (

<PersonIcon />

Header file

    );
}

export default Header;

When adding  I get the following error:

Please notice that I have installed MaterialUI Core and also MaterialUI Icons
When not adding  everything works fine

Body:
Try this

npm uninstall @material-ui/core @material-ui/icons

Then

npm i @material-ui/core @material-ui/icons

Restart the React server

npm start
// OR
yarn start

Let me know if it works, Good Luck


问:
ld: framework not found url_launcher on Flutter, xcode 13.1
I started facing an issue of

framework not found

, when upgraded flutter from 2.8.1 to 2.10.1.
I'm working on mac m1
I tried pub and pod clean with complete cache by using below command and also tried fresh setup on new system

```<code>flutter clean
pod cache clean 'FortifySec' --all
 rm -rf Pods
pod deintegrate
rm -rf ~/Library/Developer/Xcode/DerivedData/*
rm -rf ~/Library/Caches/CocoaPods
rm -rf ../pubspec.lock
rm -rf .symlinks
pod cache clean --all
flutter pub cache clean
</code>```

答:
I'm on xcode 13.1, resolved my issue by just removing frameworks entry in build setting.

```<code>xcode -> target -> Build settings-> Other Linker flag
</code>```

Removed all entry for thoes it was showing error.

Body:
I started facing an issue of

framework not found

, when upgraded flutter from 2.8.1 to 2.10.1.
I'm working on mac m1
I tried pub and pod clean with complete cache by using below command and also tried fresh setup on new system

flutter clean
pod cache clean 'FortifySec' --all
 rm -rf Pods
pod deintegrate
rm -rf ~/Library/Developer/Xcode/DerivedData/*
rm -rf ~/Library/Caches/CocoaPods
rm -rf ../pubspec.lock
rm -rf .symlinks
pod cache clean --all
flutter pub cache clean

Body:
I'm on xcode 13.1, resolved my issue by just removing frameworks entry in build setting.

xcode -> target -> Build settings-> Other Linker flag

Removed all entry for thoes it was showing error.


问:
How do I delete all messages in a discord channel with js?
Using discord.py in python, I can do the following and it'll slowly delete all messages in a channel even if they're more than 2 weeks old:

async def clear(self, ctx):

    length = await ctx.message.channel.history(limit=999).flatten()
    num = len(length)
    div = 100
    target = [num // div(1 if x < num % div else 0) for x in range(div)]

    for tar in target:
        async for message in ctx.message.channel.history(limit=tar):
            await ctx.message.channel.delete_messages([message])
```

How would I go about doing the same thing in javascript discord.js?

答:
You can use

message.channel.clone()
.then(() => message.channel.delete().catch(() => null)), 10000))
```

instead it will create new channel with same permissions and etc..

Body:
Using discord.py in python, I can do the following and it'll slowly delete all messages in a channel even if they're more than 2 weeks old:

async def clear(self, ctx):

    length = await ctx.message.channel.history(limit=999).flatten()
    num = len(length)
    div = 100
    target = [num // div(1 if x < num % div else 0) for x in range(div)]

    for tar in target:
        async for message in ctx.message.channel.history(limit=tar):
            await ctx.message.channel.delete_messages([message])

How would I go about doing the same thing in javascript discord.js?

Body:
You can use

message.channel.clone()
.then(() => message.channel.delete().catch(() => null)), 10000))

instead it will create new channel with same permissions and etc..


问:
Could not load wrapper properties from 'C:\Users\AndroidStudioProjects\Test\gradle\wrapper\gradle-wrapper.properties'
Could not load wrapper properties from 'C:\Users\AndroidStudioProjects\Test\gradle\wrapper\gradle-wrapper.properties'.

Am getting this error when I created new project in Android studio.

答:
```<code>C:\Users\Pushpa\.android\cache
</code>```

By deleting this worked for me.

Body:
C:\Users\Pushpa\.android\cache

By deleting this worked for me.


问:
Jackson ObjectMapper in JunitTest5 returns source cannot be null
Preamble: I'm learning Java (Spring) with TDD. I have a work-in-progress project here:

Branch: https://github.com/sineverba/online-banking-backend/tree/add-controller

Last commit: https://github.com/sineverba/online-banking-backend/commit/69d643eb81748656200f007bedf213d9352b079a

I'm introducing test for POST call (see add-controller branch to get current state of work).

So, in new controller I added the post call and in the test I wrote:

        var id = 1L;
        var transactionToSave = validBankAccountTransactionsEntity(new BigDecimal(99.99), "First Transaction");
        var savedTransaction = validBankAccountTransactionsEntity(id, new BigDecimal(99.99), "First Transaction");

        when(bankAccountTransactionsService.post(transactionToSave))
        .thenReturn(savedTransaction);

        mvc.perform(
                post("/api/v1/bank-account-transactions/")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(transactionToSave))
                )
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.id", is((int) id)))
        .andExpect(jsonPath("$.amount", is(transactionToSave.getAmount())));
```
<p>I got the error</p>
<pre class="lang-java prettyprint-override"><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: source cannot be null
</code>```

And the issue is with

[...]
objectMapper.writeValueAsBytes(transactionToSave)
[...]
```
<p>And in particular the error is</p>
<pre class="lang-java prettyprint-override"><code>Caused by: java.lang.IllegalArgumentException: source cannot be null
    at org.modelmapper.internal.util.Assert.notNull(Assert.java:53)
    at org.modelmapper.ModelMapper.map(ModelMapper.java:404)
    at com.bitbank.controllers.v1.BankAccountTransactionsController.convertToDto(BankAccountTransactionsController.java:54)
</code>```

So, at the end, seems error caused by convertToDto method called by post method of controller: return convertToDto(savedBankAccountTransactionsEntity);.

Cannot explain my issue, I don't know how resolve it.

I'm following a guide: https://www.mattianatali.it/come-sviluppare-rest-api-in-tdd-con-spring-boot/

You can see the author wrote same code (of course different example), about at half of page, you can see:

@Test
    void create_shouldSaveTheVehicle() throws Exception {
        var vehicleId = 1L;
        var vehicleToSave = aValidVehicle();

        when(vehicleService.save(vehicleToSave))
                .thenReturn(
                        vehicleToSave
                                .toBuilder()
                                .id(vehicleId)
                                .build()
                );

        mvc.perform(
                post("/api/v1/vehicles")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(vehicleToSave))
        )
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.id", is((int) vehicleId)))
                .andExpect(jsonPath("$.brand", is(vehicleToSave.getBrand())))
                .andExpect(jsonPath("$.model", is(vehicleToSave.getModel())))
                .andExpect(jsonPath("$.year", is(vehicleToSave.getYear())));
    }
```
<p>Where is my issue? :(</p>
<p>Thank you.</p>
<p>==================</p>
<h3>1 - Add: if I use Postman and I make the call with body</h3>
<pre class="lang-json prettyprint-override"><code>{
    "amount": 100,
    "purpose": "Postman test"
}
</code>```

it works.

答: The reason why you got this error is beacuse your Double getAmount() method overrides your default Lombok's getter and when the mapper tries to map your entity's BigDecimal amount with your DTO's amount the mapper does not find a BigDecimal property with amount as its name.

Body:
Preamble: I'm learning Java (Spring) with TDD. I have a work-in-progress project here:

Branch: https://github.com/sineverba/online-banking-backend/tree/add-controller

Last commit: https://github.com/sineverba/online-banking-backend/commit/69d643eb81748656200f007bedf213d9352b079a

I'm introducing test for POST call (see add-controller branch to get current state of work).

So, in new controller I added the post call and in the test I wrote:

        var id = 1L;
        var transactionToSave = validBankAccountTransactionsEntity(new BigDecimal(99.99), "First Transaction");
        var savedTransaction = validBankAccountTransactionsEntity(id, new BigDecimal(99.99), "First Transaction");

        when(bankAccountTransactionsService.post(transactionToSave))
        .thenReturn(savedTransaction);

        mvc.perform(
                post("/api/v1/bank-account-transactions/")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(transactionToSave))
                )
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.id", is((int) id)))
        .andExpect(jsonPath("$.amount", is(transactionToSave.getAmount())));

I got the error

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: source cannot be null

And the issue is with

[...]
objectMapper.writeValueAsBytes(transactionToSave)
[...]

And in particular the error is

Caused by: java.lang.IllegalArgumentException: source cannot be null
    at org.modelmapper.internal.util.Assert.notNull(Assert.java:53)
    at org.modelmapper.ModelMapper.map(ModelMapper.java:404)
    at com.bitbank.controllers.v1.BankAccountTransactionsController.convertToDto(BankAccountTransactionsController.java:54)

So, at the end, seems error caused by convertToDto method called by post method of controller: return convertToDto(savedBankAccountTransactionsEntity);.

Cannot explain my issue, I don't know how resolve it.

I'm following a guide: https://www.mattianatali.it/come-sviluppare-rest-api-in-tdd-con-spring-boot/

You can see the author wrote same code (of course different example), about at half of page, you can see:

@Test
    void create_shouldSaveTheVehicle() throws Exception {
        var vehicleId = 1L;
        var vehicleToSave = aValidVehicle();

        when(vehicleService.save(vehicleToSave))
                .thenReturn(
                        vehicleToSave
                                .toBuilder()
                                .id(vehicleId)
                                .build()
                );

        mvc.perform(
                post("/api/v1/vehicles")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(vehicleToSave))
        )
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.id", is((int) vehicleId)))
                .andExpect(jsonPath("$.brand", is(vehicleToSave.getBrand())))
                .andExpect(jsonPath("$.model", is(vehicleToSave.getModel())))
                .andExpect(jsonPath("$.year", is(vehicleToSave.getYear())));
    }

Where is my issue? :(

Thank you.

==================

1 - Add: if I use Postman and I make the call with body

{
    "amount": 100,
    "purpose": "Postman test"
}

it works.


问:
Populate Excel Workbook Sheet with Rows from Master Sheet Based on Criteria
I manage a large, ever-growing and changing contact list. I have a workbook with a master sheet containing 400+ names with headings in columns A-Q:

First | Last | Email | Phone | Mobile | Address | City | State | Zip | Tags | Community (and so on)

I want to be able to update my master list weekly and populate other tabs with filtered data by Community.

So, from the sheet "Master List" I want to pull all of the rows from A-Q to sheet "Twin Peaks Residents", only if the Community listed is "Twin Peaks" :-)

I was able to get counts of communities in another tab but copying rows is a different animal.

I was thinking of something like:

```<code>=IF('Master List'!K1="*Twin Peaks*")
</code>```

...the rest of the formula... that results in only the rows with Twin Peaks listed as a contact's community would populate into the "Twin Peaks Residents" sheet.

The outcome is that once a week, I download a master csv file from an online database, paste it into the master sheet and the other tabs automatically populate based on their Community label in column K.

[Edit] Perhaps a simplification using fewer variable and images would be helpful. I'm going to add two screenshots of how I would like this to work in much more simple terms.
Resulting Tab filtering for Chicago contacts
Master sheet with all contacts

答:
As @Davo says you're probably best off creating a pivot table.

However, I have solved this problem using just formulas in the past, using helper columns.

Choose a helper column. It could be on another sheet, but I'm going to go with column X on your main sheet.

In X2 set a formula: =COUNTIFS(K$2:K2,"Twin Peaks")+1

For convenience, name this column "TwinPeaksRowKey"

In your Twin Peaks sheet, set up columns same as your main sheet

Apply the formula in 'Twin Peaks'!A2: =IfNA(Index(Main!A:A, Xmatch(Row(),TwinPeaksRowKey)),"")

Copy across and down as far as you need

You can refine this a bit - have a helper sheet with the community names in row 1 and have the COUNTIFS reference that.

Or… you could learn how to use pivot tables. I will too, someday.

Body:
I manage a large, ever-growing and changing contact list. I have a workbook with a master sheet containing 400+ names with headings in columns A-Q:

First | Last | Email | Phone | Mobile | Address | City | State | Zip | Tags | Community (and so on)

I want to be able to update my master list weekly and populate other tabs with filtered data by Community.

So, from the sheet "Master List" I want to pull all of the rows from A-Q to sheet "Twin Peaks Residents", only if the Community listed is "Twin Peaks" :-)

I was able to get counts of communities in another tab but copying rows is a different animal.

I was thinking of something like:

=IF('Master List'!K1="*Twin Peaks*")

...the rest of the formula... that results in only the rows with Twin Peaks listed as a contact's community would populate into the "Twin Peaks Residents" sheet.

The outcome is that once a week, I download a master csv file from an online database, paste it into the master sheet and the other tabs automatically populate based on their Community label in column K.

[Edit] Perhaps a simplification using fewer variable and images would be helpful. I'm going to add two screenshots of how I would like this to work in much more simple terms.
Resulting Tab filtering for Chicago contacts
Master sheet with all contacts


问:
What is the correct way of retrieving an OAuth2 Bearer token in Spring
I am making service to service requests using Spring's WebClient that require an OAuth2 bearer token to be added as a header to the request.  I Can do this relatively easily by creating an ExchangeFilterFunction that intercepts the request, retrieves an access token, adds it to the header, and continues on.  Since this is not a user request, the SecurityContextHolder does not contain an Authentication that would hold an access token for me, so instead of retrieving from that, I would like to get an access token based on my Spring security configuration (currently defined in the spring.security.oauth2.client.registration and provider properties).

The way I'm doing this now is by Autowiring an OAuth2ClientContext and then getting the AccessToken from it.  Reducing the code only to what I care about for this question, I have:

```<code>@Component
public class OAuth2WebClientFilter implements ExchangeFilterFunction {

    @Autowired
    private OAuth2ClientContext oAuth2ClientContext;

    public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
        // simple retrieval of the token
        String oAuth2Token = oAuth2ClientContext.getAccessToken().getValue();

        // adding the token to the header of the request
        request = ClientRequest.from(request).header(HttpHeaders.AUTHORIZATION, "Bearer " + oAuth2Token).build();

        return next.exchange(request);
    }
}

</code>```

This does exactly what I want it to.  However, I have recently upgraded spring-security-oauth2 to 2.5.0.RELEASE, and it is saying the OAuth2ClientContext is deprecated, but I haven't found a simple replacement for this process.  So is there still a way to get an access token in a relatively simple fashion like above, and if so, how?

Also note: this concept is used elsewhere in the project and not just for the WebClient, so I'm looking to see how to properly replace an injected OAuth2ClientContext. Thanks!

答:
Spring Security provides an exchange filter function called ServletOAuth2AuthorizedClientExchangeFilterFunction.

The ServletOAuth2AuthorizedClientExchangeFilterFunction provides a
simple mechanism for requesting protected resources by using an
OAuth2AuthorizedClient and including the associated OAuth2AccessToken
as a Bearer Token. It directly uses an OAuth2AuthorizedClientManager
and therefore inherits the following capabilities:

An OAuth2AccessToken will be requested if the client has not yet been
authorized.

authorization_code - triggers the Authorization Request redirect to
initiate the flow

client_credentials - the access token is obtained directly from the
Token Endpoint

password - the access token is obtained directly from the Token
Endpoint

If the OAuth2AccessToken is expired, it will be refreshed (or renewed)
if an OAuth2AuthorizedClientProvider is available to perform the
authorization

See https://docs.spring.io/spring-security/reference/servlet/oauth2/client/authorized-clients.html#oauth2Client-webclient-servlet for details.

Body:
I am making service to service requests using Spring's WebClient that require an OAuth2 bearer token to be added as a header to the request.  I Can do this relatively easily by creating an ExchangeFilterFunction that intercepts the request, retrieves an access token, adds it to the header, and continues on.  Since this is not a user request, the SecurityContextHolder does not contain an Authentication that would hold an access token for me, so instead of retrieving from that, I would like to get an access token based on my Spring security configuration (currently defined in the spring.security.oauth2.client.registration and provider properties).

The way I'm doing this now is by Autowiring an OAuth2ClientContext and then getting the AccessToken from it.  Reducing the code only to what I care about for this question, I have:

@Component
public class OAuth2WebClientFilter implements ExchangeFilterFunction {

    @Autowired
    private OAuth2ClientContext oAuth2ClientContext;

    public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
        // simple retrieval of the token
        String oAuth2Token = oAuth2ClientContext.getAccessToken().getValue();

        // adding the token to the header of the request
        request = ClientRequest.from(request).header(HttpHeaders.AUTHORIZATION, "Bearer " + oAuth2Token).build();

        return next.exchange(request);
    }
}

This does exactly what I want it to.  However, I have recently upgraded spring-security-oauth2 to 2.5.0.RELEASE, and it is saying the OAuth2ClientContext is deprecated, but I haven't found a simple replacement for this process.  So is there still a way to get an access token in a relatively simple fashion like above, and if so, how?

Also note: this concept is used elsewhere in the project and not just for the WebClient, so I'm looking to see how to properly replace an injected OAuth2ClientContext. Thanks!


问:
Flutter : Image Picker Exception
I'm trying to pick image by image picker package , it was working but now I get this error

Unhandled Exception: PlatformException(already_active, Image picker is
already active, null, null)

and this is the code which I'm using :

```<code> File _image;
 final picker = ImagePicker();

  Future getImage() async {
    var image = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }

  Future getCameraImage() async {
    var image = await picker.getImage(source: ImageSource.camera);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }
</code>```

Explain :
when clicking to pick image ( gallery or camera ) first time it was opening the gallery and after selecting image , the setState for _image = File(image.path); not work and after that I'm trying to click to pick image again then this exception is appear

答:
Try calling Navigator.pop(this.context) outside the setState, you should never call it inside a setState call:

 File _image;
 final picker = ImagePicker();

  Future getImage() async {
    var image = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = File(image.path);
    });
    Navigator.pop(this.context);
  }

  Future getCameraImage() async {
    var image = await picker.getImage(source: ImageSource.camera);
    setState(() {
      _image = File(image.path);
    });
    Navigator.pop(this.context);
  }
```

Title: Flutter : Image Picker Exception

Body:
I'm trying to pick image by image picker package , it was working but now I get this error

Unhandled Exception: PlatformException(already_active, Image picker is
already active, null, null)

and this is the code which I'm using :

 File _image;
 final picker = ImagePicker();

  Future getImage() async {
    var image = await picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }

  Future getCameraImage() async {
    var image = await picker.getImage(source: ImageSource.camera);
    setState(() {
      _image = File(image.path);
      Navigator.pop(this.context);
    });
  }

Explain :
when clicking to pick image ( gallery or camera ) first time it was opening the gallery and after selecting image , the setState for _image = File(image.path); not work and after that I'm trying to click to pick image again then this exception is appear


问:
Which File Explorer "Details" can be set from a c# Assembly?
File Explorer offers a vast array of possible details to show.  Which ones can be set from within a c# assembly?
I am aware of:

"Company" from the AssemblyCompany Attribute

"Copyright" from the AssemblyCopyright Attribute

"File description" from the AssemblyTitle Attribute

"File version" from the AssemblyFileVersion Attribute (or the AssemblyVersion Attribute if AssemblyFileVersion is not set)

"Legal trademarks" from the AssemblyTrademark Attribute

"Product name" from the AssemblyProduct Attribute

"Product version" from the AssemblyInformationalVersion Attribute (or the AssemblyVersion Attribute if AssemblyInformationalVersion is not set)

Are there any others that can be set either as Assembly Attributes or using some other mechanism?

答:
The properties of a file comes from basic filesystem properties (size, date/time, etc.) and from specialized property handlers.

The properties you listed come from the version information resource in PE files. While the version resource supports arbitrary string/value pairs, Windows is only going to expose the "standard" entries as properties.


问:
MS Edge says it's disconnected from the internet in Developer Mode
This has been happening for a while, and I've been wondering why. I couldn't find anything else related to this, so I thought I'd ask. And yes, I have been connected to the internet while this happens.

Each time I enter developer mode in MS Edge, it says it's disconnected, however, upon exiting and refreshing the page it loads normally. Sometimes, this doesn't happen when just entering Dev Mode, but upon resizing the window (see image - "Dimensions: Responsive"). Doesn't seem to happen on Brave or Chrome, just Edge.

Things I've tried (but to no avail):

Reset the browser storage

Reinstalled Edge

Updated to the latest

答:
Well, based on the image you provided, I did some tests and I found that the reason might be this:

By default, it chooses the option: No throttling

And then you may have accidentally changed its option to: Offline

After this, when you close and reopen devtools, you will see the image in your post,like this:

So you just need to modify it to the default option No throttling to fix the issue.


问:
PHP Regular expressions problem
I'm using regex to pull info from a html table.

But I'm messing up some how, and have no idea why.

PHP CODE:

```<code>$printable = file_get_contents('./testplaylist.php', true);

if(preg_match_all('/<TR[^>]*>(.*?)<\/TR>/si', $printable, $matches, PREG_SET_ORDER)); {
foreach($matches as $match) {
$data = "$match[1]";

echo("$data <br />");

}
}
</code>```

HTML DATA:

```<code><TR class=" light ">
Stuff in here
</TR>
</code>```

Any help would be appreciated,

Thanks!

答:
I know what your first problem is. regex! I kid! but have you checked out PHP DOM?

http://www.php.net/manual/en/domdocument.loadhtmlfile.php

It would probably work in your case just fine. It would be 10x easier too.

Some people, when confronted with a problem, think “I know, I'll use
  regular expressions.”   Now they have two problems. -Jamie Zawinski

Title: PHP Regular expressions problem

Body:
I'm using regex to pull info from a html table.

But I'm messing up some how, and have no idea why.

PHP CODE:

$printable = file_get_contents('./testplaylist.php', true);

if(preg_match_all('/
]*>(.*?)<\/TR>/si', $printable, $matches, PREG_SET_ORDER)); {
foreach($matches as $match) {
$data = "$match[1]";

echo("$data
");

}
}

HTML DATA:

Stuff in here

Any help would be appreciated,

Thanks!