问:
What is the fascination with code metrics?
I've seen a number of 'code metrics' related questions on SO lately, and have to wonder what the fascination is? Here are some recent examples:

what code metrics convince you that provided code is crappy

when if ever is number of lines of code a useful metric

writing quality tests

In my mind, no metric can substitute for a code review, though:

some metrics sometimes may indicate places that need to be reviewed, and

radical changes in metrics over short time frames may indicate places that need to be reviewed

But I cannot think of a single metric that by itself always indicates 'good' or 'bad' code - there are always exceptions and reasons for things that the measurements cannot see.

Is there some magical insight to be gained from code metrics that I've overlooked? Are lazy programmers/managers looking for excuses not to read code? Are people presented with giant legacy code bases and looking for a place to start? What's going on?

Note: I have asked some of these questions on the specific threads both in answers and comments and got no replies, so I thought I should ask the community in general as perhaps I am missing something. It would be nice to run a metrics batch job and not actually have to read other people's code (or my own) ever again, I just don't think it is practical!

EDIT: I am familiar with most if not all of the metrics being discussed, I just don't see the point of them in isolation or as arbitrary standards of quality.

答:
Here is some Complexity Metrics from stan4j.

An eclipse class structure analyze tool.

I like this tool and the metrics. I treat the metrics as statistics, indicators,  warning messages. Sometime due to some methods or some classes really has some complicated logic made them to be complex, what shall be done is keep an eye on them,
review them to see if there is an need to refactor them or review them carefully, due to normally they are error prone. Also I use it as analyze tool to learn source code, due to I like to learn from complex to simple.Actually it includes some other metrics such as Robert C. Martin Metrics, Chidamber & Kemerer Metrics,Count Metrics
But I like this one best

Complexity Metrics

Cyclomatic Complexity Metrics

Cyclomatic Complexity (CC)
The cyclomatic complexity of a method is the number of decision points in the method's control flow graph incremented by one. Decision points occur at if/for/while statements, case/catch clauses and similar source code elements, where the control flow is not just linear. The number of (byte code) decision points introduced by a single (source code) statement may vary, depending e.g. on the complexity of boolean expressions. The higher the cyclomatic complexity value of a method is, the more test cases are required to test all the branches of the method's control flow graph.

Average Cyclomatic Complexity
Average value of the Cyclomatic Complexity metric over all methods of an application, library, package tree or package.

Fat Metrics
The Fat metric of an artifact is the number of edges in an appropriate dependency graph of the artifact. The dependency graph type depends on the metric variant and the chosen artifact:

Fat
The Fat metric of an application, library or package tree is the edge count of its subtree dependency graph. This graph contains all the artifact's children in the package tree hierarchy, thereby also including leaf packages. (To see the appropriate graph in the Composition View, the Structure Explorer's Flat Packages toggle has to be disabled. The Show Libraries toggle has to be enabled if the chosen artifact is a library, otherwise it has to be disabled.)

The Fat metric of a package is the edge count of its unit dependency graph. This graph contains all top level classes of the package.

The Fat metric of a class is the edge count of its member graph. This graph contains all fields, methods and member classes of the class. (This graph and the Fat value are only available if the code analysis was performed with Level of Detail Member, not Class.)

