问:
MongoDB: How to access the parent of the list when using $where
Data sample

```<code>{
  "Subject": "New thread"
  "Messages": [
    {
      "DateSent": "Mon, 16 May 2011 14:34:17 GMT -04:00",
    },
    {
      "DateSent": "Mon, 16 May 2011 14:59:57 GMT -04:00",
    }
  ],
  "Participants": [
    {
      "UserId": 2,
      "LastReadMessageIndex": 0,
    },
    {
      "UserId": 1,
      "LastReadMessageIndex": 1
    }
  ],
}
</code>```

A thread contains a list of messages and a list of participants. When a participant views a thread, the LastReadMessageIndex gets updated to the length of the Messages.

I want to retrieve the number of threads where there are unread messages for a given participant. I can use the $where operation within my list of participant like this:

```<code>db.MessageThreads.find( {Participants: {$elemMatch: { UserId: 2, $where: {this.LastReadMessageIndex) < this.**parent**.Messages.length}}} }).count();
</code>```

Is it possible to access the parent object?

答:
I think the problem you're having here is that you're pairing $elemMatch and $where. In the context of $where, the value of this should be the document itself. However, it looks like you're saying that this is a sub-document.

Here's some sample code that does what you want:

```<code>unread = function () {
    for (var i in this.Participants) {
        if (this.Participants[i].UserId == 2 &&
            this.Participants[i].LastReadMessageIndex < this.Messages.length) {
                return true;
        }
    }
    return false;
}

db.MessageThreads.find(unread)
</code>```

The only problem here is that I have hard-coded the UserId to 2. If you're planning to call this from one of the client drivers, you'll have to inject that 2 in the right spot.

If it seems a little "hacky", it is. You're trying to compare sub-documents within a single document and MongoDB is not great at this and your document structure does not make this easy.

You may want to consider:

```<code>"Participants": {
  "2": { "LastReadMessageIndex": 0 },
  "1": { "LastReadMessageIndex": 1 }
}
</code>```

This changes won't solve the problem entirely, but it does make they query a lot easier:

```<code>unread = function() {
  return (this.Participants['2'].LastReadMessageIndex <
    this.Messages.length);
}
</code>```

If this is an important query, you may want to consider building a Map / Reduce for this process instead.

Body:
Data sample

{
  "Subject": "New thread"
  "Messages": [
    {
      "DateSent": "Mon, 16 May 2011 14:34:17 GMT -04:00",
    },
    {
      "DateSent": "Mon, 16 May 2011 14:59:57 GMT -04:00",
    }
  ],
  "Participants": [
    {
      "UserId": 2,
      "LastReadMessageIndex": 0,
    },
    {
      "UserId": 1,
      "LastReadMessageIndex": 1
    }
  ],
}

A thread contains a list of messages and a list of participants. When a participant views a thread, the LastReadMessageIndex gets updated to the length of the Messages.

I want to retrieve the number of threads where there are unread messages for a given participant. I can use the $where operation within my list of participant like this:

db.MessageThreads.find( {Participants: {$elemMatch: { UserId: 2, $where: {this.LastReadMessageIndex) < this.**parent**.Messages.length}}} }).count();

Is it possible to access the parent object?

Body:
I think the problem you're having here is that you're pairing $elemMatch and $where. In the context of $where, the value of this should be the document itself. However, it looks like you're saying that this is a sub-document.

Here's some sample code that does what you want:

unread = function () {
    for (var i in this.Participants) {
        if (this.Participants[i].UserId == 2 &&
            this.Participants[i].LastReadMessageIndex < this.Messages.length) {
                return true;
        }
    }
    return false;
}

db.MessageThreads.find(unread)

The only problem here is that I have hard-coded the UserId to 2. If you're planning to call this from one of the client drivers, you'll have to inject that 2 in the right spot.

If it seems a little "hacky", it is. You're trying to compare sub-documents within a single document and MongoDB is not great at this and your document structure does not make this easy.

You may want to consider:

"Participants": {
  "2": { "LastReadMessageIndex": 0 },
  "1": { "LastReadMessageIndex": 1 }
}

This changes won't solve the problem entirely, but it does make they query a lot easier:

unread = function() {
  return (this.Participants['2'].LastReadMessageIndex <
    this.Messages.length);
}

If this is an important query, you may want to consider building a Map / Reduce for this process instead.


来源: stackexchange

问:
Error: Build path specifies execution environment JavaSE-10. There are no JREs installed in the workspace that are strictly compatible.
I'm having issues with setting up the JREs in my VSCode workspace. I thought the issue was correctly setting up my java.home in my settings.json but I'm still getting this error:

Build path specifies execution environment JavaSE-10. There are no JREs installed in the workspace that are strictly compatible.

I've looked at the answer here (Warning - Build path specifies execution environment J2SE-1.4) but the solution is for Eclipse and not VSCode.

I think it is because the JRE is specifying Java10 and I'm using Java11.

Any suggestions on how to set up the JRE for VSCode?

Also, here is the java version I'm using and my settings.

```<code>$ /usr/libexec/java_home -V

Matching Java Virtual Machines (1):
    11.0.1, x86_64: "Java SE 11.0.1"    /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
</code>```

And my java.home settings in VSCode:

"java.home": "/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home"

答:
In my case, I have setup Maven as the build environment for Java within VSCode. For maven, I found that one of the build properties in pom.xml was set to Java version 1.8, which was older than what I was using, namely 1.11. Once I updated the property as below, the warning disappeared.</p>

```<code><properties>
        <java.version>1.11</java.version>
</properties>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having issues with setting up the JREs in my VSCode workspace. I thought the issue was correctly setting up my java.home in my settings.json but I'm still getting this error:

Build path specifies execution environment JavaSE-10. There are no JREs installed in the workspace that are strictly compatible.

I've looked at the answer here (Warning - Build path specifies execution environment J2SE-1.4) but the solution is for Eclipse and not VSCode.

I think it is because the JRE is specifying Java10 and I'm using Java11.

Any suggestions on how to set up the JRE for VSCode?

Also, here is the java version I'm using and my settings.

$ /usr/libexec/java_home -V

Matching Java Virtual Machines (1):
    11.0.1, x86_64: "Java SE 11.0.1"    /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home

And my java.home settings in VSCode:

"java.home": "/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home"

Body:
In my case, I have setup Maven as the build environment for Java within VSCode. For maven, I found that one of the build properties in pom.xml was set to Java version 1.8, which was older than what I was using, namely 1.11. Once I updated the property as below, the warning disappeared.

<properties>
        <java.version>1.11</java.version>
</properties>


问:
footer overlapping over the previous div
I'm not familiar with frontend so having a bit difficulty in creating a layout in html, css3 and bootstrap 4. I've done a little aminaton thing in the background like this https://codepen.io/mohaiman/pen/MQqMyo and after it I'm trying to put another div i.e footer, but it's overlapping. I think it's an issue with positioning. Please see the image attached and suggest some valuable ideas

```<code><div class="page-header image" data-parallax="true" style="background-image: url('./assets/eCommerce_service.png');">
    <div class="filter"></div>
    <br>
    <div class="container-home">
        <div class="row">
            <div class="mx-auto col-md-8 col-lg-6">
                <div class="motto text-center">
                    <img src="assets/logo.png" class="d-block img-fluid">
                </div>
            </div>
            <div class="mx-auto col-md-8">
                <div class="motto text-center">
                    <h1 class="presentation-title presentation-font">WEBBNET DIGITAL</h1>
                    <a href="https://docs.google.com/forms/d/e/1FAIpQLSdjOF6IWFyQxQ-n1WKfUzpyrqYN2gU4iexFAsz6gqrADIioXA/viewform"
                        class="btn btn-round" target="_blank"><i class="fa fa-play">
                        </i>Get free session</a>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="container">
<div class="section section-about-us area">
    <div class="container">
        <div class="row">
            <div class="col-md-8 ml-auto mr-auto text-center">
                <h2 class="title"><strong>Kolkata's Most <span style="color:#de6b28">Trendiest</span> Agency</strong></h2>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12 col-md-7 mx-auto">
                <p>Webbnet Digital is the most creative and trendiest digital marketing agency of Kolkata. We offer some of the highest demanding motion
                     graphics logos, posters banners and all sorts of online promotion.
                    </p>
            </div>
            <div class="col-sm-12 col-md-3 ml-auto margin">
                <img src="assets/seo_home.png" class="img-rounded img-responsive">
            </div>
        </div>
    </div>
    <ul class="circles">
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>
</div>
</code>```

答:
So I started with the Codepen that you shared.

Basically, you need to make the .area div relatively positioned, so that the items that are absolutely positioned will be relative to the container they're within instead of the entire page. For the pen, I was then able to update the height of the circles and drop a footer below it:

Codepen

Body:
I'm not familiar with frontend so having a bit difficulty in creating a layout in html, css3 and bootstrap 4. I've done a little aminaton thing in the background like this https://codepen.io/mohaiman/pen/MQqMyo and after it I'm trying to put another div i.e footer, but it's overlapping. I think it's an issue with positioning. Please see the image attached and suggest some valuable ideas

WEBBNET DIGITAL

                        Get free session

Kolkata's Most Trendiest Agency

Webbnet Digital is the most creative and trendiest digital marketing agency of Kolkata. We offer some of the highest demanding motion
                     graphics logos, posters banners and all sorts of online promotion.


问:
MongoDb Atlas Full text search index rebuilding without downtime
I'm looking for the best approach for making changes (adding new fields) to a production setup full-text search index (added in 4.2)  without having any downtime and affecting my clients.</p>

答: Currently, the only way to accomplish this would be to create a 2nd index with your new definition, and then switch over in your application when the build is complete, and then delete the first index.</p>


问:
Changing user in bash script
I wanted to create an installation script for my raspberry pi which secures the default installation by configuring/hardening ssh, installing a firewall and fail2ban and finally to get rid off the default user of Raspbian. All other parts work but the final part always shows me an error.
The new user is created and added to the sudo group. After that I want to delete the old user 'pi'. As the script runs with sudo in the user context of 'pi' I thought I could solve this by switching to 'su' but I just get an error that the user couldn't be deleted as it is used by a process:

```<code>echo "Enter the new user name? Only lower case letters allowed!"
read user
sudo adduser $user && adduser $user sudo
echo "default user 'pi' will now be deleted"
su -c "deluser -remove-home pi"
</code>```

If I check with 'users' the user 'pi' is gone but I can still log in with this account. How can I solve this problem inside the script?

I tried the answers I found here: How do I use su to execute the rest of the bash script as that user? and here: https://unix.stackexchange.com/questions/361327/how-to-login-as-different-user-inside-shell-script-and-execute-a-set-of-commands but nothing seem to work. I searched Google but I can't find any solution that works. Is it even possible what I'm trying to?

答:
Think i found the cause of the problem. 'set -eux' was a great help:

```<code>deluser pi
 Removing user `pi' ...
 Warning: group `pi' has no more members.
 userdel: user pi is currently used by process 445
 /usr/sbin/deluser: `/usr/sbin/userdel pi' returned error code 8. Exiting.
</code>```