Fat for Library Dependencies (Fat - Libraries)
The Fat for Library Dependencies metric of an application is the edge count of its library dependency graph. This graph contains all libraries of the application. (To see the appropriate graph in the Composition View, the Structure Explorer's Show Libraries toggle has to be enabled.)

Fat for Flat Package Dependencies (Fat - Packages)
The Fat for Flat Package Dependencies metric of an application is the edge count of its flat package dependency graph. This graph contains all packages of the application. (To see the appropriate graph in the Composition View, the Structure Explorer's Flat Packages toggle has to be enabled and the Show Libraries toggle has to be disabled.)

The Fat for Flat Package Dependencies metric of a library is the edge count of its flat package dependency graph. This graph contains all packages of the library. (To see the appropriate graph in the Composition View, the Structure Explorer's Flat Packages and Show Libraries toggles have to be enabled.)

Fat for Top Level Class Dependencies (Fat - Units)
The Fat for Top Level Class Dependencies metric of an application or library is the edge count of its unit dependency graph. This graph contains all the top level classes of the application or library. (For reasonable applications it is too large to be visualized and thus can not be displayed in the Composition View. Unit dependency graphs may only be displayed for packages.)

OwnerDisplayName: Steven A. Lowe

LastEditorDisplayName: Steven A. Lowe


来源: stackexchange

问:
Elegant way to create M:N relationships between the same models in Laravel?
I am trying to define a model relationship that I believe is extremely ordinary, but I just could not find any elegant way to do it in Laravel. I'm talking about a same-model m:n relationship. Let's say you want to define a friends relationship:

class User extends Model
{
    public function friends(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'friends');
    }
}

```
<p>Well, this won't work both ways, because you might probably expect a table similar to this:</p>
```friends:
 - (int) id
 - (int) first_user_id
 - (int) second_user_id
 - (bool) is_accepted (default 0)
```
<p>And now, in the model, you would have been supposed to define the foreign key names. Which one is foreign? The typical use case is that one user will send a request to another, and then the other one will accept/reject it. But you will have to assign the users to that M:N relationship, you will have to do some validation (e.g., aren't they friends already?), you will have to check if the other user didn't already send a request (which is pending) to the first one and so on. However, I am trying to avoid something like the following.</p>
<pre class="lang-php prettyprint-override"><code>class User extends Model
{
    public function myFriends(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'friends', 'first_user_id', 'second_user_id');
    }

    public function friendOf(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'friends', 'second_user_id', 'first_user_id');
    }
}
</code>```

I am trying to think of a data structure that would allow this to happen as a classic relationship, but I could not quite get to it. Any ideas? Is it even possible while keeping the traditional Eloquent-relationship methods?

答:
You can define a new class and table "frienduser" which has three inputs

'user_1','user-2','is_accepted'

user_1 is sender

user_2 for receiver

Friends table contains duplicate data.

id,user_id,friend_id,friend_user_id

1,1,2,1

2,2,1,1
```<code>class FriendUser extends Model
{
    protected $table = 'friend_user';

    use HasFactory;

}
</code>```

Friend class

```<code>class Friend extends Model
{
    use HasFactory;
    public function friend_info()
    {
        return $this->belongsTo(User::class,'friend_id');
    }
      public function friend_user()
    {
        return $this->hasOne('App\Models\FriendUser', 'id','friend_user_id')->first();

    }
}
</code>```

Controller

```<code>$frienduser= Auth::user()->friends()->where('friend_id','=','2')->first()->frienduser();
 $frienduser->isaccepted=1;
 $frienduser->save();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to define a model relationship that I believe is extremely ordinary, but I just could not find any elegant way to do it in Laravel. I'm talking about a same-model m:n relationship. Let's say you want to define a friends relationship:

class User extends Model
{
    public function friends(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'friends');
    }
}

Well, this won't work both ways, because you might probably expect a table similar to this:

friends:
 - (int) id
 - (int) first_user_id
 - (int) second_user_id
 - (bool) is_accepted (default 0)

And now, in the model, you would have been supposed to define the foreign key names. Which one is foreign? The typical use case is that one user will send a request to another, and then the other one will accept/reject it. But you will have to assign the users to that M:N relationship, you will have to do some validation (e.g., aren't they friends already?), you will have to check if the other user didn't already send a request (which is pending) to the first one and so on. However, I am trying to avoid something like the following.

class User extends Model
{
    public function myFriends(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'friends', 'first_user_id', 'second_user_id');
    }

    public function friendOf(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'friends', 'second_user_id', 'first_user_id');
    }
}

I am trying to think of a data structure that would allow this to happen as a classic relationship, but I could not quite get to it. Any ideas? Is it even possible while keeping the traditional Eloquent-relationship methods?

Body:
You can define a new class and table "frienduser" which has three inputs

'user_1','user-2','is_accepted'

user_1 is sender

user_2 for receiver

Friends table contains duplicate data.

id,user_id,friend_id,friend_user_id

1,1,2,1

2,2,1,1

class FriendUser extends Model
{
    protected $table = 'friend_user';

    use HasFactory;

}

Friend class

class Friend extends Model
{
    use HasFactory;
    public function friend_info()
    {
        return $this->belongsTo(User::class,'friend_id');
    }
      public function friend_user()
    {
        return $this->hasOne('App\Models\FriendUser', 'id','friend_user_id')->first();

    }
}

Controller

$frienduser= Auth::user()->friends()->where('friend_id','=','2')->first()->frienduser();
 $frienduser->isaccepted=1;
 $frienduser->save();


问:
React Jest:- node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */);
I have below code in react.

```<code>useEffect(() => {
        (async () => {
            await httpClient
                .get(`${config.resourceServerUrl}/inventory/`)
                .then((response) => {
                    setSponsor(response.data.sponsor);
                    setAddress(response.data.address);
                    setPhaseOfTrial(response.data.phaseOfTrial);
                })
                .catch((error) => {
                    alert(error);
                });
        })();
    }, []);
</code>```

this code works successfully. only issue is , it is failing in jest test case.

```<code>describe('ListInventory', () => {
    it('should render successfully', () => {
        const { baseElement } = render(<ListInventory />);
        expect(baseElement).toBeTruthy();
    });
});
</code>```

Below is the error.

```<code>node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read properties of undefined (reading 'get')".] {
  code: 'ERR_UNHANDLED_REJECTION'
}
</code>```

I am already using catch block. what wrong is in the code? could you please help me with the same.

答:
Try handling the promise using a try-catch block, as:

```<code>  useEffect(() => {
    (async () => {
      try {
        let response = await httpClient.get(
          `${config.resourceServerUrl}/inventory/`
        );
        setSponsor(response.data.sponsor);
        setAddress(response.data.address);
        setPhaseOfTrial(response.data.phaseOfTrial);
      } catch(error) {
        alert(error);
      }
    })();
  }, []);
</code>```

or

```<code>  useEffect(() => {
    (async () => {
        let response = await httpClient.get(
          `${config.resourceServerUrl}/inventory/`
        );
        setSponsor(response.data.sponsor);
        setAddress(response.data.address);
        setPhaseOfTrial(response.data.phaseOfTrial);
    })().catch(e=>alert(e));
  }, []);
</code>```

Body:
I have below code in react.

useEffect(() => {
        (async () => {
            await httpClient
                .get(`${config.resourceServerUrl}/inventory/`)
                .then((response) => {
                    setSponsor(response.data.sponsor);
                    setAddress(response.data.address);
                    setPhaseOfTrial(response.data.phaseOfTrial);
                })
                .catch((error) => {
                    alert(error);
                });
        })();
    }, []);

this code works successfully. only issue is , it is failing in jest test case.

describe('ListInventory', () => {
    it('should render successfully', () => {
        const { baseElement } = render(<ListInventory />);
        expect(baseElement).toBeTruthy();
    });
});

Below is the error.

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read properties of undefined (reading 'get')".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

I am already using catch block. what wrong is in the code? could you please help me with the same.

Body:
Try handling the promise using a try-catch block, as:

  useEffect(() => {
    (async () => {
      try {
        let response = await httpClient.get(
          `${config.resourceServerUrl}/inventory/`
        );
        setSponsor(response.data.sponsor);
        setAddress(response.data.address);
        setPhaseOfTrial(response.data.phaseOfTrial);
      } catch(error) {
        alert(error);
      }
    })();
  }, []);

or

  useEffect(() => {
    (async () => {
        let response = await httpClient.get(
          `${config.resourceServerUrl}/inventory/`
        );
        setSponsor(response.data.sponsor);
        setAddress(response.data.address);
        setPhaseOfTrial(response.data.phaseOfTrial);
    })().catch(e=>alert(e));
  }, []);


问:
How to debug Kmeans clusters on python 3.9 tensorflow on Mac M1 pro?
When you installed python 3.9 tensorflow on new Mac M1 chip, you would probably come to this bug when you run Kmeans.predict():

```<code>nonetype' object has no attribute 'split'
</code>```

I have searched online for a long time but cannot find any useful solution. So if you happen to have the same issue as mine, maybe you can try this:

Find the file threadpoolctl.py under /Users/YOURNAME/miniforge3/envs/tensorflow/lib/python3.9/site-packages

Replace it by the file in this website:
https://github.com/joblib/threadpoolctl/blob/master/threadpoolctl.py

Restart your python

Hope it helps.

答: +100500 to the karma: worked for me as well within Python 3.8. The version of threadpoolctl.py was "2.1.0" - after making an update by version "3.2.0.dev0" KMeans started to work.</p>

Body:
When you installed python 3.9 tensorflow on new Mac M1 chip, you would probably come to this bug when you run Kmeans.predict():

nonetype' object has no attribute 'split'

I have searched online for a long time but cannot find any useful solution. So if you happen to have the same issue as mine, maybe you can try this:

Find the file threadpoolctl.py under /Users/YOURNAME/miniforge3/envs/tensorflow/lib/python3.9/site-packages

Replace it by the file in this website:
https://github.com/joblib/threadpoolctl/blob/master/threadpoolctl.py

Restart your python

Hope it helps.


问:
How to round up a timestampdiff in sql
I have a complex sql file where I am calculating timestampdiff as follows in seconds:

```<code>timestampdiff(2, char(max(END_TS) - min(START_TS))) as ELAPSED_TIME
</code>```

ELAPSED_TIME is sometimes calculated as 0 when the difference is in microseconds. Is it possible to round off to 1 second if the difference is in microseconds so ELAPSED_TIME is never equal to 0?

Example:

```<code>[db2inst1@dashmpp-head-0 - Db2wh ~]$ db2 "select * from TEST_TBL"

COL1                       COL2
-------------------------- --------------------------
2022-01-25-01.00.00.300000 2022-01-25-01.00.00.000000

  1 record(s) selected.
</code>```
```<code>[db2inst1@dashmpp-head-0 - Db2wh ~]$ db2 "select CEILING(timestampdiff(2, char(max(col1) - min(col2)))) from TEST_TBL"

1
-----------
          0

  1 record(s) selected.
</code>```

Since the difference is 300000 microseconds its equal to 0 seconds. Can we round this up to 1 second?

This is part if a long select query so I cannot use if else.

Title: How to round up a timestampdiff in sql

Body:
I have a complex sql file where I am calculating timestampdiff as follows in seconds:

timestampdiff(2, char(max(END_TS) - min(START_TS))) as ELAPSED_TIME

ELAPSED_TIME is sometimes calculated as 0 when the difference is in microseconds. Is it possible to round off to 1 second if the difference is in microseconds so ELAPSED_TIME is never equal to 0?

Example:

[db2inst1@dashmpp-head-0 - Db2wh ~]$ db2 "select * from TEST_TBL"

COL1                       COL2
-------------------------- --------------------------
2022-01-25-01.00.00.300000 2022-01-25-01.00.00.000000

  1 record(s) selected.

[db2inst1@dashmpp-head-0 - Db2wh ~]$ db2 "select CEILING(timestampdiff(2, char(max(col1) - min(col2)))) from TEST_TBL"

1
-----------
          0

  1 record(s) selected.

Since the difference is 300000 microseconds its equal to 0 seconds. Can we round this up to 1 second?

This is part if a long select query so I cannot use if else.

Body:
Either use the expression as is or create a user defined scalar function based on this expression.

WITH TEST_TBL (COL1, COL2) AS
(
VALUES
  (TIMESTAMP ('2022-01-25-01.00.00.300000'), TIMESTAMP ('2022-01-25-01.00.00.000000'))
, (TIMESTAMP ('2022-01-25-01.00.00.000000'), TIMESTAMP ('2022-01-25-01.00.00.000000'))
, (TIMESTAMP ('2022-01-25-01.00.02.000000'), TIMESTAMP ('2022-01-25-01.00.00.000000'))
)

SELECT
  COL1, COL2
-- the expression
, DECODE (COL1, COL2, 0, COALESCE (NULLIF (TIMESTAMPDIFF (2, CHAR (COL1 - COL2)), 0), 1)) AS DIFF
FROM TEST_TBL

COL1
COL2
DIFF

2022-01-25-01.00.00.300000
2022-01-25-01.00.00.000000
1

2022-01-25-01.00.00.000000
2022-01-25-01.00.00.000000
0

2022-01-25-01.00.02.000000
2022-01-25-01.00.00.000000
2

Update:

You may try the folloing as well:

CEIL (TIMESTAMPDIFF (1, CHAR (COL1 - COL2)) / 1000000.)


问:
Beautify html output
I was wondering whether there is class or something similar which I can include into my PHP pages to beautify the HTML output.

Such as putting new lines in after tags and correctly indenting so that my source code isn't only one line, I know that to the browser it doesn't matter but I wish to do this.

I have heard of http://www.php.net/manual/en/book.tidy.php but am not clear on what it does and how to implement it, i.e. I don't understand what the manual says about it.

答:
The Tidy extension is the way to go.

If you don't understand the documentation (OK, admittedly it's not very thorough), then the first results on Google for php tidy tutorials look very promising:

http://devzone.zend.com/article/761

http://www.devshed.com/c/a/PHP/Working-with-the-Tidy-Library-in-PHP-5/

ContentLicense: CC BY-SA 3.0

Title: Beautify html output


问:
Select the filtered option from the dropdown using Cypress
I have a dropdown, kind of lookup, to test. I have to type a value and based on the value, the options will be filtered. And, I have to chose the option I want.

For example, some of the options filtered based on the value provided will be in the below format:

```<code>ENG 101 English-Read and Write
ENG 101 English-Speaking
ENG 101 English-Listening
MAT 201 Mathematics-Algebra
CSC 301 JAVA-Programming
CSC 301 CSharp-Programming
</code>```

I can only type the values in the first column - 'ENG' or 'MAT' or 'CSC' in the field to filter the options.

Now, if I provide value 'MAT' in the field then only one option will be filtered. No issue with selecting the option 'Mathematics-Algebra'.

If I provide value as 'ENG' to filter then multiple options are filtered. Now, I have to select the option 'English-Listening'. This is where I have the problem.

```<code>cy.get('app-screen').find('#paper-description').type('ENG'); // this is for providing input 'ENG'
cy.get('.overlay-pane').find('mat-option span:nth-child(3)').should('have.text', 'English-Listening'); // this is for selecting the required filtered option.
</code>```

When the above statement is executed, I am getting the below Assertion Error.

```<code>Timed out retrying after 4000ms: expected '[ <span.col-3>, 2 more... ]' to have text English-Listening, but the text was English-Read and WriteEnglish-SpeakingEnglish-Listenting
</code>```

The html structure would be in the below format:

```<code><div class='overlay-pane'>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Read and Write</span>
    </mat-option>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Speaking</span>
    </mat-option>
    <mat-option>
        <span class='.col-1>ENG</span>
        <span class='.col-2>101</span>
        <span class='.col-3>English-Listening</span>
    </mat-option>
</div>
</code>```

The option to be selected this time may be 'English-Listening'. Next time, it could be 'English-Speaking' or some other option. How to select the required option out of multiple filtered items from lookup?

答:
You can use find for this

cy.get('app-screen').find('#paper-description').type('ENG')

cy.get('.overlay-pane')
  .find('mat-option')
  .eq(2)
  .find('.col-3').should('have.text', 'English-Listening')
  .click()
```

Body:
I have a dropdown, kind of lookup, to test. I have to type a value and based on the value, the options will be filtered. And, I have to chose the option I want.

For example, some of the options filtered based on the value provided will be in the below format:

ENG 101 English-Read and Write
ENG 101 English-Speaking
ENG 101 English-Listening
MAT 201 Mathematics-Algebra
CSC 301 JAVA-Programming
CSC 301 CSharp-Programming

I can only type the values in the first column - 'ENG' or 'MAT' or 'CSC' in the field to filter the options.

Now, if I provide value 'MAT' in the field then only one option will be filtered. No issue with selecting the option 'Mathematics-Algebra'.

If I provide value as 'ENG' to filter then multiple options are filtered. Now, I have to select the option 'English-Listening'. This is where I have the problem.

cy.get('app-screen').find('#paper-description').type('ENG'); // this is for providing input 'ENG'
cy.get('.overlay-pane').find('mat-option span:nth-child(3)').should('have.text', 'English-Listening'); // this is for selecting the required filtered option.

When the above statement is executed, I am getting the below Assertion Error.

Timed out retrying after 4000ms: expected '[ , 2 more... ]' to have text English-Listening, but the text was English-Read and WriteEnglish-SpeakingEnglish-Listenting

The html structure would be in the below format:

    <mat-option>
        ENG
        101
        English-Read and Write
    </mat-option>
    <mat-option>
        ENG
        101
        English-Speaking
    </mat-option>
    <mat-option>
        ENG
        101
        English-Listening
    </mat-option>

The option to be selected this time may be 'English-Listening'. Next time, it could be 'English-Speaking' or some other option. How to select the required option out of multiple filtered items from lookup?


问:
Programmatically download the QR image
I  tried to create a QR code with QRcode.js library. As of the UI, I can manually click on the button download to download it but I would to download automatically without clicking the button.

Base on my code bellow.

```<code>function genQR(link_string){
    let qr_code_element = document.querySelector(".qr-code");

      if (link_string != "") {
          if (qr_code_element.childElementCount == 0) {
            generate(qr_code_element, link_string);
          } else {
          qr_code_element.innerHTML = "";
            generate(qr_code_element, link_string);
          }
      } else {
          alert("not valid QR input");
          qr_code_element.style = "display: none";
      }
  }

  function generate(qr_code_element, link_string) {
    qr_code_element.style = "";
    var qrcode = new QRCode(qr_code_element, {
        text: link_string,
        width: 200,
        height: 200,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });

    let download = document.createElement("button");
    // qr_code_element.appendChild(download);

    let download_link = document.createElement("a");
    download_link.setAttribute("download", "qr.png");
    download_link.setAttribute("id", "downloadbtn");
    download_link.innerText = "Download";
    // download.appendChild(download_link);

    let qr_code_img = document.querySelector(".qr-code img");
    let qr_code_canvas = document.querySelector("canvas");

    if (qr_code_img.getAttribute("src") == null) {
      setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
      }, 300);
    } else {
        setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
        }, 300);
    }

    var clickEvent = new MouseEvent("click", {
      "view": window,
      "bubbles": true,
      "cancelable": false
  });

  //I expect the below line will automatically download the QR but nothing fires.
  download_link.dispatchEvent(clickEvent);
}
</code>```

If I use button to click and download by hand will works fine for me but I want to reduce too many steps.

I think I almost done here but failed.

Could anyone show me how to automatic download?

Thank you in advance.

答:
I done my target by adding the source you shared at the bottom of my code and then added this function to convert dataURL to Blob

```<code>function dataURItoBlob(dataURI) {
  var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
  }

 var blob = new Blob([ab], {type: mimeString});
  return blob;

}
</code>```

Thank you very much @Gianmarco Rengucci
I rate for you

Title: Programmatically download the QR image

Body:
I  tried to create a QR code with QRcode.js library. As of the UI, I can manually click on the button download to download it but I would to download automatically without clicking the button.

Base on my code bellow.

function genQR(link_string){
    let qr_code_element = document.querySelector(".qr-code");

      if (link_string != "") {
          if (qr_code_element.childElementCount == 0) {
            generate(qr_code_element, link_string);
          } else {
          qr_code_element.innerHTML = "";
            generate(qr_code_element, link_string);
          }
      } else {
          alert("not valid QR input");
          qr_code_element.style = "display: none";
      }
  }

  function generate(qr_code_element, link_string) {
    qr_code_element.style = "";
    var qrcode = new QRCode(qr_code_element, {
        text: link_string,
        width: 200,
        height: 200,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });

    let download = document.createElement("button");
    // qr_code_element.appendChild(download);

    let download_link = document.createElement("a");
    download_link.setAttribute("download", "qr.png");
    download_link.setAttribute("id", "downloadbtn");
    download_link.innerText = "Download";
    // download.appendChild(download_link);

    let qr_code_img = document.querySelector(".qr-code img");
    let qr_code_canvas = document.querySelector("canvas");

    if (qr_code_img.getAttribute("src") == null) {
      setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
      }, 300);
    } else {
        setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
        }, 300);
    }

    var clickEvent = new MouseEvent("click", {
      "view": window,
      "bubbles": true,
      "cancelable": false
  });

  //I expect the below line will automatically download the QR but nothing fires.
  download_link.dispatchEvent(clickEvent);
}

If I use button to click and download by hand will works fine for me but I want to reduce too many steps.

I think I almost done here but failed.

Could anyone show me how to automatic download?

Thank you in advance.

Body:
I done my target by adding the source you shared at the bottom of my code and then added this function to convert dataURL to Blob

function dataURItoBlob(dataURI) {
  var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
  }

 var blob = new Blob([ab], {type: mimeString});
  return blob;

}

Thank you very much @Gianmarco Rengucci
I rate for you


问:
The text contained in the tag is equal to a specific text and does not contain only the specific text
Here is my probleme:
I have two tags.

```<code><div class='twoLink'
<a class='link' <div> microsoft word </div></a>
<a class='link' <div> word </div></a>
</div>
</code>```

My goal is to click on the tag containing only the word "word" and not "microsoft word".

so I did this :

```<code>element = 'word'
linkWord = WebDriverWait(driver, timeout=5).until(EC.element_to_be_clickable(
         (By.XPATH,"//a[contains(@class, 'link')]/div[contains(text(), '"+ element +"')]")))
         driver.execute_script("arguments[0].click();", linkWord )
</code>```

But this method makes me click on the tag containing "word" and not equal to "word", so the tag I click is the first one and not the second one as I would have liked.

I would have to find a method to check an equality but I didn't find one.

What can I do about it please ?

答:
```<code>//a[@class='link']/div[text()='word']
</code>```

which is simply

```<code>f"//a[@class='link']/div[text()='{element}']"
</code>```

Remove contains() and then just use text() to compare what the
 tag value is.

Body:
Here is my probleme:
I have two tags.

<div class='twoLink'
<a class='link'
 microsoft word

<a class='link'
 word

My goal is to click on the tag containing only the word "word" and not "microsoft word".

so I did this :

element = 'word'
linkWord = WebDriverWait(driver, timeout=5).until(EC.element_to_be_clickable(
         (By.XPATH,"//a[contains(@class, 'link')]/div[contains(text(), '"+ element +"')]")))
         driver.execute_script("arguments[0].click();", linkWord )

But this method makes me click on the tag containing "word" and not equal to "word", so the tag I click is the first one and not the second one as I would have liked.

I would have to find a method to check an equality but I didn't find one.

What can I do about it please ?

Body:
//a[@class='link']/div[text()='word']

which is simply

f"//a[@class='link']/div[text()='{element}']"

Remove contains() and then just use text() to compare what the <div> tag value is.


问:
Why does this code Fail once i add validation in laravel 8?
I am just starting to learn Laravel and I am a little lost here. This code works without validation.

The task is to build a website with user registration Posting data to an already existing database. As I have pointed, without validation it works just fine but when i add validation it fails.

```<code>
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;

class RegController extends Controller
{
    public function store(Request $request) {

        Member::create([

        'fname' => $request ->fname,
        'lname' => $request ->lname,
        'gender' => $request ->gender,
        'msisdn' => $request ->msisdn,
        'email' => $request ->email,
        'status' => $request ->mstatus,
        'no_of_children' => $request ->kids,
        'occupation' => $request ->profession,
        'age' => $request ->age,
        'bna' => $request ->bna,
        'residence' => $request ->residence,
        ]);

        return redirect('/members/register');

       }
}
</code>```

But this doesn't...

```<code>
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;

class RegController extends Controller
{
    public function store(Request $request) {

        $request->validate([
            'fname' => 'required',
            'lname' => 'required',
            'gender' => 'required',
            'msisdn' => 'required|unique:members_tbl',
            'email' => 'required|unique:members_tbl',
            'status' => 'required',
            'kids' => 'required',
            'profession' => 'required',
            'age' => 'required',
            'bna' => 'required',
            'residence' => 'required',
        ],
        [
            'fname.required' => 'Please Enter your First Name',
            'lname.required' => 'Please Enter your Last Name',
            'gender.required' => 'Please Enter your Gender',
            'msisdn.required' => 'Please Enter your Phone Number',
            'msisdn.unique' => 'A user has already registered with the phone Number',
            'email.unique' => 'A user has already registered with the email',
            'email.required' => 'Please enter a valid email address',
            'status.required' => 'Please Let us know your marital status',
            'kids.required' => 'Please fill out this field',
            'profession.required' => 'Please fill out this field',
            'age.required' => 'Please fill out this field',
            'bna.required' => 'Please fill out this field',
            'residence.required' => 'Please let us know where you live',
        ]);

        Member::create([

        'fname' => $request ->fname,
        'lname' => $request ->lname,
        'gender' => $request ->gender,
        'msisdn' => $request ->msisdn,
        'email' => $request ->email,
        'status' => $request ->mstatus,
        'no_of_children' => $request ->kids,
        'occupation' => $request ->profession,
        'age' => $request ->age,
        'bna' => $request ->bna,
        'residence' => $request ->residence,
        ]);

        return redirect('/members/register');

       }
}

</code>```

What am i missing? The code works well without the validation but just redirects back to the form when validation is added.

Here is my Model

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $table="members_tbl";

    protected $fillable =[
        'fname',
        'lname',
        'gender',
        'msisdn',
        'email',
        'status',
        'no_of_children',
        'occupation',
        'age',
        'bna',
        'residence'
    ];
}
</code>```

This is the result of var_dump($request)

```<code> public 'request' =>
    object(Symfony\Component\HttpFoundation\InputBag)[44]
      protected 'parameters' =>
        array (size=13)
          '_token' => string 'DuNeITGaDF9K7eEMmU4HwX7nVLJUYDaZ1iYGT4dw' (length=40)
          'fname' => string 'Joe' (length=3)
          'lname' => string 'Peski' (length=5)
          'gender' => string 'male' (length=4)
          'msisdn' => string '254722000001' (length=12)
          'email' => string 'joetry@hotmail.com' (length=18)
          'residence' => string 'New Place' (length=9)
          'age' => string 'teen' (length=4)
          'bna' => string 'no' (length=2)
          'mstatus' => string 'single' (length=6)
          'kids' => string '4' (length=1)
          'profession' => string 'IT' (length=2)
          'submit' => string 'Submit' (length=6)