I tried ps -fu pi to find the process which causes the trouble: it's /lib/systemd/systemd --user Is there a way to stop this process inside the script?

Title: Changing user in bash script

Body:
I wanted to create an installation script for my raspberry pi which secures the default installation by configuring/hardening ssh, installing a firewall and fail2ban and finally to get rid off the default user of Raspbian. All other parts work but the final part always shows me an error.
The new user is created and added to the sudo group. After that I want to delete the old user 'pi'. As the script runs with sudo in the user context of 'pi' I thought I could solve this by switching to 'su' but I just get an error that the user couldn't be deleted as it is used by a process:

echo "Enter the new user name? Only lower case letters allowed!"
read user
sudo adduser $user && adduser $user sudo
echo "default user 'pi' will now be deleted"
su -c "deluser -remove-home pi"

If I check with 'users' the user 'pi' is gone but I can still log in with this account. How can I solve this problem inside the script?

I tried the answers I found here: How do I use su to execute the rest of the bash script as that user? and here: https://unix.stackexchange.com/questions/361327/how-to-login-as-different-user-inside-shell-script-and-execute-a-set-of-commands but nothing seem to work. I searched Google but I can't find any solution that works. Is it even possible what I'm trying to?

Body:
Think i found the cause of the problem. 'set -eux' was a great help:

deluser pi
 Removing user `pi' ...
 Warning: group `pi' has no more members.
 userdel: user pi is currently used by process 445
 /usr/sbin/deluser: `/usr/sbin/userdel pi' returned error code 8. Exiting.

I tried ps -fu pi to find the process which causes the trouble: it's /lib/systemd/systemd --user Is there a way to stop this process inside the script?


问:
Bluetooth pairing without user confirmation
Can I pair two devices over Bluetooth without a need to confirm this in user interface, accept to pair this devices. Can I exchange some extra data over, for example NFC, and then safely pair those two devices over Bluetooth without any extra user action?</p>

答:
BT version 2.0 or less - You should be able to pair/bond using a standard PIN code, entered programmatically e.g. 1234 or 0000. This is not very secure but many BT devices do this.

BT version 2.1 or greater - Mode 4 Secure Simple Pairing "just works" model can be used. It uses elliptical encryption (whatever that is) and is very secure but is open to Man In The Middle attacks. Compared to the old '0000' pin code approach it is light years ahead. This doesn't require any user input.

This is according to the Bluetooth specs but what you can use depends on what verson of the Bluetooth standard your stack supports and what API you have.

ContentLicense: CC BY-SA 3.0


问:
How to multiply a dataframe's column by a log using julia?
I have a dataframe. I want to multiply column "b" by a "log" and then replace NaN by 0s.

How can I do that in Julia?
I am checking this: DataFrames.jl
But I do not understand.

```<code>df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]),
           b = repeat([2, 1], outer=[4]),
           c = randn(8))
</code>```

答:
I want to multiply column "b" by a "log"

Assuming you mean you want to apply the (natural) log to each element in column :b, you can do the following:

log.(df.b)

log(x) applies the (natural) log to an individual element x. By putting a dot after the log, you are broadcasting the log function across each element.

If you wanted to replace column b, do the following:

df.b = log.(df.b)

and then replace NaN by 0s

I'm assuming you want to handle the case where you have a DomainError (ie taking the log of a negative number). Your best best is to handle the error before it arises:

map( x -> x <= 0 ? 0.0 : log(x), df.b)

This maps the anonymous function x -> x <= 0 ? 0.0 : log(x) across each element of column b in your DataFrame. This function tests if x is less than zero - if yes then return 0.0 else return log(x). This "one-line if statement" is called a ternary operator.

Body:
I have a dataframe. I want to multiply column "b" by a "log" and then replace NaN by 0s.

How can I do that in Julia?
I am checking this: DataFrames.jl
But I do not understand.

df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]),
           b = repeat([2, 1], outer=[4]),
           c = randn(8))


问:
How to comment out whole sections of a .htaccess file?
Is it possible to comment out one or more sections of an .htaccess file, like you would using /* and */ in various programming languages?</p>

答: Make many files, make your test and put the right file into production, the others ones being alternatives stored as backups just in case. I think that's the most elegant way of doing it because Apache</p>


问:
Array sort NullpointerException
I have a pretty easy for loop I need to use an array in but I need it sorted and finding that I get a NullpointerException when I know the array I am passing is populated.  I'm working with the Array.sort() means my int[] needs to be a generic and also thinking that I can convert to a list and use Collections sort but both seem to give me the error NullPointerException.

```<code>public static void main(String[] args) {
    try {
        int[] arrangedArray = null;
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        int numberInputs = Integer.parseInt(buffer.readLine());
        while(numberInputs>0) {
            int size = Integer.parseInt(buffer.readLine());
            String[] arr1 = buffer.readLine().split(" ");
            Integer[] array1 = new Integer[size];
            for(int i = 0;i<size-1;i++) {
                System.out.println("Debug: " + arr1[i]);
                array1[i] = Integer.parseInt(arr1[i]);
            }
            arrangedArray = findMissingReapeatingFromArray(array1, size);
            numberInputs--;
        }
        for(int k =0;k<arrangedArray.length;k++) {
            System.out.print(arrangedArray[k] + " ");
        }
    } catch(IOException ex) {
        System.out.println(ex.toString());
    }
}
static int[] findMissingReapeatingFromArray(Integer[] number, int length) {
    List list = new ArrayList<>(Arrays.asList(number));
    Set<Integer> set = new HashSet<Integer>(list);
    System.out.println("Debug: " + set.size() + " " + number.length + " " + length);
    int[] array = new int[2];
    Collections.sort(Arrays.asList(number)); // the error is here stating my array is null
    //for loop to accomplish algorithm
    return array;
 }
</code>```

**EDIT:**Added the main to see the input where the input shows all the elements are correct in the array that is being passed to the function without the null. The Debug for the findMissingRepeatingFromArray gives for the input

```<code>1
5
2 3 4 4 5
Debug: 2
Debug: 3
Debug: 4
Debug: 4
[2, 3, 4, 4, null]
</code>```

My debug statement returns the correct return.  What am I doing wrong?

答:
The reason for your error is that you have null values in your array.  Internally Collections.sort() uses compareTo() method that cannot be called on a null.

The reason for the null in your array is that you do not initialize its last element and it stays with its default value.

You have

```<code>for(int i = 0; i < size-1; i++)
</code>```

and it should've been

```<code>for(int i = 0; i < size; i++)
</code>```

[index values from 0 to (size-1)]

Title: Array sort NullpointerException

Body:
I have a pretty easy for loop I need to use an array in but I need it sorted and finding that I get a NullpointerException when I know the array I am passing is populated.  I'm working with the Array.sort() means my int[] needs to be a generic and also thinking that I can convert to a list and use Collections sort but both seem to give me the error NullPointerException.

public static void main(String[] args) {
    try {
        int[] arrangedArray = null;
        BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
        int numberInputs = Integer.parseInt(buffer.readLine());
        while(numberInputs>0) {
            int size = Integer.parseInt(buffer.readLine());
            String[] arr1 = buffer.readLine().split(" ");
            Integer[] array1 = new Integer[size];
            for(int i = 0;i<size-1;i++) {
                System.out.println("Debug: " + arr1[i]);
                array1[i] = Integer.parseInt(arr1[i]);
            }
            arrangedArray = findMissingReapeatingFromArray(array1, size);
            numberInputs--;
        }
        for(int k =0;k<arrangedArray.length;k++) {
            System.out.print(arrangedArray[k] + " ");
        }
    } catch(IOException ex) {
        System.out.println(ex.toString());
    }
}
static int[] findMissingReapeatingFromArray(Integer[] number, int length) {
    List list = new ArrayList<>(Arrays.asList(number));
    Set<Integer> set = new HashSet<Integer>(list);
    System.out.println("Debug: " + set.size() + " " + number.length + " " + length);
    int[] array = new int[2];
    Collections.sort(Arrays.asList(number)); // the error is here stating my array is null
    //for loop to accomplish algorithm
    return array;
 }

**EDIT:**Added the main to see the input where the input shows all the elements are correct in the array that is being passed to the function without the null. The Debug for the findMissingRepeatingFromArray gives for the input

1
5
2 3 4 4 5
Debug: 2
Debug: 3
Debug: 4
Debug: 4
[2, 3, 4, 4, null]

My debug statement returns the correct return.  What am I doing wrong?

Body:
The reason for your error is that you have null values in your array.  Internally Collections.sort() uses compareTo() method that cannot be called on a null.

The reason for the null in your array is that you do not initialize its last element and it stays with its default value.

You have

for(int i = 0; i < size-1; i++)

and it should've been

for(int i = 0; i < size; i++)

[index values from 0 to (size-1)]


问:
Is there a way to create a table with nodes as cells in Graphviz
While it is pretty easy to create a table of labels in Graphviz, I have not come across a method that teaches a way to create a table of nodes. All the nodes are standalone and clickable svg elements. This can, of course, be done with HTML and div etc. But can we do the same without leaving the Graphviz world?

See figure

答:
Graphviz does not support nodes within "html".

Nor, (to my knowledge) does Graphviz support any SVG "onclick" events (for any nodes).
You might consider postprocessing the SVG output to add the "onclick" code.


问:
Which one of these headers comes from MSVCR100.DLL?
I'm working on a cpp app, works fine on the virtual machine im developing but in my laptop (XP without c++ redistributable package) it shows an error saying the app needs MSVCR100.DLL and it's not in the computer. I am not referencing the dll directly anywhere in the app so I guess it could be because of the headers included. I don't want to use this dll include, I'd prefer if the app works without it. These are the headers included:

```<code>#include <winsock2.h>
#include <windows.h>
#include <process.h>
#include <shellapi.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
</code>```

I tried commenting a few, but for commenting other I have to change too much code just for testing.

Which one of those headers comes from MSVCR100.DLL?

The project setting "Runtime library" is set to Multi-threaded (/MT).

答: The MSVCR100.DLL is the C runtime library of Visual Studio 2010, I think. I suppose your labtop has no Visual Studio installed. So you got to supply this DLL with your application. It should be there on your development system.</p>

Body:
I'm working on a cpp app, works fine on the virtual machine im developing but in my laptop (XP without c++ redistributable package) it shows an error saying the app needs MSVCR100.DLL and it's not in the computer. I am not referencing the dll directly anywhere in the app so I guess it could be because of the headers included. I don't want to use this dll include, I'd prefer if the app works without it. These are the headers included:

#include <winsock2.h>
#include <windows.h>
#include <process.h>
#include <shellapi.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

I tried commenting a few, but for commenting other I have to change too much code just for testing.

Which one of those headers comes from MSVCR100.DLL?

The project setting "Runtime library" is set to Multi-threaded (/MT).


问:
Force  to download image instead of opening url link to image

  Download
```