</code>```

答:
Validator doesn't read your status. Make sure you have a default value for this field.

If status is not required, you can change required to nullable, then create a default value after validation.

You need to display an error message to know what the error is.

```<code>$errors = $validator->errors();
</code>```

Usually, this case occurs when you use a select box, check box, or something that can't read a value or empty, null.

The solution is to add a default value or add a hidden field with a default value.

```<code><input type="hidden" name="status" value="0">
<select name="status">
    ...
</select>
</code>```

Body:
I am just starting to learn Laravel and I am a little lost here. This code works without validation.

The task is to build a website with user registration Posting data to an already existing database. As I have pointed, without validation it works just fine but when i add validation it fails.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;

class RegController extends Controller
{
    public function store(Request $request) {

        Member::create([

        'fname' => $request ->fname,
        'lname' => $request ->lname,
        'gender' => $request ->gender,
        'msisdn' => $request ->msisdn,
        'email' => $request ->email,
        'status' => $request ->mstatus,
        'no_of_children' => $request ->kids,
        'occupation' => $request ->profession,
        'age' => $request ->age,
        'bna' => $request ->bna,
        'residence' => $request ->residence,
        ]);

        return redirect('/members/register');

       }
}

But this doesn't...

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Member;

class RegController extends Controller
{
    public function store(Request $request) {

        $request->validate([
            'fname' => 'required',
            'lname' => 'required',
            'gender' => 'required',
            'msisdn' => 'required|unique:members_tbl',
            'email' => 'required|unique:members_tbl',
            'status' => 'required',
            'kids' => 'required',
            'profession' => 'required',
            'age' => 'required',
            'bna' => 'required',
            'residence' => 'required',
        ],
        [
            'fname.required' => 'Please Enter your First Name',
            'lname.required' => 'Please Enter your Last Name',
            'gender.required' => 'Please Enter your Gender',
            'msisdn.required' => 'Please Enter your Phone Number',
            'msisdn.unique' => 'A user has already registered with the phone Number',
            'email.unique' => 'A user has already registered with the email',
            'email.required' => 'Please enter a valid email address',
            'status.required' => 'Please Let us know your marital status',
            'kids.required' => 'Please fill out this field',
            'profession.required' => 'Please fill out this field',
            'age.required' => 'Please fill out this field',
            'bna.required' => 'Please fill out this field',
            'residence.required' => 'Please let us know where you live',
        ]);

        Member::create([

        'fname' => $request ->fname,
        'lname' => $request ->lname,
        'gender' => $request ->gender,
        'msisdn' => $request ->msisdn,
        'email' => $request ->email,
        'status' => $request ->mstatus,
        'no_of_children' => $request ->kids,
        'occupation' => $request ->profession,
        'age' => $request ->age,
        'bna' => $request ->bna,
        'residence' => $request ->residence,
        ]);

        return redirect('/members/register');

       }
}

What am i missing? The code works well without the validation but just redirects back to the form when validation is added.

Here is my Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $table="members_tbl";

    protected $fillable =[
        'fname',
        'lname',
        'gender',
        'msisdn',
        'email',
        'status',
        'no_of_children',
        'occupation',
        'age',
        'bna',
        'residence'
    ];
}

This is the result of var_dump($request)

 public 'request' =>
    object(Symfony\Component\HttpFoundation\InputBag)[44]
      protected 'parameters' =>
        array (size=13)
          '_token' => string 'DuNeITGaDF9K7eEMmU4HwX7nVLJUYDaZ1iYGT4dw' (length=40)
          'fname' => string 'Joe' (length=3)
          'lname' => string 'Peski' (length=5)
          'gender' => string 'male' (length=4)
          'msisdn' => string '254722000001' (length=12)
          'email' => string 'joetry@hotmail.com' (length=18)
          'residence' => string 'New Place' (length=9)
          'age' => string 'teen' (length=4)
          'bna' => string 'no' (length=2)
          'mstatus' => string 'single' (length=6)
          'kids' => string '4' (length=1)
          'profession' => string 'IT' (length=2)
          'submit' => string 'Submit' (length=6)

Body:
Validator doesn't read your status. Make sure you have a default value for this field.

If status is not required, you can change required to nullable, then create a default value after validation.

You need to display an error message to know what the error is.

$errors = $validator->errors();

Usually, this case occurs when you use a select box, check box, or something that can't read a value or empty, null.

The solution is to add a default value or add a hidden field with a default value.

<input type="hidden" name="status" value="0">
<select name="status">
    ...
</select>


问:
the '%' symbol is shown as '?' in ms-outlook on passing htmltext from flex
I am trying to pass htmltext which contains '%' symbol as a deafult template to ms-outlook.
The problem is that '%' symbol gets conveted to '?' in ms-outlook.

what should i do to get '%' symbol instead of '?'.

Thanks in Advance. :)

答: Try replacing the % sign with its url encoded equivalent %25 . I assume you're opening a mailto: link with the body appended as a url parameter, which is where outlook gets confused with the encoding.</p>


问:
Upload a newer version of document from within Alfresco repository
I have a two documents (a.pdf and b.pdf) in the Alfresco repository. I want to apply/upload b.pdf as a new version of a.pdf. Is there any way that I can do this using Javascript or a java code?

Thank you

答:
Create Document, Make it Versionable, Modify It
Creates a document, makes it versionable, checks it out, modifies the content of the working copy, checks it in again and then repeats the process but checks in the document with a version history note and as a major version increment:

```<code>// create file, make it versionable
var doc = userhome.createFile('checkmeout.txt');
doc.addAspect('cm:versionable');
doc.content = 'original text';

// check it out and update content on the working copy
var workingCopy = doc.checkout();
workingCopy.content = 'updated text 1';

// check it in
doc = workingCopy.checkin();

// check it out again
workingCopy = doc.checkout();
workingCopy.content = 'updated text 2';

// check it in again, but with a version history note and as major version increment
doc = workingCopy.checkin('a history note', true);
</code>```

You can take reference from below javascript api link
https://hub.alfresco.com/t5/alfresco-content-services-hub/javascript-api-cookbook/ba-p/293260

Body:
Create Document, Make it Versionable, Modify It
Creates a document, makes it versionable, checks it out, modifies the content of the working copy, checks it in again and then repeats the process but checks in the document with a version history note and as a major version increment:

// create file, make it versionable
var doc = userhome.createFile('checkmeout.txt');
doc.addAspect('cm:versionable');
doc.content = 'original text';

// check it out and update content on the working copy
var workingCopy = doc.checkout();
workingCopy.content = 'updated text 1';

// check it in
doc = workingCopy.checkin();

// check it out again
workingCopy = doc.checkout();
workingCopy.content = 'updated text 2';

// check it in again, but with a version history note and as major version increment
doc = workingCopy.checkin('a history note', true);

You can take reference from below javascript api link
https://hub.alfresco.com/t5/alfresco-content-services-hub/javascript-api-cookbook/ba-p/293260


问:
How to add single item between two grid row in android
Hello guys I want to display one single item between two grid row items.

I want this type of out.

I'm try this way but it didn't work.

My Activity layout XML activity_grid_with_single_rv.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activitry.GridWithSingleRVActivity">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvGridWithSingle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"/>
</LinearLayout>
</code>```

My Activity class GridWithSingleRVActivity.java

```<code>public class GridWithSingleRVActivity extends AppCompatActivity {
    private RecyclerView rvGridWithSingle;
    private GridWIthSingleRVAdapter gridWIthSingleRVAdapter;
    private ArrayList<GridWithSingle> gridWithSingles=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_with_single_rv);
        rvGridWithSingle=findViewById(R.id.rvGridWithSingle);
        getGridWithSingles();
        rvGridWithSingle.setLayoutManager(new GridLayoutManager(this,2));
        gridWIthSingleRVAdapter=new GridWIthSingleRVAdapter(this,gridWithSingles);
        rvGridWithSingle.setAdapter(gridWIthSingleRVAdapter);
    }

    private ArrayList<GridWithSingle> getGridWithSingles(){
        gridWithSingles.clear();
        gridWithSingles=new ArrayList<>();
        int addSingleCnt=0;
        for (int i=0;i<20;i++){
            gridWithSingles.add(new GridWithSingle(i+1,"GRID : "+(i+1)));
            if (addSingleCnt==1){
                addSingleCnt=0;
                gridWithSingles.add(new GridWithSingle(-1,"Single : "));
            }else {
                addSingleCnt++;
            }
        }
        return gridWithSingles;
    }
}
</code>```

My Adapter class GridWIthSingleRVAdapter.java

```<code>public class GridWIthSingleRVAdapter extends RecyclerView.Adapter<GridWIthSingleRVAdapter.GridWIthSingleRVVH> {

    private Context context;
    private ArrayList<GridWithSingle> gridWithSingles=new ArrayList<>();
    private final int GRID_LAYOUT=1;
    private final int SINGLE_LAYOUT=0;

    public GridWIthSingleRVAdapter(Context context, ArrayList<GridWithSingle> gridWithSingles) {
        this.context = context;
        this.gridWithSingles = gridWithSingles;
    }

    @NonNull
    @Override
    public GridWIthSingleRVVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType==GRID_LAYOUT)
        return new GridWIthSingleRVVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.row_grid_item,parent,false));
        else
        return new GridWIthSingleRVVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.row_single_item,parent,false));

    }

    @Override
    public void onBindViewHolder(@NonNull GridWIthSingleRVVH holder, int position) {
        if (holder.getItemViewType()==GRID_LAYOUT){
            holder.txtGrid.setText(gridWithSingles.get(position).getName());
        }else {
            holder.txtSingle.setText(gridWithSingles.get(position).getName());
        }
    }

    @Override
    public int getItemCount() {
        return gridWithSingles.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (gridWithSingles.get(position).getId()==-1){
            return SINGLE_LAYOUT;
        }else {
            return GRID_LAYOUT;
        }
    }

    public class GridWIthSingleRVVH extends RecyclerView.ViewHolder{
        private TextView txtGrid,txtSingle;
        public GridWIthSingleRVVH(@NonNull View itemView) {
            super(itemView);
            txtGrid=itemView.findViewById(R.id.txtGrid);
            txtSingle=itemView.findViewById(R.id.txtSingle);
        }
    }
}
</code>```