Is there a way to force the download of a file instead of opening the file in a new window? Right now if the file is a URL, like the example below it won't be downloaded and will open in a new window.

答:
setTimeout(function() {

   url = 'https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png';
   // downloadFile(url); // UNCOMMENT THIS LINE TO MAKE IT WORK

}, 2000);

// Source: http://pixelscommander.com/en/javascript/javascript-file-download-ignore-content-type/
window.downloadFile = function (sUrl) {

    //iOS devices do not support downloading. We have to inform user about this.
    if (/(iP)/g.test(navigator.userAgent)) {
       //alert('Your device does not support files downloading. Please try again in desktop browser.');
       window.open(sUrl, '_blank');
       return false;
    }

    //If in Chrome or Safari - download via virtual link click
    if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
        //Creating new link node.
        var link = document.createElement('a');
        link.href = sUrl;
        link.setAttribute('target','_blank');

        if (link.download !== undefined) {
            //Set HTML5 download attribute. This will prevent file from opening if supported.
            var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
            link.download = fileName;
        }

        //Dispatching click event.
        if (document.createEvent) {
            var e = document.createEvent('MouseEvents');
            e.initEvent('click', true, true);
            link.dispatchEvent(e);
            return true;
        }
    }

    // Force file download (whether supported by server).
    if (sUrl.indexOf('?') === -1) {
        sUrl += '?download';
    }

    window.open(sUrl, '_blank');
    return true;
}

window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;```

Title: Force <a download /> to download image instead of opening url link to image

Body:
  Download

Is there a way to force the download of a file instead of opening the file in a new window? Right now if the file is a URL, like the example below it won't be downloaded and will open in a new window.


问:
How does SharePoint versioning engine store only changes to files and not the whole file?
One of the many things that SharePoint does extremely well is that when you have versioning enabled for files uploaded to a Document Library, every time you save changes to a file it only saves the difference from the previous version of the file to the Content Database but NOT the whole file again.

I am trying to duplicate that same behavior with standard C# code on either a File System folder in Windows or a SQL Database blob field. Does anyone have any idea or pointers on how SharePoint accomplishes this and how it can be done outside of SharePoint?

答:
SharePoint uses a technique called data "shredding" to contain each change to a given file.  Unfortunately, I don't think you will find enough technical details to truly reproduce what they are doing, but you might be able to devise a reasonable approximation using your own design.

When shredded, the data associated with a file such as Document.docx is distributed across a set of BLOBs associated with the file. The independent BLOBS are each assigned a unique ID (offset) to enable reconstruction in the correct order when requested by a user.

Each document "shred" is stored in a SQL database table named DocStreams. Each BLOB contains a numerical Id representative of the source BLOB when coalesced. When a client updates a file, only the shredded BLOB that corresponds to the change is updated with the update occurring on the database server as opposed to the Web server.

For more details on Shredding see

http://download.microsoft.com/download/9/6/6/9661DAC2-393D-445A-BDC1-E60743B1231E/Shredded%20Storage%20in%20SharePoint%202013.pdf

https://jeremythake.com/the-truth-behind-shredded-storage-in-sharepoint-2013-a84ec047f28e

https://www.c-sharpcorner.com/UploadFile/91b369/shredded-storage-in-sharepoint-2013/


问:
Pytest isinstance of a type
I'm pretty new to Python and I'm setting up a little game and I want to test it.
Currently, I'm generating an array of objects (Rock, Paper, Scissors) and each of them inherit from a Roll object:

```<code>def build_the_three_rolls():
  return [Rock(), Paper(), Scissors()]
</code>```

This is my test with py.test:

```<code>def test_building_rolls():
  assert len(build_the_three_rolls()) == 3
  assert isinstance(build_the_three_rolls()[0], Rock)
  assert isinstance(build_the_three_rolls()[1], Paper)
  assert isinstance(build_the_three_rolls()[2], Scissors)
</code>```

but when I run it, I'm getting the following error:

```<code>>       assert isinstance(build_the_three_rolls()[1], Paper)
E       assert False
E        +  where False = isinstance(<roll.Paper object at 0x110ab42e8>, Paper)
</code>```

I don't understand why it fails

Thanks!

UPDATE:

Here's the definition of Roll and its child classes:

```<code>class Roll:
def __init__(self, name, defeated_by_self, defeat_self):
    self.name = name
    self.defeated_by_self = defeated_by_self
    self.defeat_self = defeat_self

class Rock(Roll):
    def __init__(self):
        defeated_by_self = {}
        defeated_by_self["Scissors"] = "Scissors"
        defeat_self = {}
        defeat_self["Paper"] = "Paper"
        super().__init__("Rock", defeated_by_self, defeat_self)

class Paper(Roll):
    def __init__(self):
        defeated_by_self = {}
        defeated_by_self["Rock"] = "Rock"
        defeat_self = {}
        defeat_self["Scissors"] = "Scissors"
        super().__init__("Paper", defeated_by_self, defeat_self)

class Scissors(Roll):
    def __init__(self):
        defeated_by_self = {}
        defeated_by_self["Paper"] = "Paper"
        defeat_self = {}
        defeat_self["Rock"] = "Rock"
        super().__init__("Scissors", defeated_by_self, defeat_self)
</code>```

答:
I hit a similar issue and ultimately discovered that in my case it had to do with a relative import path issue. When I investigated MySubClass.__class__ from ipython run in the directory with MyClass's module it was different than the same thing when pytest was run on the tests folder. Example below:

Directory structure:

```<code>└── project
    ├── __init__.py
    ├── src
    │   ├── __init__.py
    │   ├── my_module.py
    └── tests
        ├── __init__.py
        └── test_my_module.py
</code>```

my_module.py:

```<code>class MyClass:
    def __init__(self, param1):
        self.param1 = param1

class MySubClass(MyClass):
    def __init__(self, param1):
        super().__init__(param1)
</code>```

test_my_module.py:

```<code>def test_my_sub_class():
    pkl_instance = # loaded from a pkl file saved from ipython
    test_instance = MySubClass(param1="This was instantiated in
    test_my_module.py")

    # assert isinstance(pkl_instance, test_instance) fails
    print(pkl_instance.__class__)   # <class 'my_module.MySubClass'>
    print(test_instance.__class__)  # <class 'project.src.my_module.MySubClass'>
</code>```

Title: Pytest isinstance of a type

Body:
I'm pretty new to Python and I'm setting up a little game and I want to test it.
Currently, I'm generating an array of objects (Rock, Paper, Scissors) and each of them inherit from a Roll object:

def build_the_three_rolls():
  return [Rock(), Paper(), Scissors()]

This is my test with py.test:

def test_building_rolls():
  assert len(build_the_three_rolls()) == 3
  assert isinstance(build_the_three_rolls()[0], Rock)
  assert isinstance(build_the_three_rolls()[1], Paper)
  assert isinstance(build_the_three_rolls()[2], Scissors)

but when I run it, I'm getting the following error:

>       assert isinstance(build_the_three_rolls()[1], Paper)
E       assert False
E        +  where False = isinstance(<roll.Paper object at 0x110ab42e8>, Paper)

I don't understand why it fails

Thanks!

UPDATE:

Here's the definition of Roll and its child classes:

class Roll:
def __init__(self, name, defeated_by_self, defeat_self):
    self.name = name
    self.defeated_by_self = defeated_by_self
    self.defeat_self = defeat_self

class Rock(Roll):
    def __init__(self):
        defeated_by_self = {}
        defeated_by_self["Scissors"] = "Scissors"
        defeat_self = {}
        defeat_self["Paper"] = "Paper"
        super().__init__("Rock", defeated_by_self, defeat_self)

class Paper(Roll):
    def __init__(self):
        defeated_by_self = {}
        defeated_by_self["Rock"] = "Rock"
        defeat_self = {}
        defeat_self["Scissors"] = "Scissors"
        super().__init__("Paper", defeated_by_self, defeat_self)

class Scissors(Roll):
    def __init__(self):
        defeated_by_self = {}
        defeated_by_self["Paper"] = "Paper"
        defeat_self = {}
        defeat_self["Rock"] = "Rock"
        super().__init__("Scissors", defeated_by_self, defeat_self)

Body:
I hit a similar issue and ultimately discovered that in my case it had to do with a relative import path issue. When I investigated MySubClass.__class__ from ipython run in the directory with MyClass's module it was different than the same thing when pytest was run on the tests folder. Example below:

Directory structure:

└── project
    ├── __init__.py
    ├── src
    │   ├── __init__.py
    │   ├── my_module.py
    └── tests
        ├── __init__.py
        └── test_my_module.py

my_module.py:

class MyClass:
    def __init__(self, param1):
        self.param1 = param1

class MySubClass(MyClass):
    def __init__(self, param1):
        super().__init__(param1)

test_my_module.py:

def test_my_sub_class():
    pkl_instance = # loaded from a pkl file saved from ipython
    test_instance = MySubClass(param1="This was instantiated in
    test_my_module.py")

    # assert isinstance(pkl_instance, test_instance) fails
    print(pkl_instance.__class__)   # <class 'my_module.MySubClass'>
    print(test_instance.__class__)  # <class 'project.src.my_module.MySubClass'>


问:
Angular clear router path params
I have a router config like this.

```<code>{
    path: 'home',
    component: HomeComponent,
    children: [
        {
            path: '',
            component: HomeContentComponent
        },
        {
            path: ':id',
            component: HomeContentComponent
        },
        {
            path: 'home2',
            component: HomeComponent
        },
        {
            path: '',
            redirectTo: '',
            pathMatch: 'full',
        },
    ],
}
</code>```

Everything is working fine. I can navigate to /home/id1 to and the I can read the params in the HomeContentComponent like this.

```<code>constructor(private activatedRoute: ActivatedRoute) {

this.activatedRoute.params.pipe(
  takeUntil(this.onDestroy)
).subscribe(params => {
  console.log("HERE ARE MY PARAMS ID", params.id);
});
}
</code>```

Now when I logout I clear my local storage and navigate to the login page with

```<code>this.router.navigateByUrl('/login');
</code>```

This works fine. But after the login (maybe from a different user) I navigate back to the home page with

```<code>this.router.navigateByUrl('/home');
</code>```

My problem now is that it automatically has the old id "id1" set from the previous user (route) which I can see on the console output and that the browser automatically loads /home/id1 instead of /home.
But I need to navigate to the /home route without any params.

Is there any way to clear the path params?

答:
Try </p>

```<code>router.navigate(['/home'], {replaceUrl: true })`
</code>```

Title: Angular clear router path params

Body:
I have a router config like this.

{
    path: 'home',
    component: HomeComponent,
    children: [
        {
            path: '',
            component: HomeContentComponent
        },
        {
            path: ':id',
            component: HomeContentComponent
        },
        {
            path: 'home2',
            component: HomeComponent
        },
        {
            path: '',
            redirectTo: '',
            pathMatch: 'full',
        },
    ],
}

Everything is working fine. I can navigate to /home/id1 to and the I can read the params in the HomeContentComponent like this.

constructor(private activatedRoute: ActivatedRoute) {

this.activatedRoute.params.pipe(
  takeUntil(this.onDestroy)
).subscribe(params => {
  console.log("HERE ARE MY PARAMS ID", params.id);
});
}

Now when I logout I clear my local storage and navigate to the login page with

this.router.navigateByUrl('/login');

This works fine. But after the login (maybe from a different user) I navigate back to the home page with

this.router.navigateByUrl('/home');

My problem now is that it automatically has the old id "id1" set from the previous user (route) which I can see on the console output and that the browser automatically loads /home/id1 instead of /home.
But I need to navigate to the /home route without any params.

Is there any way to clear the path params?

Body:
Try

router.navigate(['/home'], {replaceUrl: true })`


问:
Generating random points out of a triangle
I have the following code to generate random points on a given map. I want to avoid having points in the lake area (top right corner). I sort of divided the lake into a rectangle and a triangle. For the rectangle, I could figure out how to avoid having points in there. But, for the triangle (shown with the red line), I couldn't find a solution. Any suggestion? You can find the "Map.png" below the code.

```<code>import numpy as np
import matplotlib.pyplot as plt

def point_generator(number):
    xlist,ylist = [], []
    for i in range(number):
        x = np.random.uniform(BBox[0],BBox[1])
        y = np.random.uniform(BBox[2],BBox[3])
        while x>-87.8 and y>42.25:
            x = np.random.uniform(BBox[0],BBox[1])
            y = np.random.uniform(BBox[2],BBox[3])
        xlist.append(x); ylist.append(y)
    return(xlist,ylist)

BBox = ((-89.541239, -87.541239,
         40.773460, 42.498943))
im = plt.imread('Map.png')

fig, ax = plt.subplots(figsize = (15,15))
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])

plt.plot([-87.8,-87.8],[42.25,42.498943],'-k')
plt.plot([-87.8,-87.541239],[42.25,42.25],'-k')
plt.plot([-87.8,-87.541239],[42.25,41.75],'-r')

xs,ys = point_generator(1500)
plt.plot(xs,ys, '.b')
ax.imshow(im, zorder=0, extent = BBox, aspect= 'equal',alpha=0.5)
</code>```

答: A simple yet correct way of achieving this is by generating random points in the entire surface and then removing the random points that fell in the undesired areas. This way, given that the distribution is uniform in all areas, the remaining distribution is still uniform.</p>

Body:
I have the following code to generate random points on a given map. I want to avoid having points in the lake area (top right corner). I sort of divided the lake into a rectangle and a triangle. For the rectangle, I could figure out how to avoid having points in there. But, for the triangle (shown with the red line), I couldn't find a solution. Any suggestion? You can find the "Map.png" below the code.

import numpy as np
import matplotlib.pyplot as plt

def point_generator(number):
    xlist,ylist = [], []
    for i in range(number):
        x = np.random.uniform(BBox[0],BBox[1])
        y = np.random.uniform(BBox[2],BBox[3])
        while x>-87.8 and y>42.25:
            x = np.random.uniform(BBox[0],BBox[1])
            y = np.random.uniform(BBox[2],BBox[3])
        xlist.append(x); ylist.append(y)
    return(xlist,ylist)

BBox = ((-89.541239, -87.541239,
         40.773460, 42.498943))
im = plt.imread('Map.png')

fig, ax = plt.subplots(figsize = (15,15))
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])

plt.plot([-87.8,-87.8],[42.25,42.498943],'-k')
plt.plot([-87.8,-87.541239],[42.25,42.25],'-k')
plt.plot([-87.8,-87.541239],[42.25,41.75],'-r')

xs,ys = point_generator(1500)
plt.plot(xs,ys, '.b')
ax.imshow(im, zorder=0, extent = BBox, aspect= 'equal',alpha=0.5)


问:
React Native image fades with signed URL (google cloud storage)
I'm persisting user profile with asyncStorage. When I request the user information from backend it responds with different avatar url but same image. And react native re renders the image component maybe because url is different. And it causes to image fade out fade in effect.

Here's demonstation:

```<code>export default _ => {
  const [user, setUser] = React.useState({})

  React.useEffect(_ => {

    _getUser()

  }, [])

  _getUser = async _ =>
  {
    const saved = await AsyncStorage('user')
    if (saved)
      setUser(JSON.parse(saved))

    _fetchUser()
  }

  _fetchUser = async _ =>
  {
    const response = await fetch()
    setUser(response)

    await AsyncStorage.setItem('user', JSON.stringify(response))
  }

  return (
    <View>
      <Image source={{uri: user.avatar}} />
    </View>
  )
}
</code>```

So, how can I prevent re render or fade in/out effect?

答:
Try to add else condition:

 _getUser = async _ =>
  {
    const saved = await AsyncStorage('user')
    if (saved) {
      setUser(JSON.parse(saved))
    } else {
      _fetchUser()
    }
  }
```

Body:
I'm persisting user profile with asyncStorage. When I request the user information from backend it responds with different avatar url but same image. And react native re renders the image component maybe because url is different. And it causes to image fade out fade in effect.

Here's demonstation:

export default _ => {
  const [user, setUser] = React.useState({})

  React.useEffect(_ => {

    _getUser()

  }, [])

  _getUser = async _ =>
  {
    const saved = await AsyncStorage('user')
    if (saved)
      setUser(JSON.parse(saved))

    _fetchUser()
  }

  _fetchUser = async _ =>
  {
    const response = await fetch()
    setUser(response)

    await AsyncStorage.setItem('user', JSON.stringify(response))
  }

  return (
    <View>
      <Image source={{uri: user.avatar}} />
    </View>
  )
}

So, how can I prevent re render or fade in/out effect?


问:
How to read double signups for a class in two separate databases without subqueries? SQL
I am using MySQL for an intro to databases course. We are currently practicing using aggregations and joins to create new relevant columns. I have a class table that contains information about classes such as the class id, name, code, etc.

```<code>ID  Name                        Description     Code    MaximumStudents
1   Computer Science 310 SQL    NULL            CS-HU310    10
3   Communications              NULL            COMM113     5
4   English                     NULL            ENG101      4
5   Math                        NULL            MA030       5
6   Electrical                  NULL            ECE230      10
</code>```

I also have a ClassStudent table that shows all students that are signed up for a class
as well as sign up times and class codes.

```<code>//Some data from this table has been removed to avoid unnecessary clutter on the post
ID  ClassID StudentID   SignUpDate
33  3           3   2020-02-04 13:12:23
34  3           7   2020-02-04 13:12:23
38  4           2   2020-02-04 13:20:12
39  4           4   2020-02-04 13:20:12
40  4           5   2020-02-04 13:20:12
41  4           7   2020-02-04 13:20:12
42  4           8   2020-02-04 13:20:12
43  4           9   2020-02-04 13:20:12
45  5           2   2020-02-04 13:35:22
46  5           3   2020-02-04 13:35:22
47  5           4   2020-02-04 13:35:22
48  5           2   2020-02-04 13:35:42
49  5           3   2020-02-04 13:35:42
50  5           4   2020-02-04 13:35:42
51  5           2   2020-02-05 15:57:20
52  5           3   2020-02-05 15:57:20
53  5           4   2020-02-05 15:57:20
</code>```

The task at hand is to display the how may students have signed up for each class twice, where applicable. If you look at the table above, you can see that there are students with IDs 2, 3, and 4, that have signed up for class number 5, 3 times. So there should be an additional column called DoubleSignUps.

Using the following query I have added a few columns to answer other parts of the question that is being asked, however I can't figure out the last column.

```<code>SELECT Class.ID, Class.Name, Class.Code, Class.MaximumStudents,
COUNT(DISTINCT ClassStudent.StudentID) AS StudentCount,
MIN(ClassStudent.SignUpDate) AS EarliestSignUp,
MAX(ClassStudent.SignUpDate) AS LatestSignUp,
COUNT(ClassStudent.StudentID) AS DoubleSignUp
FROM Class
LEFT JOIN ClassStudent
ON Class.ID=ClassStudent.ClassID
GROUP BY ID;
</code>```

Any help/explanation as to how I can do this would be greatly appreciated. All I need to do is for every ClassID, there should only be one StudentID associated, and any extra would add to a double sign up count.