Two layout item xml

grid_item.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/cvGrid"
        android:layout_margin="10dp"
        app:cardCornerRadius="5dp"
        app:cardElevation="5dp"
        app:cardBackgroundColor="#EF9A9A">
        <TextView
            android:id="@+id/txtGrid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GRID"
            android:layout_gravity="center"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="@color/black"/>
    </androidx.cardview.widget.CardView>
</LinearLayout>
</code>```

single_item.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/cvSingle"
        android:layout_margin="10dp"
        app:cardCornerRadius="5dp"
        app:cardElevation="5dp"
        app:cardBackgroundColor="#CE93D8">
        <TextView
            android:id="@+id/txtSingle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SINGLE"
            android:layout_gravity="center"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="@color/black"/>
    </androidx.cardview.widget.CardView>
</LinearLayout>
</code>```

Output

答:
You need to specify a spanSizeLookup for the affected columns to the layoutManager.

A couple of years ago I wrote a similar proof of concepts where the idea was to insert "ads" every 4 rows.

The project is located on GitHub.

The sample does this the trick directly in the activity by using recyclerView types and modifying the span size.

```<code>layoutManager = GridLayoutManager(this, 2)
mainRecyclerView.layoutManager = layoutManager
mainRecyclerView.adapter = adapter

layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return when (adapter.getItemViewType(position)) {
                    adapter.viewTypeGreen -> 1
                    adapter.viewTypePurple -> 1
                    adapter.viewTypeAd -> 2
                    else -> -1
                }
            }
        }
</code>```

The repository that provides this data simulates inserting a different type every 4 items

Body:
Hello guys I want to display one single item between two grid row items.

I want this type of out.

I'm try this way but it didn't work.

My Activity layout XML activity_grid_with_single_rv.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activitry.GridWithSingleRVActivity">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvGridWithSingle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="5dp"/>
</LinearLayout>

My Activity class GridWithSingleRVActivity.java

public class GridWithSingleRVActivity extends AppCompatActivity {
    private RecyclerView rvGridWithSingle;
    private GridWIthSingleRVAdapter gridWIthSingleRVAdapter;
    private ArrayList<GridWithSingle> gridWithSingles=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_with_single_rv);
        rvGridWithSingle=findViewById(R.id.rvGridWithSingle);
        getGridWithSingles();
        rvGridWithSingle.setLayoutManager(new GridLayoutManager(this,2));
        gridWIthSingleRVAdapter=new GridWIthSingleRVAdapter(this,gridWithSingles);
        rvGridWithSingle.setAdapter(gridWIthSingleRVAdapter);
    }

    private ArrayList<GridWithSingle> getGridWithSingles(){
        gridWithSingles.clear();
        gridWithSingles=new ArrayList<>();
        int addSingleCnt=0;
        for (int i=0;i<20;i++){
            gridWithSingles.add(new GridWithSingle(i+1,"GRID : "+(i+1)));
            if (addSingleCnt==1){
                addSingleCnt=0;
                gridWithSingles.add(new GridWithSingle(-1,"Single : "));
            }else {
                addSingleCnt++;
            }
        }
        return gridWithSingles;
    }
}

My Adapter class GridWIthSingleRVAdapter.java

public class GridWIthSingleRVAdapter extends RecyclerView.Adapter<GridWIthSingleRVAdapter.GridWIthSingleRVVH> {

    private Context context;
    private ArrayList<GridWithSingle> gridWithSingles=new ArrayList<>();
    private final int GRID_LAYOUT=1;
    private final int SINGLE_LAYOUT=0;

    public GridWIthSingleRVAdapter(Context context, ArrayList<GridWithSingle> gridWithSingles) {
        this.context = context;
        this.gridWithSingles = gridWithSingles;
    }

    @NonNull
    @Override
    public GridWIthSingleRVVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType==GRID_LAYOUT)
        return new GridWIthSingleRVVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.row_grid_item,parent,false));
        else
        return new GridWIthSingleRVVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.row_single_item,parent,false));

    }

    @Override
    public void onBindViewHolder(@NonNull GridWIthSingleRVVH holder, int position) {
        if (holder.getItemViewType()==GRID_LAYOUT){
            holder.txtGrid.setText(gridWithSingles.get(position).getName());
        }else {
            holder.txtSingle.setText(gridWithSingles.get(position).getName());
        }
    }

    @Override
    public int getItemCount() {
        return gridWithSingles.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (gridWithSingles.get(position).getId()==-1){
            return SINGLE_LAYOUT;
        }else {
            return GRID_LAYOUT;
        }
    }

    public class GridWIthSingleRVVH extends RecyclerView.ViewHolder{
        private TextView txtGrid,txtSingle;
        public GridWIthSingleRVVH(@NonNull View itemView) {
            super(itemView);
            txtGrid=itemView.findViewById(R.id.txtGrid);
            txtSingle=itemView.findViewById(R.id.txtSingle);
        }
    }
}

Two layout item xml

grid_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/cvGrid"
        android:layout_margin="10dp"
        app:cardCornerRadius="5dp"
        app:cardElevation="5dp"
        app:cardBackgroundColor="#EF9A9A">
        <TextView
            android:id="@+id/txtGrid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="GRID"
            android:layout_gravity="center"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="@color/black"/>
    </androidx.cardview.widget.CardView>
</LinearLayout>

single_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/cvSingle"
        android:layout_margin="10dp"
        app:cardCornerRadius="5dp"
        app:cardElevation="5dp"
        app:cardBackgroundColor="#CE93D8">
        <TextView
            android:id="@+id/txtSingle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SINGLE"
            android:layout_gravity="center"
            android:textStyle="bold"
            android:textSize="18sp"
            android:textColor="@color/black"/>
    </androidx.cardview.widget.CardView>
</LinearLayout>

Output

Body:
You need to specify a spanSizeLookup for the affected columns to the layoutManager.

A couple of years ago I wrote a similar proof of concepts where the idea was to insert "ads" every 4 rows.

The project is located on GitHub.

The sample does this the trick directly in the activity by using recyclerView types and modifying the span size.

layoutManager = GridLayoutManager(this, 2)
mainRecyclerView.layoutManager = layoutManager
mainRecyclerView.adapter = adapter

layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return when (adapter.getItemViewType(position)) {
                    adapter.viewTypeGreen -> 1
                    adapter.viewTypePurple -> 1
                    adapter.viewTypeAd -> 2
                    else -> -1
                }
            }
        }

The repository that provides this data simulates inserting a different type every 4 items


问:
What are "other" requests in Cosmos DB insights when creating items?
My database is configured to auto scale from 500 to 5000RUs/s.
Once a day I'm running an import where about 2.5 million items are created. The parition key is the date in format "2022-02-10". I'm using bulk updates and transactional batches.

I can observe two things:

I'm getting status 429 pretty quickly

There are many "other" requests showing up in Insights (see below)

What are the "other" requests I see here? I'm only creating items, nothing else queries the DB. Or could these be the transactional batches not showing up as individual creates?

答:
After some more testing I can confirm that transactional batches end up as "other" in Insights, even if they include only create operations.

This also means it has nothing to do with the 429s.


问:
Polyfit issue with vector sizes even though size() function shows they're the same
I am receiving this error message, but I've printed the size of my two vectors and they're identical. I'm not sure what else could be causing it

答: The third argument to polyfit should be a number indicating the degree of the polynomial.  You've given it a string, which is confusing it.  If you want a linear fit, use polyfit(x, y, 1).


问:
How to test RxJs observable callback with NgRx setState
I would like to know how to test the code inside a .subscribe callback, with the subscription being on a NgRx store selector.

Environment: Angular 13, RxJs 7+, NgRx 13, Jest 27

Consider

my-component.ts

```<code>...
ngOnInit {
  this.myValue = true;
  this.store.select(mySelector).pipe(filter(data => data.attribute === true)).subscribe(data => {
    this.myValue = false; // I want to test this
  }
}
...
</code>```

my-component.spec.ts

```<code>describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let store: MockStore;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [...],
      providers: [
        provideMockStore({
          initialState: { myFeature: { } },
        }),
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    store = TestBed.inject(MockStore);
  });

  it('should perform animation & redirect to /dashboard if login successful', () => {
    store.setState({
      myFeature: {
        ...
        attribute: true,
      },
    });

    expect(component.myValue).toBe(false);
  });
</code>```

This works, but it's random. Since this is asynchronous I could test myValue before the subscribe callback has been called and the test would fail, for example if my subscribe callback takes time to do stuff, like so (I'm adding a delay of 500ms) :

```<code>...
ngOnInit {
  this.myValue = true;
  this.store.select(mySelector).pipe(filter(data => data.attribute === true), delay(500)).subscribe(data => {
    this.myValue = false; // I want to test this
  }
}
...
</code>```

This fails.

How can I wait the callback to perform before testing my value ? I could wait an arbitrary time like 1 sec before testing, but it could break at any time in the future it's not robust enough. Like :

```<code>it('should perform animation & redirect to /dashboard if login successful',
async () => {
    store.setState({
      myFeature: {
        ...
        attribute: true,
      },
    });
    await lastValueFrom(timer(600)); //rxjs 7
    expect(component.myValue).toBe(false);
  });
</code>```

Thanks for your help

答:
Use waitForAsync and fixture.whenStable to ensure completion of async tasks before evaluating the expect.

```<code>it('should perform animation & redirect to /dashboard if login successful', waitForAsync(() => {
    store.setState({
      myFeature: {
        ...
        attribute: true,
      },
    });

    fixture.whenStable()
      .then(() => expect(component.myValue).toBe(false));
  }));
</code>```

Body:
I would like to know how to test the code inside a .subscribe callback, with the subscription being on a NgRx store selector.

Environment: Angular 13, RxJs 7+, NgRx 13, Jest 27

Consider

my-component.ts

...
ngOnInit {
  this.myValue = true;
  this.store.select(mySelector).pipe(filter(data => data.attribute === true)).subscribe(data => {
    this.myValue = false; // I want to test this
  }
}
...

my-component.spec.ts

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let store: MockStore;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [...],
      providers: [
        provideMockStore({
          initialState: { myFeature: { } },
        }),
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    store = TestBed.inject(MockStore);
  });

  it('should perform animation & redirect to /dashboard if login successful', () => {
    store.setState({
      myFeature: {
        ...
        attribute: true,
      },
    });

    expect(component.myValue).toBe(false);
  });

This works, but it's random. Since this is asynchronous I could test myValue before the subscribe callback has been called and the test would fail, for example if my subscribe callback takes time to do stuff, like so (I'm adding a delay of 500ms) :

...
ngOnInit {
  this.myValue = true;
  this.store.select(mySelector).pipe(filter(data => data.attribute === true), delay(500)).subscribe(data => {
    this.myValue = false; // I want to test this
  }
}
...

This fails.

How can I wait the callback to perform before testing my value ? I could wait an arbitrary time like 1 sec before testing, but it could break at any time in the future it's not robust enough. Like :

it('should perform animation & redirect to /dashboard if login successful',
async () => {
    store.setState({
      myFeature: {
        ...
        attribute: true,
      },
    });
    await lastValueFrom(timer(600)); //rxjs 7
    expect(component.myValue).toBe(false);
  });

Thanks for your help

Body:
Use waitForAsync and fixture.whenStable to ensure completion of async tasks before evaluating the expect.

it('should perform animation & redirect to /dashboard if login successful', waitForAsync(() => {
    store.setState({
      myFeature: {
        ...
        attribute: true,
      },
    });

    fixture.whenStable()
      .then(() => expect(component.myValue).toBe(false));
  }));


问:
How do you copy the contents of a Cell into the Clipboard
I'm trying to copy the cell contents into the clipboard.

I've read and tried the exact example provided in the Excel 2007 Help file. However for some reason the DataObject object is not valid. So the example:

```<code>Dim MyData As DataObject

Private Sub CommandButton1_Click()
    Set MyData = New DataObject

    MyData.SetText TextBox1.Text
    MyData.PutInClipboard

    TextBox2.Paste
End Sub

Private Sub UserForm_Initialize()
    TextBox1.Text = "Move this data to a " _
        & "DataObject, to the Clipboard, then to " _
        & "TextBox2!"
End Sub
</code>```

Does not work in my case. I've searched for a good while now and I can not find an answer to why the DataObject object is not available.

Here is my code:

```<code>Dim MyData As DataObject

Private Sub Worksheet_Change(ByVal Target As Range)
    If ActiveCell.Column = 3 Then
        Set MyData = New DataObject
        MyData.SetText ActiveCell.Offset(-1, -1).Text
        MyData.PutInclipboard
    End If
End Sub
</code>```

Error on Compile is: "User-Defined type not defined" and it highlights the "MyData As DataObject" line.

Is there another method to simply copying the text in a cell to the clipboard?

答:
Ok, few things:

First you need to Add a reference to "Microsoft Forms 2.0 Object Library", if you don't feel like searching through, just add a user form to the project and then immediately delete it, the reference will stay. You need that reference to use DataObject

I'll attach some code that I got to work, I changed the offsets but make them whatever you need...

```<code>Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Set MyData = New DataObject
    If ActiveCell.Column = 3 Then
        MyData.SetText ActiveCell.Offset(-1, 0).Text
        MyData.PutInClipboard
    End If
End Sub
</code>```

OwnerDisplayName: Brian Boatright

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to copy the cell contents into the clipboard.

I've read and tried the exact example provided in the Excel 2007 Help file. However for some reason the DataObject object is not valid. So the example:

Dim MyData As DataObject

Private Sub CommandButton1_Click()
    Set MyData = New DataObject

    MyData.SetText TextBox1.Text
    MyData.PutInClipboard

    TextBox2.Paste
End Sub

Private Sub UserForm_Initialize()
    TextBox1.Text = "Move this data to a " _
        & "DataObject, to the Clipboard, then to " _
        & "TextBox2!"
End Sub

Does not work in my case. I've searched for a good while now and I can not find an answer to why the DataObject object is not available.

Here is my code:

Dim MyData As DataObject

Private Sub Worksheet_Change(ByVal Target As Range)
    If ActiveCell.Column = 3 Then
        Set MyData = New DataObject
        MyData.SetText ActiveCell.Offset(-1, -1).Text
        MyData.PutInclipboard
    End If
End Sub

Error on Compile is: "User-Defined type not defined" and it highlights the "MyData As DataObject" line.

Is there another method to simply copying the text in a cell to the clipboard?

Body:
Ok, few things:

First you need to Add a reference to "Microsoft Forms 2.0 Object Library", if you don't feel like searching through, just add a user form to the project and then immediately delete it, the reference will stay. You need that reference to use DataObject

I'll attach some code that I got to work, I changed the offsets but make them whatever you need...

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Set MyData = New DataObject
    If ActiveCell.Column = 3 Then
        MyData.SetText ActiveCell.Offset(-1, 0).Text
        MyData.PutInClipboard
    End If
End Sub

OwnerDisplayName: curtisk


问:
Flutter: detect if device has "back navigation" built into the OS?
In Flutter, I would like to know if the device has any functionality built into the OS for navigating back. Or in other words, if the user can trigger navigation without having an actual button within the app.

For example, an iPhone 7 does not have a physical back button or a swipe-back gesture. If the app doesn't have it's own way to navigate, the user can get stuck.

On the contrary, most modern devices have some way of going back built into the system, like a physical/virtual back button or a swipe-back gesture.

Can I distinguish between these types of devices?

答:
From what I have seen it is only IOS that do this, so it can be done with:

```<code> if (Platform.isIOS){
#show backButton();
}
</code>```

But I have not seen a package or function that specifically lets you know this information. Keep me in the loop if you find anything

Body:
From what I have seen it is only IOS that do this, so it can be done with:

 if (Platform.isIOS){
#show backButton();
}

But I have not seen a package or function that specifically lets you know this information. Keep me in the loop if you find anything


问:
Looping through a nested list and summing all elements of each internal list in python
My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

```<code>All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)

print (Summed_list)
</code>```

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

答:
You can use the built-in map function. It maps a function to a list of  iterables.

```<code>map(function, list-of-iterables)
</code>```

Since Python 3 this will get you a map-generator, therefore you might want to make it a list, set or whatever iterable you prefer.

```<code>list(map(sum, list-of-iterables))
</code>```

So in your case:

```<code>>>> All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
>>> summed_list = list(map(sum, All_slips))
>>> print(summed_list)
[10, 16, 19]
</code>```

Body:
My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)

print (Summed_list)

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

Body:
You can use the built-in map function. It maps a function to a list of  iterables.

map(function, list-of-iterables)

Since Python 3 this will get you a map-generator, therefore you might want to make it a list, set or whatever iterable you prefer.

list(map(sum, list-of-iterables))

So in your case:

>>> All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
>>> summed_list = list(map(sum, All_slips))
>>> print(summed_list)
[10, 16, 19]


问:
Scrap info from htm with Beautifulsoup
Good morning, i can't find the data correctly with beautifulsoup, can you help me? i want to get the last numbers of this html:
i want to have only the employee id ( 22219 )</p>
```<code>    <td class="day list-item">
<div class="allocation-day click-area clickable" data-date="2022-02-07" data-url="anonymous-duty-details?beginDate=2022-02-07&allocatedEmployeeId=22219">
<div class="day-info">
<div class="date-with-type">7</div>
<div class="weekday">Mo.</div>
<div class="row-status-icons">
</code>```
```<code>
from bs4 import BeautifulSoup as bs

url = ('20105.html')
with open(url, 'r') as f:
    contents = f.read()
    soup = bs(contents, features="html.parser")

userfinder = soup.find_all('data-url', class_='')
tutte = soup.find_all('div', attrs={"data-url":"data-url"})
print(tutte)

print(tutte)
print(userfinder)

</code>```

答:
You could select your targets more specific - In this case css selectors are used two select all div with an attribute data-url:

```<code>soup.select('div[data-url]')
</code>```

To get the values from the resultset you have to iterate it:

```<code>for url in soup.select('div[data-url]'):
    print(url['data-url'])
##output
anonymous-duty-details?beginDate=2022-02-07&allocatedEmployeeId=22219
</code>```

Getting only the ids a simple approache could be to split() the url-string, but be aware only if structure is still the same, else you have to use regex or other approaches:

```<code>for url in soup.select('div[data-url]'):
    print(url['data-url'].split('=')[-1])

##output
22219
</code>```

Simple regex approache:

```<code>import re

for url in soup.select('div[data-url]'):
    print(re.search(r"allocatedEmployeeId=(\d*)",url['data-url']).group(1))

##output
22219
</code>```

EDIT

Getting only the first result use select_one():

```<code>soup.select_one('div[data-url]')['data-url'].split('=')[-1]
</code>```

or

```<code>import re

re.search(r"allocatedEmployeeId=(\d*)",soup.select_one('div[data-url]')['data-url']).group(1)
</code>```

Title: Scrap info from htm with Beautifulsoup

Body:
Good morning, i can't find the data correctly with beautifulsoup, can you help me? i want to get the last numbers of this html:
i want to have only the employee id ( 22219 )

7

Mo.

from bs4 import BeautifulSoup as bs

url = ('20105.html')
with open(url, 'r') as f:
    contents = f.read()
    soup = bs(contents, features="html.parser")

userfinder = soup.find_all('data-url', class_='')
tutte = soup.find_all('div', attrs={"data-url":"data-url"})
print(tutte)

print(tutte)
print(userfinder)

Body:
You could select your targets more specific - In this case css selectors are used two select all div with an attribute data-url:

soup.select('div[data-url]')

To get the values from the resultset you have to iterate it:

for url in soup.select('div[data-url]'):
    print(url['data-url'])
##output
anonymous-duty-details?beginDate=2022-02-07&allocatedEmployeeId=22219