EDIT:

Here is the database that I am expecting to see

```<code>ID  Name                        Description     Code    MaximumStudents DoubleSignUps
1   Computer Science 310 SQL    NULL            CS-HU310    10            0
3   Communications              NULL            COMM113     5             0
4   English                     NULL            ENG101      4             0
5   Math                        NULL            MA030       5             0
6   Electrical                  NULL            ECE230      10            3
</code>```

NOTE: My query above will also display a Earliest Signup column,Latest Signup, and Student Count, however there is not enough room in the window to add them.

答:
You need a subquery that groups by ClassID and StudentID to get duplicate signups.

```<code>SELECT StudentID, ClassID
FROM ClassStudent
GROUP BY StudentID, ClassID
HAVING COUNT(*) > 1
</code>```

You can then group this by ClassID to get the number of double signups for each class:

```<code>SELECT ClassID, COUNT(*) AS DoubleSignups
FROM (
    SELECT StudentID, ClassID
    FROM ClassStudent
    GROUP BY StudentID, ClassID
    HAVING COUNT(*) > 1) AS x
GROUP BY ClassID
</code>```

Then you can join this with your original query.

```<code>SELECT Class.ID, Class.Name, Class.Code, Class.MaximumStudents,
    COUNT(DISTINCT ClassStudent.StudentID) AS StudentCount,
    MIN(ClassStudent.SignUpDate) AS EarliestSignUp,
    MAX(ClassStudent.SignUpDate) AS LatestSignUp,
    IFNULL(d.DoubleSignup, 0) AS DoubleSignup
FROM Class
LEFT JOIN (
    SELECT ClassID, COUNT(*) AS DoubleSignup
    FROM (
        SELECT StudentID, ClassID
        FROM ClassStudent
        GROUP BY StudentID, ClassID
        HAVING COUNT(*) > 1) AS x
    GROUP BY ClassID
) AS d ON d.ClassID = Class.ID
LEFT JOIN ClassStudent ON Class.ID=ClassStudent.ClassID
GROUP BY Class.ID
</code>```

Body:
I am using MySQL for an intro to databases course. We are currently practicing using aggregations and joins to create new relevant columns. I have a class table that contains information about classes such as the class id, name, code, etc.

ID  Name                        Description     Code    MaximumStudents
1   Computer Science 310 SQL    NULL            CS-HU310    10
3   Communications              NULL            COMM113     5
4   English                     NULL            ENG101      4
5   Math                        NULL            MA030       5
6   Electrical                  NULL            ECE230      10

I also have a ClassStudent table that shows all students that are signed up for a class
as well as sign up times and class codes.

//Some data from this table has been removed to avoid unnecessary clutter on the post
ID  ClassID StudentID   SignUpDate
33  3           3   2020-02-04 13:12:23
34  3           7   2020-02-04 13:12:23
38  4           2   2020-02-04 13:20:12
39  4           4   2020-02-04 13:20:12
40  4           5   2020-02-04 13:20:12
41  4           7   2020-02-04 13:20:12
42  4           8   2020-02-04 13:20:12
43  4           9   2020-02-04 13:20:12
45  5           2   2020-02-04 13:35:22
46  5           3   2020-02-04 13:35:22
47  5           4   2020-02-04 13:35:22
48  5           2   2020-02-04 13:35:42
49  5           3   2020-02-04 13:35:42
50  5           4   2020-02-04 13:35:42
51  5           2   2020-02-05 15:57:20
52  5           3   2020-02-05 15:57:20
53  5           4   2020-02-05 15:57:20

The task at hand is to display the how may students have signed up for each class twice, where applicable. If you look at the table above, you can see that there are students with IDs 2, 3, and 4, that have signed up for class number 5, 3 times. So there should be an additional column called DoubleSignUps.

Using the following query I have added a few columns to answer other parts of the question that is being asked, however I can't figure out the last column.

SELECT Class.ID, Class.Name, Class.Code, Class.MaximumStudents,
COUNT(DISTINCT ClassStudent.StudentID) AS StudentCount,
MIN(ClassStudent.SignUpDate) AS EarliestSignUp,
MAX(ClassStudent.SignUpDate) AS LatestSignUp,
COUNT(ClassStudent.StudentID) AS DoubleSignUp
FROM Class
LEFT JOIN ClassStudent
ON Class.ID=ClassStudent.ClassID
GROUP BY ID;

Any help/explanation as to how I can do this would be greatly appreciated. All I need to do is for every ClassID, there should only be one StudentID associated, and any extra would add to a double sign up count.

EDIT:

Here is the database that I am expecting to see

ID  Name                        Description     Code    MaximumStudents DoubleSignUps
1   Computer Science 310 SQL    NULL            CS-HU310    10            0
3   Communications              NULL            COMM113     5             0
4   English                     NULL            ENG101      4             0
5   Math                        NULL            MA030       5             0
6   Electrical                  NULL            ECE230      10            3

NOTE: My query above will also display a Earliest Signup column,Latest Signup, and Student Count, however there is not enough room in the window to add them.

Body:
You need a subquery that groups by ClassID and StudentID to get duplicate signups.

SELECT StudentID, ClassID
FROM ClassStudent
GROUP BY StudentID, ClassID
HAVING COUNT(*) > 1

You can then group this by ClassID to get the number of double signups for each class:

SELECT ClassID, COUNT(*) AS DoubleSignups
FROM (
    SELECT StudentID, ClassID
    FROM ClassStudent
    GROUP BY StudentID, ClassID
    HAVING COUNT(*) > 1) AS x
GROUP BY ClassID

Then you can join this with your original query.

SELECT Class.ID, Class.Name, Class.Code, Class.MaximumStudents,
    COUNT(DISTINCT ClassStudent.StudentID) AS StudentCount,
    MIN(ClassStudent.SignUpDate) AS EarliestSignUp,
    MAX(ClassStudent.SignUpDate) AS LatestSignUp,
    IFNULL(d.DoubleSignup, 0) AS DoubleSignup
FROM Class
LEFT JOIN (
    SELECT ClassID, COUNT(*) AS DoubleSignup
    FROM (
        SELECT StudentID, ClassID
        FROM ClassStudent
        GROUP BY StudentID, ClassID
        HAVING COUNT(*) > 1) AS x
    GROUP BY ClassID
) AS d ON d.ClassID = Class.ID
LEFT JOIN ClassStudent ON Class.ID=ClassStudent.ClassID
GROUP BY Class.ID


问:
Writing to file using the .insert string method
Best way to code writing to a specific point in a file using r+ mode and the .insert method?

gets.chomp is used and attached to a variable called x it is this variable and the assigned string that needs to be inserted at a specific position when writing to a file.

Thanks

答:
You can replace or insert stuff in a file. Scroll to 'Modifying a File in Place Without a Temporary File' on Pleac . It's fragile and not considered good practise. The usual way is:

read the original file

Modify the content in memory

Write it to a temporary file

(Optionally) rename the original file to something like orig_file.old

Rename the temporary file to the originale filename.

This way minimalizes the chance of data loss in case of powerouts and the like.

Update: according to your comment you need something like

```<code>File.open('test.txt', 'r+') do |f|
  str = f.read
  f.rewind
  f.write( str.insert(6, ' HI THERE '))
end
</code>```

Body:
You can replace or insert stuff in a file. Scroll to 'Modifying a File in Place Without a Temporary File' on Pleac . It's fragile and not considered good practise. The usual way is:

read the original file

Modify the content in memory

Write it to a temporary file

(Optionally) rename the original file to something like orig_file.old

Rename the temporary file to the originale filename.

This way minimalizes the chance of data loss in case of powerouts and the like.

Update: according to your comment you need something like

File.open('test.txt', 'r+') do |f|
  str = f.read
  f.rewind
  f.write( str.insert(6, ' HI THERE '))
end


问:
How can I join proper path with move_uploaded_file function?
I have a problem with move_uploaded_file function. I don't know why it doesn't work, maybe it is something wrong with path in init.php. I have few files in which are correlated, so I decided to show you my repository:
https://github.com/pchudzin/Learning-PHP-OOP/tree/master/PhotoGallerySystem
Here you can download my code, there is also database file.

I have 2 warnings and error message from my code ("the file directory probably does not have permission"):

Warning: move_uploaded_file(SITE_ROOT\admin\images\13-uklad-1.png):
  failed to open stream: No such file or directory in
  C:\xampp\htdocs\kurs_OOP_PHP\Learning-PHP-OOP\PhotoGallerySystem\admin\includes\photo.php
  on line 62

Warning: move_uploaded_file(): Unable to move
  'C:\xampp\tmp\php1C1.tmp' to 'SITE_ROOT\admin\images\13-uklad-1.png'
  in
  C:\xampp\htdocs\kurs_OOP_PHP\Learning-PHP-OOP\PhotoGallerySystem\admin\includes\photo.php
  on line 62

Absolute path to images folder:

C:\xampp\htdocs\kurs_OOP_PHP\Learning-PHP-OOP\PhotoGallerySystem\admin\images

The images folder has read/write permissions.

I will be grateful for your help!
init.php

```<code><?php

defined('DS') ? null : define( 'DS', DIRECTORY_SEPARATOR );

defined('DS') ? null : define( 'SITE_ROOT', 'C:' . DS . 'xampp' . DS . 'htdocs' . DS . 'kurs_OOP_PHP' . DS . 'Learning-PHP-OOP' . DS . 'PhotoGallerySystem' );

defined('INCLUDES_PATH') ? null : define('INCLUDES_PATH', 'SITE_ROOT' . DS . 'admin'. DS . 'includes');

require_once("functions.php");
require_once("new_config.php");
require_once("database.php");
require_once("db_object.php");
require_once("user.php");
require_once("photo.php");
require_once("session.php");

?>
</code>```

photo.php

```<code><?php

  class Photo extends Db_object {

    protected static $db_table = "photos";
    protected static $db_table_fields = array('photo_id', 'title', 'description', 'filename', 'type', 'size');
    public $photo_id;
    public $title;
    public $description;
    public $filename;
    public $type;
    public $size;

    public $tmp_path;
    public $upload_directory = "images";
    public $errors = array();

    public $upload_errors_array = array(
      UPLOAD_ERR_OK => "There is no error, the file uploaded with success.",
      UPLOAD_ERR_INI_SIZE => "The uploaded file exceeds the upload_max_filesize directive in php.ini.",
      UPLOAD_ERR_FORM_SIZE => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.",
      UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded.",
      UPLOAD_ERR_NO_FILE => "No file was uploaded.",
      UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder.",
      UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
      UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload."
    );
    // This is passing $_FILES['uploaded_file'] as an argument
    public function set_file( $file ) {

      if( empty( $file ) || !$file || !is_array( $file ) ) {
        $this->errors[] = "There was no file uploaded here";
        return false;
      } else if( $file['error'] != 0 ) {
        $this->errors[] = $this->upload_errors_array[ $file['error'] ];
        return false;
      } else {
        $this->filename = basename( $file['name'] );
        $this->tmp_path = $file['tmp_name'];
        $this->type = $file['type'];
        $this->size = $file['size'];
      }
    }

    public function save() {
      if( $this->photo_id ) {
        $this->update();
      } else {
        if( !empty( $this->errors ) ) {
          return false;
        }
        if( empty( $this->filename ) || empty( $this->tmp_path ) ) {
          $this->erros[] = "the file was not available";
          return false;
        }
        $target_path = 'SITE_ROOT' . DS . 'admin'. DS . $this->upload_directory . DS . $this->filename;

        if ( file_exists( $target_path ) ) {
          $this->errors = "The file {$this->filename} already exists";
          return false;
        }
        if ( move_uploaded_file( $this->tmp_path, $target_path ) ) {
          if( $this->create() ) {
            unset( $this->tmp_path);
            return true;
          }
        } else {
          $this->errors[] = "the file directory probably does not have permission";
          return false;
        }

      }

    }

  }

?>
</code>```

upload.php

```<code><?php include("includes/header.php"); ?>
<?php

  if( !$session->is_signed_in() ) {
    redirect( "login.php" );
  }

?>

<?php

  $message="";

  if( isset( $_POST['submit'] ) ) {
    $photo = new Photo();
    $photo->title = $_POST['title'];
    $photo->set_file( $_FILES['file_upload'] );

    if( $photo->save() ) {
      $message = "Photo uploaded succesfully";
    } else {
      $message = join("<br>", $photo->errors);
    }
  }
 ?>

        <!-- Navigation -->
        <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
            <!-- Brand and toggle get grouped for better mobile display -->

            <?php include("includes/top_nav.php"); ?>

            <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
            <?php include("includes/side_nav.php"); ?>
            <!-- /.navbar-collapse -->
        </nav>

        <div id="page-wrapper">
          <div class="container-fluid">

              <!-- Page Heading -->
              <div class="row">
                  <div class="col-lg-12">
                      <h1 class="page-header">
                          Upload
                          <small>Subheading</small>
                      </h1>
                      <div class="col-md-6">
                        <?php echo $message ?>
                        <form action="upload.php" method="post" enctype="multipart/form-data">
                          <div class="form-group">
                            <input type="text" name="title" class="form-control">
                          </div>
                          <div class="form-group">
                            <input type="file" name="file_upload">
                          </div>
                          <input type="submit" name="submit">
                        </form>
                      </div>
                  </div>
              </div>
              <!-- /.row -->

          </div>
          <!-- /.container-fluid -->

        </div>
        <!-- /#page-wrapper -->

  <?php include("includes/footer.php"); ?>
</code>```

db_object.php

```<code><?php

  class Db_object {

    protected static $db_table = "users";

    public static function find_all() {

      return static::find_by_query("SELECT * FROM " . static::$db_table . " ");
    }
    public static function find_by_id( $user_id ) {

      global $database;
      $the_result_array=static::find_by_query("SELECT * FROM " . static::$db_table . " WHERE id=$user_id LIMIT 1");

      return !empty( $the_result_array ) ? array_shift( $the_result_array ) : false;
    }
    public static function find_by_query( $sql ) {

      global $database;
      $result_set = $database->query( $sql );
      $the_object_array = array();

      while( $row = mysqli_fetch_array( $result_set ) ) {

        $the_object_array[] = static::instantation($row);
      }
      return $the_object_array;
    }
    public static function instantation( $the_record ) {

      $calling_class = get_called_class();

      $the_object = new $calling_class;

      foreach ($the_record as $the_attribute => $value) {

        if( $the_object->has_the_attribute( $the_attribute ) ) {

          $the_object->$the_attribute = $value;
        }
      }
      return $the_object;
    }
    private function has_the_attribute( $the_attribute ) {

      $object_properties = get_object_vars($this);
      return array_key_exists( $the_attribute, $object_properties );
    }
    protected function properties() {

      $properties = array();
      foreach (static::$db_table_fields as $db_field) {
        if( property_exists($this, $db_field) ) {
          $properties[$db_field] = $this->$db_field;
        }
      }
      return $properties;
    }
    protected function clean_properties() {
      global $database;

      $clean_properties = array();

      foreach ($this->properties() as $key => $value) {
        $clean_properties[$key] = $database->escape_string($value);
      }
      return $clean_properties;
    }

    public function save() {
      return isset( $this->id ) ? $this->update() : $this->create();
    }
    public function create() {
      global $database;

      $properties = $this->clean_properties();

      $sql = "INSERT INTO " . static::$db_table . "(" . implode(",", array_keys($properties)) . ")";
      $sql .= "VALUES ('" . implode("','", array_values($properties)) . "')";

      if( $database->query( $sql ) ) {
        $this->id = $database->the_insert_id();
        return true;
      } else {
        return false;
      }
    }
    public function update() {
      global $database;

      $properties = $this->properties();
      $properties_pairs = array();

      foreach ($properties as $key => $value) {
        $properties_pairs[] ="{$key}='{$value}'";
      }
      $sql = "UPDATE " . static::$db_table . " SET ";
      $sql .= implode(", ", $properties_pairs);
      $sql .= " WHERE id= " . $database->escape_string( $this->id );

      $database->query( $sql );

      return ( mysqli_affected_rows( $database->connection ) == 1 ) ? true : false;
    }
    public function delete() {
      global $database;
      $sql = "DELETE FROM " . static::$db_table . " ";
      $sql .= "WHERE id=" . $database->escape_string( $this->id );
      $sql .= " LIMIT 1";

      $database->query( $sql );

      return ( mysqli_affected_rows( $database->connection ) == 1 ) ? true : false;
    }
  }

?>
</code>```

答:
It looks like this line:

```<code>$target_path = 'SITE_ROOT' . DS . 'admin'. DS . $this->upload_directory . DS . $this->filename;
</code>```

is using the literal string 'SITE_ROOT' when you mean to use the constant SITE_ROOT. So I think your line should read:

```<code>$target_path = SITE_ROOT . DS . 'admin'. DS . $this->upload_directory . DS . $this->filename;
</code>```

Body:
I have a problem with move_uploaded_file function. I don't know why it doesn't work, maybe it is something wrong with path in init.php. I have few files in which are correlated, so I decided to show you my repository:
https://github.com/pchudzin/Learning-PHP-OOP/tree/master/PhotoGallerySystem
Here you can download my code, there is also database file.

I have 2 warnings and error message from my code ("the file directory probably does not have permission"):

Warning: move_uploaded_file(SITE_ROOT\admin\images\13-uklad-1.png):
  failed to open stream: No such file or directory in
  C:\xampp\htdocs\kurs_OOP_PHP\Learning-PHP-OOP\PhotoGallerySystem\admin\includes\photo.php
  on line 62

Warning: move_uploaded_file(): Unable to move
  'C:\xampp\tmp\php1C1.tmp' to 'SITE_ROOT\admin\images\13-uklad-1.png'
  in
  C:\xampp\htdocs\kurs_OOP_PHP\Learning-PHP-OOP\PhotoGallerySystem\admin\includes\photo.php
  on line 62

Absolute path to images folder:

C:\xampp\htdocs\kurs_OOP_PHP\Learning-PHP-OOP\PhotoGallerySystem\admin\images

The images folder has read/write permissions.

I will be grateful for your help!
init.php

<?php

defined('DS') ? null : define( 'DS', DIRECTORY_SEPARATOR );

defined('DS') ? null : define( 'SITE_ROOT', 'C:' . DS . 'xampp' . DS . 'htdocs' . DS . 'kurs_OOP_PHP' . DS . 'Learning-PHP-OOP' . DS . 'PhotoGallerySystem' );

defined('INCLUDES_PATH') ? null : define('INCLUDES_PATH', 'SITE_ROOT' . DS . 'admin'. DS . 'includes');

require_once("functions.php");
require_once("new_config.php");
require_once("database.php");
require_once("db_object.php");
require_once("user.php");
require_once("photo.php");
require_once("session.php");

?>

photo.php

<?php

  class Photo extends Db_object {

    protected static $db_table = "photos";
    protected static $db_table_fields = array('photo_id', 'title', 'description', 'filename', 'type', 'size');
    public $photo_id;
    public $title;
    public $description;
    public $filename;
    public $type;
    public $size;

    public $tmp_path;
    public $upload_directory = "images";
    public $errors = array();

    public $upload_errors_array = array(
      UPLOAD_ERR_OK => "There is no error, the file uploaded with success.",
      UPLOAD_ERR_INI_SIZE => "The uploaded file exceeds the upload_max_filesize directive in php.ini.",
      UPLOAD_ERR_FORM_SIZE => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.",
      UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded.",
      UPLOAD_ERR_NO_FILE => "No file was uploaded.",
      UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder.",
      UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
      UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload."
    );
    // This is passing $_FILES['uploaded_file'] as an argument
    public function set_file( $file ) {

      if( empty( $file ) || !$file || !is_array( $file ) ) {
        $this->errors[] = "There was no file uploaded here";
        return false;
      } else if( $file['error'] != 0 ) {
        $this->errors[] = $this->upload_errors_array[ $file['error'] ];
        return false;
      } else {
        $this->filename = basename( $file['name'] );
        $this->tmp_path = $file['tmp_name'];
        $this->type = $file['type'];
        $this->size = $file['size'];
      }
    }

    public function save() {
      if( $this->photo_id ) {
        $this->update();
      } else {
        if( !empty( $this->errors ) ) {
          return false;
        }
        if( empty( $this->filename ) || empty( $this->tmp_path ) ) {
          $this->erros[] = "the file was not available";
          return false;
        }
        $target_path = 'SITE_ROOT' . DS . 'admin'. DS . $this->upload_directory . DS . $this->filename;

        if ( file_exists( $target_path ) ) {
          $this->errors = "The file {$this->filename} already exists";
          return false;
        }
        if ( move_uploaded_file( $this->tmp_path, $target_path ) ) {
          if( $this->create() ) {
            unset( $this->tmp_path);
            return true;
          }
        } else {
          $this->errors[] = "the file directory probably does not have permission";
          return false;
        }

      }

    }

  }