Getting only the ids a simple approache could be to split() the url-string, but be aware only if structure is still the same, else you have to use regex or other approaches:

for url in soup.select('div[data-url]'):
    print(url['data-url'].split('=')[-1])

##output
22219

Simple regex approache:

import re

for url in soup.select('div[data-url]'):
    print(re.search(r"allocatedEmployeeId=(\d*)",url['data-url']).group(1))

##output
22219

EDIT

Getting only the first result use select_one():

soup.select_one('div[data-url]')['data-url'].split('=')[-1]

or

import re

re.search(r"allocatedEmployeeId=(\d*)",soup.select_one('div[data-url]')['data-url']).group(1)


问:
Transform request data in Krakrnd with lua
Using Krakend as api gateway.

I have an endpoint configured in krakend.json:

```<code>"endpoint":"/call",
"extra_config":{
   "github.com/devopsfaith/krakend-lua/proxy":{
      "sources":[
         "/function.lua"
      ],
      "pre":"pre_backend(request.load())",
      "live":true,
      "allow_open_libs":true
   }
},
"method":"POST",
"output_encoding":"json",
"headers_to_pass":[
   "*"
],
"backend":[
   {
      "url_pattern":"/api/v1/get_client_id",
    [...]]
},
</code>```

The endopont "/api/v1/get_client_id" recives just a param:

```<code>{"user_mail_1":"test@test.es"}
</code>```

I want, whith the lua script my endopoint "/call" recives:

```<code>{"email":"test@test.es"}
</code>```

and transform on before send:

```<code>{"user_mail_1":"test@test.es"}
</code>```

I tried with gsub, but use body() as "string" is no efficient.

```<code>    function pre_backend( req )
      print('--Backend response, pre-logic:');
      local r = req;
      r:params('test','test');
      r:query('lovelyquery')
      r:body('test','test');
      lolcal v = r:body():gsub('email', 'user_mail_1')
...
</code>```

Is a way to parse "req" as a table, dict or something i can transform data?

Is another way to transform REQUEST data?

EXAMPLE WORKING WITH GSUB:

```<code>function pre_backend( req )
  print('--Backend response, pre-logic:');
  print('--req');
  print(req);
  print(type(req));
  local r = req;
  print('--body');
  print(type(r:body()));
  print(r:body())
  local body_transformed = r:body():gsub('email', 'user_mail_1');
  print('--body_transformed');
  print(body_transformed);
  print(type(body_transformed));
end
</code>```

Console output:

```<code>2022/02/11 09:59:52  DEBUG: [http-server-handler: no extra config]
--Backend response, pre-logic:
--req
userdata: 0xc0004f9b60
userdata
--body
string
{"email" : "test@test.es","test_field":"email"}
--body_transformed
{"user_mail_1" : "test@test.es","test_field":"user_mail_1"}
string
</code>```