?>

upload.php

<?php include("includes/header.php"); ?>
<?php

  if( !$session->is_signed_in() ) {
    redirect( "login.php" );
  }

?>

<?php

  $message="";

  if( isset( $_POST['submit'] ) ) {
    $photo = new Photo();
    $photo->title = $_POST['title'];
    $photo->set_file( $_FILES['file_upload'] );

    if( $photo->save() ) {
      $message = "Photo uploaded succesfully";
    } else {
      $message = join("
", $photo->errors);
    }
  }
 ?>

            <?php include("includes/top_nav.php"); ?>

            <?php include("includes/side_nav.php"); ?>

                          Upload
                          Subheading

                        <?php echo $message ?>
                        <form action="upload.php" method="post" enctype="multipart/form-data">

                            <input type="text" name="title" class="form-control">

                            <input type="file" name="file_upload">

                          <input type="submit" name="submit">
                        </form>

  <?php include("includes/footer.php"); ?>

db_object.php

<?php

  class Db_object {

    protected static $db_table = "users";

    public static function find_all() {

      return static::find_by_query("SELECT * FROM " . static::$db_table . " ");
    }
    public static function find_by_id( $user_id ) {

      global $database;
      $the_result_array=static::find_by_query("SELECT * FROM " . static::$db_table . " WHERE id=$user_id LIMIT 1");

      return !empty( $the_result_array ) ? array_shift( $the_result_array ) : false;
    }
    public static function find_by_query( $sql ) {

      global $database;
      $result_set = $database->query( $sql );
      $the_object_array = array();

      while( $row = mysqli_fetch_array( $result_set ) ) {

        $the_object_array[] = static::instantation($row);
      }
      return $the_object_array;
    }
    public static function instantation( $the_record ) {

      $calling_class = get_called_class();

      $the_object = new $calling_class;

      foreach ($the_record as $the_attribute => $value) {

        if( $the_object->has_the_attribute( $the_attribute ) ) {

          $the_object->$the_attribute = $value;
        }
      }
      return $the_object;
    }
    private function has_the_attribute( $the_attribute ) {

      $object_properties = get_object_vars($this);
      return array_key_exists( $the_attribute, $object_properties );
    }
    protected function properties() {

      $properties = array();
      foreach (static::$db_table_fields as $db_field) {
        if( property_exists($this, $db_field) ) {
          $properties[$db_field] = $this->$db_field;
        }
      }
      return $properties;
    }
    protected function clean_properties() {
      global $database;

      $clean_properties = array();

      foreach ($this->properties() as $key => $value) {
        $clean_properties[$key] = $database->escape_string($value);
      }
      return $clean_properties;
    }

    public function save() {
      return isset( $this->id ) ? $this->update() : $this->create();
    }
    public function create() {
      global $database;

      $properties = $this->clean_properties();

      $sql = "INSERT INTO " . static::$db_table . "(" . implode(",", array_keys($properties)) . ")";
      $sql .= "VALUES ('" . implode("','", array_values($properties)) . "')";

      if( $database->query( $sql ) ) {
        $this->id = $database->the_insert_id();
        return true;
      } else {
        return false;
      }
    }
    public function update() {
      global $database;

      $properties = $this->properties();
      $properties_pairs = array();

      foreach ($properties as $key => $value) {
        $properties_pairs[] ="{$key}='{$value}'";
      }
      $sql = "UPDATE " . static::$db_table . " SET ";
      $sql .= implode(", ", $properties_pairs);
      $sql .= " WHERE id= " . $database->escape_string( $this->id );

      $database->query( $sql );

      return ( mysqli_affected_rows( $database->connection ) == 1 ) ? true : false;
    }
    public function delete() {
      global $database;
      $sql = "DELETE FROM " . static::$db_table . " ";
      $sql .= "WHERE id=" . $database->escape_string( $this->id );
      $sql .= " LIMIT 1";

      $database->query( $sql );

      return ( mysqli_affected_rows( $database->connection ) == 1 ) ? true : false;
    }
  }

?>

Body:
It looks like this line:

$target_path = 'SITE_ROOT' . DS . 'admin'. DS . $this->upload_directory . DS . $this->filename;

is using the literal string 'SITE_ROOT' when you mean to use the constant SITE_ROOT. So I think your line should read:

$target_path = SITE_ROOT . DS . 'admin'. DS . $this->upload_directory . DS . $this->filename;


问:
PM2 with NodeJS dgram
I am trying to run a NodeJS application(udp_recv) using pm2.
The application starts on boot via pm2 startup and pm2 save.
However, the dgram gives me an error saying -

```<code>server error:
1|udp_recv | Error: bind EADDRNOTAVAIL 192.168.0.9:7001
1|udp_recv |     at state.handle.lookup (dgram.js:242:18)
1|udp_recv |     at process._tickCallback (internal/process/next_tick.js:63:19)
1|udp_recv |     at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
1|udp_recv |     at startup (internal/bootstrap/node.js:283:19)
1|udp_recv |     at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
</code>```

But once I stop all the application (pm2 stop all) and re-run (pm2 start all)
Then there's no error and the application runs normally without any error.

My IP is 192.168.0.9 listening for UDP streams on a predefined port. The computer connected via ethernet sends the UDP streams from IP 192.168.0.6

Can someone tell me how to solve the error?

答:
https://forums.balena.io/t/eaddrnotavail-when-trying-to-bind-socket-after-device-turns-back-on/4285

Turns out binding right after reboot via dgram can cause the error.
Simply because "EADDRNOTAVAIL" means address not available.

Solution setTimeout on socket.bind to around 60 seconds and it'll work just fine.

```<code>setTimeout(() => {
    server.bind({
        address: "127.0.0.1",
        port: process.env.SERVER_PORT,
        exclusive : true
    })
}, 60000)
</code>```

Also, another solution is to try to reconnect/rebind on server error "EADDRNOTAVAIL"

```<code>//If server(app.js) gets any error
server.on('error', (err) => {

    console.log(`server error:\n${err.stack}`);
    //Server is closed
    //server.close();

    //add an "if" block to check if the error is of type "EADDRNOTAVAIL"
    server.bind({
            address: "127.0.0.1",
            port: process.env.SERVER_PORT,
            exclusive : true
        })
});
</code>```

Title: PM2 with NodeJS dgram

Body:
I am trying to run a NodeJS application(udp_recv) using pm2.
The application starts on boot via pm2 startup and pm2 save.
However, the dgram gives me an error saying -

server error:
1|udp_recv | Error: bind EADDRNOTAVAIL 192.168.0.9:7001
1|udp_recv |     at state.handle.lookup (dgram.js:242:18)
1|udp_recv |     at process._tickCallback (internal/process/next_tick.js:63:19)
1|udp_recv |     at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
1|udp_recv |     at startup (internal/bootstrap/node.js:283:19)
1|udp_recv |     at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

But once I stop all the application (pm2 stop all) and re-run (pm2 start all)
Then there's no error and the application runs normally without any error.

My IP is 192.168.0.9 listening for UDP streams on a predefined port. The computer connected via ethernet sends the UDP streams from IP 192.168.0.6

Can someone tell me how to solve the error?

Body:
https://forums.balena.io/t/eaddrnotavail-when-trying-to-bind-socket-after-device-turns-back-on/4285

Turns out binding right after reboot via dgram can cause the error.
Simply because "EADDRNOTAVAIL" means address not available.

Solution setTimeout on socket.bind to around 60 seconds and it'll work just fine.

setTimeout(() => {
    server.bind({
        address: "127.0.0.1",
        port: process.env.SERVER_PORT,
        exclusive : true
    })
}, 60000)

Also, another solution is to try to reconnect/rebind on server error "EADDRNOTAVAIL"

//If server(app.js) gets any error
server.on('error', (err) => {

    console.log(`server error:\n${err.stack}`);
    //Server is closed
    //server.close();

    //add an "if" block to check if the error is of type "EADDRNOTAVAIL"
    server.bind({
            address: "127.0.0.1",
            port: process.env.SERVER_PORT,
            exclusive : true
        })
});


问:
How to reset built-in styles for autocompleted and autofilled inputs in 2020? Recipes for Chrome
Recipes for Chrome in 2020:

1) Prevent small font size (browser: 11px, dummy font-family)

2) Reset awesome colors of background (blue, yellow, etc) from Chrome

3) Overturn crash of the "floating label input" pattern on autofill then page is just loaded (the label is initially displayed like a placeholder, and when user start typing it transitions to a small label at the top of the field).

答:
1) Prevent small font size (browser: 11px, dummy font-family):

```<code>input:-webkit-autofill::first-line {
  font: 400 15px/18px 'SourceSansPro', sans-serif;
}
</code>```

2. Reset awesome colors of background (blue, yellow, etc) from Chrome:

```<code>input:-webkit-autofill {
   transition: background-color 5000s ease-in-out 0s;
}
</code>```

3) Overturn crash of the "floating label input" pattern on autofill then page is just loaded (value is empty, no events of change for catch this)

Unfortunately, we can listen for the start of an animation, and we can start an animation in response to autofilling using the -webkit-autofill pseudo-class:

```<code>input:-webkit-autofill {
   animation: onAutoFillStart 20s ease-in-out infinite;
}
@keyframes onAutoFillStart {
  from  {color: #000}
  to {color: #090909}
}
</code>```

Check Chrome auto-fill for inputs:

```<code>function inputAutoFillCheck() {
  function onAnimationStart({ target, animationName }) {
    if (animationName !== "onAutoFillStart") return;
    target.parentElement.classList.add("has-txt");
  }
  document.querySelectorAll(".form__input-field").forEach(field => {
    field.addEventListener("animationstart", onAnimationStart, false);
  });
}
inputAutoFillCheck();
</code>```

PS

It does not works well for autofill then page is just loaded:

 autocomplete="new-password"

 Instead of autocomplete="off" use autocomplete="false" ;)

 form autocomplete="off" and input autocomplete="off"

 $('[autocomplete=off]').val('');

 input:-internal-autofill-previewed { font-size: 22px !important }

 input:-webkit-autofill {font-size: 22px !important }

Body:
1) Prevent small font size (browser: 11px, dummy font-family):

input:-webkit-autofill::first-line {
  font: 400 15px/18px 'SourceSansPro', sans-serif;
}

2. Reset awesome colors of background (blue, yellow, etc) from Chrome:

input:-webkit-autofill {
   transition: background-color 5000s ease-in-out 0s;
}

3) Overturn crash of the "floating label input" pattern on autofill then page is just loaded (value is empty, no events of change for catch this)

Unfortunately, we can listen for the start of an animation, and we can start an animation in response to autofilling using the -webkit-autofill pseudo-class:

input:-webkit-autofill {
   animation: onAutoFillStart 20s ease-in-out infinite;
}
@keyframes onAutoFillStart {
  from  {color: #000}
  to {color: #090909}
}

Check Chrome auto-fill for inputs:

function inputAutoFillCheck() {
  function onAnimationStart({ target, animationName }) {
    if (animationName !== "onAutoFillStart") return;
    target.parentElement.classList.add("has-txt");
  }
  document.querySelectorAll(".form__input-field").forEach(field => {
    field.addEventListener("animationstart", onAnimationStart, false);
  });
}
inputAutoFillCheck();

PS

It does not works well for autofill then page is just loaded:

 autocomplete="new-password"

 Instead of autocomplete="off" use autocomplete="false" ;)

 form autocomplete="off" and input autocomplete="off"

 $('[autocomplete=off]').val('');

 input:-internal-autofill-previewed { font-size: 22px !important }

 input:-webkit-autofill {font-size: 22px !important }


问:
How can I debounce a setOnClickListener for 1 second using Kotlin Coroutines?
When user taps fast on the button the showDialog() method displays multiple times on top of each other, so when you dismiss it there is another one behind it. I am looking for a way to ignore the second tap for 1 second without using a handler or check the previous tap's time.

```<code>//Button that opens a dialog
button.setOnClickListener {
    showDialog()
}
</code>```

I am looking for a solution using Kotlin coroutines or Kotlin flows for future implementations.

答:
It's better to use a simple Flag for that instead of delay as it's not a good user experience.

But if you want to use Coroutines, You can simply use Kotlin Coroutine's Flow to apply this:

First I created an Extension Function for the click event that returns a Coroutine's Flow. like this:

```<code>    fun View.clicks(): Flow<Unit> = callbackFlow {
    setOnClickListener {
        offer(Unit)
    }
    awaitClose { setOnClickListener(null) }
   }
</code>```

Now, All you need is Calling your Function in onCreate like this:

```<code>button.clicks().debounce(1000).onEach { println("clicked") }.launchIn(GlobalScope)
</code>```

Don't forget to add these lines in build.gradle file:

```<code>implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
</code>```

Edit:

The Flow analogue of throttleFirst operator is not implemented yet in kotlin coroutines. however, can be implemented with the help of Extension Functions:

```<code>@FlowPreview
@ExperimentalCoroutinesApi
fun <T> Flow<T>.throttleFirst(windowDuration: Long): Flow<T> = flow {
    var lastEmissionTime = 0L
    collect { upstream ->
        val currentTime = System.currentTimeMillis()
        val mayEmit = currentTime - lastEmissionTime > windowDuration
        if (mayEmit)
        {
            lastEmissionTime = currentTime
            emit(upstream)
        }
    }
}
</code>```

The changes are as follows:

```<code>binding.button.clicks().throttleFirst(1250)
        .onEach {
            //delay(100)
            showDialog()
        }.launchIn(GlobalScope)
</code>```

Also, you can use a delay() to handle this. Take it easy to change value of these parameters according to your needs.

Body:
When user taps fast on the button the showDialog() method displays multiple times on top of each other, so when you dismiss it there is another one behind it. I am looking for a way to ignore the second tap for 1 second without using a handler or check the previous tap's time.

//Button that opens a dialog
button.setOnClickListener {
    showDialog()
}

I am looking for a solution using Kotlin coroutines or Kotlin flows for future implementations.

Body:
It's better to use a simple Flag for that instead of delay as it's not a good user experience.

But if you want to use Coroutines, You can simply use Kotlin Coroutine's Flow to apply this:

First I created an Extension Function for the click event that returns a Coroutine's Flow. like this:

    fun View.clicks(): Flow<Unit> = callbackFlow {
    setOnClickListener {
        offer(Unit)
    }
    awaitClose { setOnClickListener(null) }
   }

Now, All you need is Calling your Function in onCreate like this:

button.clicks().debounce(1000).onEach { println("clicked") }.launchIn(GlobalScope)

Don't forget to add these lines in build.gradle file:

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'

Edit:

The Flow analogue of throttleFirst operator is not implemented yet in kotlin coroutines. however, can be implemented with the help of Extension Functions:

@FlowPreview
@ExperimentalCoroutinesApi
fun <T> Flow<T>.throttleFirst(windowDuration: Long): Flow<T> = flow {
    var lastEmissionTime = 0L
    collect { upstream ->
        val currentTime = System.currentTimeMillis()
        val mayEmit = currentTime - lastEmissionTime > windowDuration
        if (mayEmit)
        {
            lastEmissionTime = currentTime
            emit(upstream)
        }
    }
}

The changes are as follows:

binding.button.clicks().throttleFirst(1250)
        .onEach {
            //delay(100)
            showDialog()
        }.launchIn(GlobalScope)

Also, you can use a delay() to handle this. Take it easy to change value of these parameters according to your needs.


问:
Python equivalent of PHP's @
Is there a Python equivalent of PHP's @?

```<code>@function_which_is_doomed_to_fail();
</code>```

I've always used this block:

```<code>try:
  foo()
except:
  pass
</code>```

But I know there has to be a better way.

Does anyone know how I can Pythonicify that code?

I think adding some context to that code would be appropriate:

```<code>for line in blkid:
  line = line.strip()
  partition = Partition()

  try:
    partition.identifier = re.search(r'^(/dev/[a-zA-Z0-9]+)', line).group(0)
  except:
    pass

  try:
    partition.label = re.search(r'LABEL="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  try:
    partition.uuid = re.search(r'UUID="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  try:
    partition.type = re.search(r'TYPE="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  partitions.add(partition)
</code>```

答:
Building upon Gabi Purcanu's answer and your desire to condense to one-liners, you could encapsulate his solution into a function and reduce your example:</p>

```<code>def cond_match(regexp, line, grp):
    match = re.search(regexp, line)
    if match:
        return match.group(grp)
    else:
        return None

for line in blkid:
    line = line.strip()
    partition = Partition()
    partition.identifier = cond_match(r'^(/dev/[a-zA-Z0-9]+)', line, 0)
    partition.label = cond_match(r'LABEL="((?:[^"\\]|\\.)*)"', line, 1)
    partition.uuid = cond_match(r'UUID="((?:[^"\\]|\\.)*)"', line, 1)
    partition.type = cond_match(r'TYPE="((?:[^"\\]|\\.)*)"', line, 1)
    partitions.add(partition)
</code>```

Title: Python equivalent of PHP's @

Body:
Is there a Python equivalent of PHP's @?

@function_which_is_doomed_to_fail();

I've always used this block:

try:
  foo()
except:
  pass

But I know there has to be a better way.

Does anyone know how I can Pythonicify that code?

I think adding some context to that code would be appropriate:

for line in blkid:
  line = line.strip()
  partition = Partition()

  try:
    partition.identifier = re.search(r'^(/dev/[a-zA-Z0-9]+)', line).group(0)
  except:
    pass

  try:
    partition.label = re.search(r'LABEL="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  try:
    partition.uuid = re.search(r'UUID="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  try:
    partition.type = re.search(r'TYPE="((?:[^"\\]|\\.)*)"', line).group(1)
  except:
    pass

  partitions.add(partition)

Body:
Building upon Gabi Purcanu's answer and your desire to condense to one-liners, you could encapsulate his solution into a function and reduce your example:

def cond_match(regexp, line, grp):
    match = re.search(regexp, line)
    if match:
        return match.group(grp)
    else:
        return None

for line in blkid:
    line = line.strip()
    partition = Partition()
    partition.identifier = cond_match(r'^(/dev/[a-zA-Z0-9]+)', line, 0)
    partition.label = cond_match(r'LABEL="((?:[^"\\]|\\.)*)"', line, 1)
    partition.uuid = cond_match(r'UUID="((?:[^"\\]|\\.)*)"', line, 1)
    partition.type = cond_match(r'TYPE="((?:[^"\\]|\\.)*)"', line, 1)
    partitions.add(partition)


问:
TypeError: Cannot read property 'location' of undefined (jest)
I have a simple component that uses useLocation hook from React Router.

// App.jsx

import React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();
  const pathName = location.pathname;
  useEffect(() => {
    // Use pathName here
  }, [pathName]);
}
```

<p>// App.test.js</p>

<pre class="lang-js prettyprint-override"><code>import App from './App';

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});
</code>```

// Update App.test.js (with jest mock)

import App from './App';

describe('App component', () => {
  jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  }));

  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});
```

Could you please tell me how I can fix this? Thanks.

答:
The problem is that you need to specify that you are using es6 module syntax. Try this:

import App from './App';

jest.mock('react-router-dom', () => ({
    __esModule: true,
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  }));

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});
```

Reference.

Body:
I have a simple component that uses useLocation hook from React Router.

// App.jsx

import React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  const location = useLocation();
  const pathName = location.pathname;
  useEffect(() => {
    // Use pathName here
  }, [pathName]);
}

// App.test.js

import App from './App';

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});

// Update App.test.js (with jest mock)

import App from './App';

describe('App component', () => {
  jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  }));

  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});

Could you please tell me how I can fix this? Thanks.

Body:
The problem is that you need to specify that you are using es6 module syntax. Try this:

import App from './App';

jest.mock('react-router-dom', () => ({
    __esModule: true,
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  }));

describe('App component', () => {
  it('Renders correctly', () => {
    const wrapper = shallow(<App />);

    expect(wrapper).toMatchSnapshot();
  });
});

Reference.