As we can see the gsub is not efficient becouse replace all strings.
If I can work with req as table, dict or something similar, I can replace dict key/value. ex: req['xxx] = 'xxx' or iterate req.keys

答:
gsub stands for global substitution. It replaces all occurances of the pattern in the string.

If you just want to replace "email" infront of an email address simply use a pattern that takes this into account.

```<code>print((r:body():gsub('(")(email)("%s-:%s-"%w+@%w+%.%w+")', "%1user_mail_1%3")))
</code>```

Alternatively if you knwo that you only want to replace the first occurance of email you can simply do this:

```<code>print((r:body():gsub("email", "user_mail_1", 1)))
</code>```

The thrid parameter will stop gsub after the first replacement.

Body:
Using Krakend as api gateway.

I have an endpoint configured in krakend.json:

"endpoint":"/call",
"extra_config":{
   "github.com/devopsfaith/krakend-lua/proxy":{
      "sources":[
         "/function.lua"
      ],
      "pre":"pre_backend(request.load())",
      "live":true,
      "allow_open_libs":true
   }
},
"method":"POST",
"output_encoding":"json",
"headers_to_pass":[
   "*"
],
"backend":[
   {
      "url_pattern":"/api/v1/get_client_id",
    [...]]
},

The endopont "/api/v1/get_client_id" recives just a param:

{"user_mail_1":"test@test.es"}

I want, whith the lua script my endopoint "/call" recives:

{"email":"test@test.es"}

and transform on before send:

{"user_mail_1":"test@test.es"}

I tried with gsub, but use body() as "string" is no efficient.

    function pre_backend( req )
      print('--Backend response, pre-logic:');
      local r = req;
      r:params('test','test');
      r:query('lovelyquery')
      r:body('test','test');
      lolcal v = r:body():gsub('email', 'user_mail_1')
...

Is a way to parse "req" as a table, dict or something i can transform data?

Is another way to transform REQUEST data?

EXAMPLE WORKING WITH GSUB:

function pre_backend( req )
  print('--Backend response, pre-logic:');
  print('--req');
  print(req);
  print(type(req));
  local r = req;
  print('--body');
  print(type(r:body()));
  print(r:body())
  local body_transformed = r:body():gsub('email', 'user_mail_1');
  print('--body_transformed');
  print(body_transformed);
  print(type(body_transformed));
end

Console output:

2022/02/11 09:59:52  DEBUG: [http-server-handler: no extra config]
--Backend response, pre-logic:
--req
userdata: 0xc0004f9b60
userdata
--body
string
{"email" : "test@test.es","test_field":"email"}
--body_transformed
{"user_mail_1" : "test@test.es","test_field":"user_mail_1"}
string

As we can see the gsub is not efficient becouse replace all strings.
If I can work with req as table, dict or something similar, I can replace dict key/value. ex: req['xxx] = 'xxx' or iterate req.keys

Body:
gsub stands for global substitution. It replaces all occurances of the pattern in the string.

If you just want to replace "email" infront of an email address simply use a pattern that takes this into account.

print((r:body():gsub('(")(email)("%s-:%s-"%w+@%w+%.%w+")', "%1user_mail_1%3")))

Alternatively if you knwo that you only want to replace the first occurance of email you can simply do this:

print((r:body():gsub("email", "user_mail_1", 1)))

The thrid parameter will stop gsub after the first replacement.


问:
Easiest and quickest way to authenticate GKE when creating GKE cluster via terraform
I'm trying to create a GKE cluster via terraform on a test project, however it now asks me for a more complicated means of authentication and I was wondering if there is a nice quick  and easy way to authenticate? Like a copy-paste password or so?</p>

答:
Assuming you are just running this from the command line, you'll need to install the gcloud CLI and then run the following command prior to running Terraform:

```<code>gcloud init
gcloud auth application-default login
</code>```

You can check out https://learn.hashicorp.com/tutorials/terraform/gke for more info.

Note:  for a real automated deployment, you would not want to use gcloud auth application-default login but rather you'd set up a service account.

Body:
Assuming you are just running this from the command line, you'll need to install the gcloud CLI and then run the following command prior to running Terraform:

gcloud init
gcloud auth application-default login

You can check out https://learn.hashicorp.com/tutorials/terraform/gke for more info.

Note:  for a real automated deployment, you would not want to use gcloud auth application-default login but rather you'd set up a service account.


问:
conditional updateMany in MongoDB
I'm attempting to do a conditional update on all documents with a "Song Rating" greater than 9 in PyMongo. If the above condition is met, I want to add a condition to the document called "is_hit_song" and set its value to True.

```<code>collection.updateMany(
{'Song Rating': { '$gt': 9 }},
{'$set': {'is_hit_song': True}}, upsert=False, array_filters=None)
</code>```

This is what I have tried, but I can't seem to execute the update because I get the error below.

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-110-2c2bc2715e77> in <module>()
      3 collection.updateMany(
      4     {'Song Rating': { '$gt': 9 }},
----> 5     {'$set': {'is_hit_song': True}},  upsert=False, array_filters=None)

/usr/local/lib/python3.7/dist-packages/pymongo/collection.py in __call__(self, *args, **kwargs)
   3319                         "call the '%s' method on a 'Collection' object it is "
   3320                         "failing because no such method exists." %
-> 3321                         self.__name.split(".")[-1])

TypeError: 'Collection' object is not callable. If you meant to call the 'updateMany' method on a 'Collection' object it is failing because no such method exists.
</code>```

Can anyone help me understand what I'm doing wrong?

答:
In pymongo the method is named update_many()

see an example here

Title: conditional updateMany in MongoDB

Body:
I'm attempting to do a conditional update on all documents with a "Song Rating" greater than 9 in PyMongo. If the above condition is met, I want to add a condition to the document called "is_hit_song" and set its value to True.

collection.updateMany(
{'Song Rating': { '$gt': 9 }},
{'$set': {'is_hit_song': True}}, upsert=False, array_filters=None)

This is what I have tried, but I can't seem to execute the update because I get the error below.

TypeError                                 Traceback (most recent call last)
<ipython-input-110-2c2bc2715e77> in <module>()
      3 collection.updateMany(
      4     {'Song Rating': { '$gt': 9 }},
----> 5     {'$set': {'is_hit_song': True}},  upsert=False, array_filters=None)

/usr/local/lib/python3.7/dist-packages/pymongo/collection.py in __call__(self, *args, **kwargs)
   3319                         "call the '%s' method on a 'Collection' object it is "
   3320                         "failing because no such method exists." %
-> 3321                         self.__name.split(".")[-1])

TypeError: 'Collection' object is not callable. If you meant to call the 'updateMany' method on a 'Collection' object it is failing because no such method exists.

Can anyone help me understand what I'm doing wrong?


问:
Error when running migrate and seed together
I have been running

rake db:drop db:create db:migrate db:seed

in development.  This has been working fine...up until today.  Multiple people on my team are seeing this with a specific application.  Now we get error when seeding the database.  The last migration renames a column (this migration has been in place for two months).  The rake task crashes when the seed step fires (the seed data has been changed to use the next column name).

This works fine

```<code>rake db:drop db:create db:migrate
rake db:seed
</code>```

I've gone back and checked older commits in my master and they're also breaking.  It's odd that this just started happening on code that has been known to work.

Rails 5.0.2, Ruby 2.3.4, Rake 12.0.0

答:
Same problem with Rails 6.0.3
I have migration that add new columns to existing model, and seed crashes because of this.

Adding

```<code>ApplicationRecord.reset_column_information
</code>```

at the top of seeds.rb
solved the problem.

Body:
I have been running

rake db:drop db:create db:migrate db:seed

in development.  This has been working fine...up until today.  Multiple people on my team are seeing this with a specific application.  Now we get error when seeding the database.  The last migration renames a column (this migration has been in place for two months).  The rake task crashes when the seed step fires (the seed data has been changed to use the next column name).

This works fine

rake db:drop db:create db:migrate
rake db:seed

I've gone back and checked older commits in my master and they're also breaking.  It's odd that this just started happening on code that has been known to work.

Rails 5.0.2, Ruby 2.3.4, Rake 12.0.0

Body:
Same problem with Rails 6.0.3
I have migration that add new columns to existing model, and seed crashes because of this.

Adding

ApplicationRecord.reset_column_information

at the top of seeds.rb
solved the problem.


问:
MySQL : calculate SUM of a Query
i have a mysql query that looks like this :

```<code>select  (pondérée_note*100)/pondérée as b
from answers
where answers.question_id in (select id
                              from questions
                              where categorie_id = 3)
  and user_id = 5
</code>```

The query returns a table b :

```<code>b
50
50
13
25
</code>```

I want to do the sum of those values By

```<code>select SUM(query);
</code>```

but it doesn't work because of a syntax error.

is it possible to sum a query like this ?
Thanks.

答:
Try this:</p>
```<code>select  sum((pondérée_note*100)/pondérée) as sumb
from answers
where answers.question_id in
(select id from questions where categorie_id = 3) and user_id = 5
</code>```

Title: MySQL : calculate SUM of a Query

Body:
i have a mysql query that looks like this :

select  (pondérée_note*100)/pondérée as b
from answers
where answers.question_id in (select id
                              from questions
                              where categorie_id = 3)
  and user_id = 5

The query returns a table b :

b
50
50
13
25

I want to do the sum of those values By

select SUM(query);

but it doesn't work because of a syntax error.

is it possible to sum a query like this ?
Thanks.

Body:
Try this:

select  sum((pondérée_note*100)/pondérée) as sumb
from answers
where answers.question_id in
(select id from questions where categorie_id = 3) and user_id = 5


问:
If I use a class more than once in an application, will it be compiled just once into the exe?
I'm evaluating the many possibilities for a trial protection system and came up with the following question:

If I use my "trial check" class more than once (scattered several times over the application), will it be compiled just once into the exe?

The reason why I'm asking is that if it's only compiled once into the exe, then patching this single class will invalidate all places where it is used.

If it's compiled just once, are there any viable alternatives to prevent this?

Thanks!

EDIT: I'm actually not trying to roll my own protection system, I'm looking at several existing solutions like OnGuard, mxProtector and TRegWare. It was while looking at the various solutions source-code, that I came up with this question.

答:
Just for the principle: There is actually a possibility to have the "same" class compiled multiple times. If you declare the class with a generic type and later have several instances with different instance types, the class code is compiled for each type. The generic class don't even have to make use of the generic type. If you spread the generic instances over different units, the code will be separated, too.</p>

```<code>type
  TDummy<T> = class
  public
    procedure Dummy1;
  end;

procedure TDummy<T>.Dummy1;
begin
  ...
end;

var
  FDummy1: TDummy<Integer>;
  FDummy2: TDummy<Byte>;
  FDummy3: TDummy<TButton>;
  FDummy4: TDummy<TLabel>;
</code>```

Body:
Just for the principle: There is actually a possibility to have the "same" class compiled multiple times. If you declare the class with a generic type and later have several instances with different instance types, the class code is compiled for each type. The generic class don't even have to make use of the generic type. If you spread the generic instances over different units, the code will be separated, too.

type
  TDummy<T> = class
  public
    procedure Dummy1;
  end;

procedure TDummy<T>.Dummy1;
begin
  ...
end;

var
  FDummy1: TDummy<Integer>;
  FDummy2: TDummy<Byte>;
  FDummy3: TDummy<TButton>;
  FDummy4: TDummy<TLabel>;


问:
Adding new column to dataframe and change it to list
Based on the given dataset, I must create a function which takes as input the original dataframe and returns the same dataframe, but with one additional column called subr_faved_by_as_list, where you have the same information as in subr_faved_by, but as a python list instead of a string.

That's my code:

```<code>from urllib import request
import pandas as pd
module_url = f"https://raw.githubusercontent.com/luisespinosaanke/cmt309-portfolio/master/data_portfolio_21.csv"
module_name = module_url.split('/')[-1]
print(f'Fetching {module_url}')
#with open("file_1.txt") as f1, open("file_2.txt") as f2
with request.urlopen(module_url) as f, open(module_name,'w') as outf:
  a = f.read()
  outf.write(a.decode('utf-8'))

df = pd.read_csv('data_portfolio_21.csv')
# this fills empty cells with empty strings
df = df.fillna('')
</code>```
```<code>df.info()

Data columns (total 17 columns):
 #   Column                 Non-Null Count  Dtype
---  ------                 --------------  -----
 0   author                 19940 non-null  object
 1   posted_at              19940 non-null  object
 2   num_comments           19940 non-null  int64
 3   score                  19940 non-null  int64
 4   selftext               19940 non-null  object
 5   subr_created_at        19940 non-null  object
 6   subr_description       19940 non-null  object
 7   subr_faved_by          19940 non-null  object
 8   subr_numb_members      19940 non-null  int64
 9   subr_numb_posts        19940 non-null  int64
 10  subreddit              19940 non-null  object
 11  title                  19940 non-null  object
 12  total_awards_received  19940 non-null  int64
 13  upvote_ratio           19940 non-null  float64
 14  user_num_posts         19940 non-null  int64
 15  user_registered_at     19940 non-null  object
 16  user_upvote_ratio      19940 non-null  float64
dtypes: float64(2), int64(6), object(9)
</code>```

And that's the function

```<code>def transform_faves(df):
    df['subr_faved_by_as_list'] = df['subr_faved_by'].str.split(' ', n = 1, expand = True)

    return df

df = transform_faves(df)
</code>```

I am getting the following error:

```<code>list indices must be integers or slices, not str
</code>```

答:
If use expand=True it return DataFrame, so need omit it, also is possible omit space string for split:

```<code>def transform_faves(df):
    df['subr_faved_by_as_list'] = df['subr_faved_by'].str.split(n = 1)

    return df

df = transform_faves(df)
</code>```

Body:
Based on the given dataset, I must create a function which takes as input the original dataframe and returns the same dataframe, but with one additional column called subr_faved_by_as_list, where you have the same information as in subr_faved_by, but as a python list instead of a string.

That's my code:

from urllib import request
import pandas as pd
module_url = f"https://raw.githubusercontent.com/luisespinosaanke/cmt309-portfolio/master/data_portfolio_21.csv"
module_name = module_url.split('/')[-1]
print(f'Fetching {module_url}')
#with open("file_1.txt") as f1, open("file_2.txt") as f2
with request.urlopen(module_url) as f, open(module_name,'w') as outf:
  a = f.read()
  outf.write(a.decode('utf-8'))

df = pd.read_csv('data_portfolio_21.csv')
# this fills empty cells with empty strings
df = df.fillna('')

df.info()

Data columns (total 17 columns):
 #   Column                 Non-Null Count  Dtype
---  ------                 --------------  -----
 0   author                 19940 non-null  object
 1   posted_at              19940 non-null  object
 2   num_comments           19940 non-null  int64
 3   score                  19940 non-null  int64
 4   selftext               19940 non-null  object
 5   subr_created_at        19940 non-null  object
 6   subr_description       19940 non-null  object
 7   subr_faved_by          19940 non-null  object
 8   subr_numb_members      19940 non-null  int64
 9   subr_numb_posts        19940 non-null  int64
 10  subreddit              19940 non-null  object
 11  title                  19940 non-null  object
 12  total_awards_received  19940 non-null  int64
 13  upvote_ratio           19940 non-null  float64
 14  user_num_posts         19940 non-null  int64
 15  user_registered_at     19940 non-null  object
 16  user_upvote_ratio      19940 non-null  float64
dtypes: float64(2), int64(6), object(9)

And that's the function

def transform_faves(df):
    df['subr_faved_by_as_list'] = df['subr_faved_by'].str.split(' ', n = 1, expand = True)

    return df

df = transform_faves(df)

I am getting the following error:

list indices must be integers or slices, not str

Body:
If use expand=True it return DataFrame, so need omit it, also is possible omit space string for split:

def transform_faves(df):
    df['subr_faved_by_as_list'] = df['subr_faved_by'].str.split(n = 1)

    return df

df = transform_faves(df)


问:
Psql could not connect to server: No such file or directory, 5432 error?
I'm trying to run psql on my Vagrant machine, but I get this error:

```<code>psql: could not connect to server: No such file or directory

Is the server running locally and accepting connections on
Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

Note: Vagrant 1.9.2
Box: ubuntu/trusty64, https://atlas.hashicorp.com/ubuntu/boxes/trusty64

EDIT
Commands I've used in order to install and run postgres:

sudo apt-get update

sudo apt-get install postgresql

sudo su postgres

psql -d postgres -U postgres

答:
I couldn't connect using the psql command and kept getting the error Cannot connect to Server: No such file or directory.

Step 1: Check the status of the Postgres cluster

$ pg_lsclusters

Step 2: Restart the Postgres cluster

$ sudo pg_ctlcluster 12 main start

Make sure to replace 12 with your version of Postgres

Step 3: Check again and connect

$ pg_lsclusters

$ sudo -i -u postgres

$ psql

Body:
I'm trying to run psql on my Vagrant machine, but I get this error:

psql: could not connect to server: No such file or directory

Is the server running locally and accepting connections on
Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Note: Vagrant 1.9.2
Box: ubuntu/trusty64, https://atlas.hashicorp.com/ubuntu/boxes/trusty64

EDIT
Commands I've used in order to install and run postgres:

sudo apt-get update

sudo apt-get install postgresql

sudo su postgres

psql -d postgres -U postgres