问:
Interpolate time series and resample/pivot. How to get the expected output
I have a df that looks like this:

```<code>Video | Start              | End                | Duration |
vid1  |2018-10-02 16:00:29 |2018-10-02 20:07:05 |   246    |
vid2  |2018-10-04 16:03:08 |2018-10-04 16:10:11 |     7    |
vid3  |2018-10-04 10:13:40 |2018-10-06 12:07:38 |   113    |
</code>```

What I want to do is resample dataframe by 10 minutes by start column and assign 1 if the video lasted in that timestamp and 0 if not.
The desired output is:

```<code>Start              | vid1 | vid2 | vid3 |
2018-10-02 16:00:00|  1   |  0   | 0    |
2018-10-02 16:10:00|  1   |  0   | 0    |
...
2018-10-04 16:10:00|  0   |  1   | 0    |
2018-10-04 16:20:00|  0   |  0   | 1    |
</code>```

The output is presented only for visualization the output, hence, it can contain errors.

The problem is that I can not resample dataframe in a way to make a desired crosstab output.

Body:
I have a df that looks like this:

Video | Start              | End                | Duration |
vid1  |2018-10-02 16:00:29 |2018-10-02 20:07:05 |   246    |
vid2  |2018-10-04 16:03:08 |2018-10-04 16:10:11 |     7    |
vid3  |2018-10-04 10:13:40 |2018-10-06 12:07:38 |   113    |

What I want to do is resample dataframe by 10 minutes by start column and assign 1 if the video lasted in that timestamp and 0 if not.
The desired output is:

Start              | vid1 | vid2 | vid3 |
2018-10-02 16:00:00|  1   |  0   | 0    |
2018-10-02 16:10:00|  1   |  0   | 0    |
...
2018-10-04 16:10:00|  0   |  1   | 0    |
2018-10-04 16:20:00|  0   |  0   | 1    |

The output is presented only for visualization the output, hence, it can contain errors.

The problem is that I can not resample dataframe in a way to make a desired crosstab output.

Body:
Try this:

df.apply(lambda x: pd.Series(x['Video'],
                             index=pd.date_range(x['Start'].floor('10T'),
                                                 x['End'].ceil('10T'),
                                                 freq='10T')), axis=1)\
  .stack().str.get_dummies().reset_index(level=0, drop=True)

Output:

                     vid1   vid2   vid3
2018-10-02 16:00:00      1      0      0
2018-10-02 16:10:00      1      0      0
2018-10-02 16:20:00      1      0      0
2018-10-02 16:30:00      1      0      0
2018-10-02 16:40:00      1      0      0
...                    ...    ...    ...
2018-10-06 11:30:00      0      0      1
2018-10-06 11:40:00      0      0      1
2018-10-06 11:50:00      0      0      1
2018-10-06 12:00:00      0      0      1
2018-10-06 12:10:00      0      0      1

[330 rows x 3 columns]


来源: stackexchange

问:
Trouble converting file types by calling a program from the terminal
I'm trying to automate a process of taking in a 'pdb' file from user input and then using that input file in a program called from the Terminal called 'Antechamber' that outputs a 'mol2'file.

Here is my code:

```<code>import sys

inFile = sys.argv[tetrafluoroborate.pdb]

outFile = sys.argv[tetrafluoroborate.mol2]

p = 'antechamber' + ' -i ' + inFile + ' fi pdb o- ' +  outFile  + ' -fo mol2'

subprocess.call(p)
</code>```

The Antechamber program takes four commands: '-i' is the input file, '-fi' is the output file type, '-o' is the output file, and '-fo' is the output file format.

When I run the script, I get:

```<code>Traceback (most recent call last):
  File "test.py", line 4, in <module>
    inFile = sys.argv[tetrafluoroborate.pdb]
NameError: name 'tetrafluoroborate' is not defined
</code>```

I'm new to coding, and I appreciate any help.
Thank you!

答:
If you need to call the antechamber script from python and the input and output names will have the same prefix, I would suggest a python script like this:

```<code>import sys

prefix = sys.argv[1]

inFile = prefix + '.pdb'
outFile = prefix + '.mol2'

pcommand = 'antechamber' + ' -i ' + inFile + ' -fi pdb -o ' +  outFile  + ' -fo mol2'
subprocess.call(pcommand)
</code>```

Then you can call from the command line by:

```<code>python test.py tetrafluoroborate
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to automate a process of taking in a 'pdb' file from user input and then using that input file in a program called from the Terminal called 'Antechamber' that outputs a 'mol2'file.

Here is my code:

import sys

inFile = sys.argv[tetrafluoroborate.pdb]

outFile = sys.argv[tetrafluoroborate.mol2]

p = 'antechamber' + ' -i ' + inFile + ' fi pdb o- ' +  outFile  + ' -fo mol2'

subprocess.call(p)

The Antechamber program takes four commands: '-i' is the input file, '-fi' is the output file type, '-o' is the output file, and '-fo' is the output file format.

When I run the script, I get:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    inFile = sys.argv[tetrafluoroborate.pdb]
NameError: name 'tetrafluoroborate' is not defined

I'm new to coding, and I appreciate any help.
Thank you!

Body:
If you need to call the antechamber script from python and the input and output names will have the same prefix, I would suggest a python script like this:

import sys

prefix = sys.argv[1]

inFile = prefix + '.pdb'
outFile = prefix + '.mol2'

pcommand = 'antechamber' + ' -i ' + inFile + ' -fi pdb -o ' +  outFile  + ' -fo mol2'
subprocess.call(pcommand)

Then you can call from the command line by:

python test.py tetrafluoroborate


问:
Showing Images in GridView
I have some image path stored in database and I have to show the image in grid layout.
here is my code

```<code>public class HeadshotAllPhoto extends Activity
{
    GridView imagegrid;
    String path,filemanagerstring;
    String[] ImageNameArr;
    String filePath = null;
    String ImageName ;
    Bitmap bitmap;
    DataHelperHeadshot dbHeadshot;

String sub_list ;
String[] pathArr;
Bitmap[] bmp;
ArrayList<String> items = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.headshotallphoto);
    dbHeadshot = new DataHelperHeadshot(this);

    bg = (ImageView)findViewById(R.id.selectHeadshotView);

    List<String> names = this.dbHeadshot.fetchAllHeadshot();
    StringBuilder sb = new StringBuilder();
    for (String name : names)
    {
       name.trim();
       sb.append(",");
       sb.append(name);
    }

    bmp = new Bitmap[icount+1];
    sub_list = sb.toString();
    Log.i("sub_list .. ",""+sub_list);
    pathArr = sub_list.split(",");

    for(int p=0;p<pathArr.length;p++)
    {
        if(pathArr[p]!=null)
        {
            bitmap = decodeFile(pathArr[p]);
            if(bitmap!=null)
            {
                items.add(pathArr[p]);
                bmp[p] = bitmap;
            }
        }
        if(pathArr[p] == null)
            break;
    }

    imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imagegrid.setAdapter(new ImageAdapter(getApplicationContext(),bmp));
    imagegrid.setOnItemClickListener(this);
    }
}

public class ImageAdapter extends BaseAdapter
{
    private Context mContext;
    Bitmap[] mImageArray;

    public ImageAdapter(Context c, Bitmap[] imgArray)
    {
          mContext = c;
          mImageArray = imgArray;
    }
    public int getCount()
    {
          return mImageArray.length;
    }
    public Object getItem(int position)
    {
          return position;
    }
    public long getItemId(int position)
    {
          return position;
    }

    public View getView(int position,View convertView,ViewGroup parent)
    {
        System.gc();
        ImageView i = null ;

        if (convertView == null )
        {
            i = new ImageView(mContext);
            i.setLayoutParams(new GridView.LayoutParams(92,92));
            i.setScaleType(ImageView.ScaleType.CENTER_CROP);
            i.setImageBitmap(mImageArray[position]);
        }
         else
             i = (ImageView) convertView;
         return i;
    }
}

public Bitmap decodeFile(String filePath)
{
    System.out.println("filepath in decode file .. "+filePath);
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 100;
    final int H = 50;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < H)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    System.out.println("decode file ........... "+filePath);
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}
}
</code>```

Pls help me
Thanks

答: Refer : Andriod API demos - Grid2.java</p>

ContentLicense: CC BY-SA 3.0

Title: Showing Images in GridView

Body:
I have some image path stored in database and I have to show the image in grid layout.
here is my code

public class HeadshotAllPhoto extends Activity
{
    GridView imagegrid;
    String path,filemanagerstring;
    String[] ImageNameArr;
    String filePath = null;
    String ImageName ;
    Bitmap bitmap;
    DataHelperHeadshot dbHeadshot;

String sub_list ;
String[] pathArr;
Bitmap[] bmp;
ArrayList<String> items = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.headshotallphoto);
    dbHeadshot = new DataHelperHeadshot(this);

    bg = (ImageView)findViewById(R.id.selectHeadshotView);

    List<String> names = this.dbHeadshot.fetchAllHeadshot();
    StringBuilder sb = new StringBuilder();
    for (String name : names)
    {
       name.trim();
       sb.append(",");
       sb.append(name);
    }

    bmp = new Bitmap[icount+1];
    sub_list = sb.toString();
    Log.i("sub_list .. ",""+sub_list);
    pathArr = sub_list.split(",");

    for(int p=0;p<pathArr.length;p++)
    {
        if(pathArr[p]!=null)
        {
            bitmap = decodeFile(pathArr[p]);
            if(bitmap!=null)
            {
                items.add(pathArr[p]);
                bmp[p] = bitmap;
            }
        }
        if(pathArr[p] == null)
            break;
    }

    imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imagegrid.setAdapter(new ImageAdapter(getApplicationContext(),bmp));
    imagegrid.setOnItemClickListener(this);
    }
}

public class ImageAdapter extends BaseAdapter
{
    private Context mContext;
    Bitmap[] mImageArray;

    public ImageAdapter(Context c, Bitmap[] imgArray)
    {
          mContext = c;
          mImageArray = imgArray;
    }
    public int getCount()
    {
          return mImageArray.length;
    }
    public Object getItem(int position)
    {
          return position;
    }
    public long getItemId(int position)
    {
          return position;
    }

    public View getView(int position,View convertView,ViewGroup parent)
    {
        System.gc();
        ImageView i = null ;

        if (convertView == null )
        {
            i = new ImageView(mContext);
            i.setLayoutParams(new GridView.LayoutParams(92,92));
            i.setScaleType(ImageView.ScaleType.CENTER_CROP);
            i.setImageBitmap(mImageArray[position]);
        }
         else
             i = (ImageView) convertView;
         return i;
    }
}

public Bitmap decodeFile(String filePath)
{
    System.out.println("filepath in decode file .. "+filePath);
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 100;
    final int H = 50;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < H)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    System.out.println("decode file ........... "+filePath);
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}
}

Pls help me
Thanks

Body: Refer : Andriod API demos - Grid2.java


问:
Connecting DMS to S3
We are trying to get DMS set up with an S3 Source however we are unable to connect the replication instance to the Source S3 endpoint.

When we run a connection test on the source endpoint, the error we receive is:

Error Details: [errType=ERROR_RESPONSE, status=1020414, errMessage= Failed to connect to database., errDetails=]

We have followed the documentation however we are still unable to get the connection to work. The bucket is within the VPC that the replication instance has access to, and the IAM role has the GetObject, ListBucket and dms* permissions. I'm 95% sure that the JSON mapping file is set up correctly with schema and table names pointing to the right place.

Due to the lack of error messages or detailed reasons why we can't connect to the source database (the S3 bucket/CSV file), debugging this feels a tad hit and miss. We are using the Amazon Console and not the CLI, if that makes much of a difference.

答:
I had this same error.

Check this troubleshooting guide. It covers the basic configuration problems you might run into.

My answer wasn't there, tho, and I couldn't find it anywhere, not even asking in the official forums.

In my case, for some reason I thought I should use the full bucket name in the "Bucket Name" field, like "arn:aws:s3:::my-bucket". Probably because I had to use the ARN for the role in the previous field.

And the error message when you try to connect to it will not be clear, it only says it couldn't connect to the bucket. Anyway, you don't need to provide an ARN, just the bucket's name, as in "my-bucket".

Title: Connecting DMS to S3


问:
How do I use python/selenium to automate sequence of button clicks on a website?
The problem i am trying to solve is this: my home security system does not have a scheduling option and I frequently forget to switch on the system.

I am considering writing a python script that can open a browser, login to the website and click on buttons to activate the home alarm.

I see selenium recommended for automating browser and site action. I wonder though if these two tools can:

be scheduled to run even my computer is sleeping?

automate the whole nine yards - from opening the browser to button clicks to logging off?

I am new to the world of selenium / automation - appreciate any response. Thanks.

答:
Yes you can easily do that with Python and Selenium. You can also run it when your computer is in sleep mode, you can use Task Scheduler for that and set up a task that will wake your computer up and run your script and you wont even need to login (I'm assuming you use Windows here).

However, selenium scripts are as robust as you make them, and as @tjallo mentioned if there is an API available, its better to use that route instead. You can actually open the browser windows and open the dev console and look at the Network tab when you click on buttons to enable/disable certain features and see what requests are made, and then try to make same requests with the requests module in Python.

If you are interested exploring the topic of Selenium & Webdriver, I have an entire playlist which explains Selenium concepts from beginner to senior and you can find it here: https://www.youtube.com/playlist?list=PLK7KNOA7vbPOK1Ih3SXyaM1VnWut5Tn17


问:
How to prevent simultaneous logins of the same user with Firebase?
I'd like for the new session to essentially "log out" of any previous session. For example, when you are in an authenticated session in one computer, starting a new session on another computer and authenticating with firebase on our app will log out the other session on the first computer.

I haven't been able to find any method that allows me to log out of a session "remotely". I know that I can unauth() and goOffline() from within a session. But how do I do it from a different authenticated session of the same user?

Thanks for the help!

Background Info:

I am using simple email/password login for firebase authentication

I don't have security rules setup yet, although this is in the works

I'm using Javascript with Firebase

答:
TL;DR

https://pastebin.com/jWYu53Up

We've come across this topic as well. Despite the thread's obsolescence and the fact that it doesn't entirely outline our exact same desire we wanted to achieve, yet we could soak some of the general concepts of @kato's answer up. The conceptions have roughly remained the same but this thread definitely deserves a more up-to-date answer.

Heads-up: before you read this explanation right off the bat, be aware of the fact you'll likely find it a bit out of context because it doesn't entirely cover the original SO question. In fact, it's rather a different mental model to assemble a system to prevent multiple sessions at the same time. To be more precise, it's our mental model that fits our scenario. :)

For example, when you are in an authenticated session in one computer, starting a new session on another computer and authenticating with firebase on our app will log out the other session on the first computer.

Maintaining this type of "simultaneous-login-prevention" implies 1) the active sessions of each client should be differentiated even if it's from the same device 2) the client should be signed out from a particular device which AFAICT Firebase isn't capable of. FWIW you can revoke tokens to explicitly make ALL of the refresh tokens of the specified user expired and, therefore, it's prompted to sign in again but the downside of doing so is that it ruins ALL of the existing sessions(even the one that's just been activated).

These "overheads" led to approaching the problem in a slightly different manner. It differs in that 1) there's no need to keep track of concrete devices 2) the client is signed out programmatically without unnecessarily destroying any of its active sessions to enhance the user experience.

Leverage Firebase Presence to pass the heavy-lifting of keeping track of connection status changes of clients(even if the connection is terminated for some weird reason) but here's the catch: it does not natively come with Firestore. Refer to Connecting to Cloud Firestore to keep the databases in sync. It's also worthwhile to note we don't set a reference to the special .info/connected path compared to their examples. Instead, we take advantage of the onAuthStateChanged() observer to act in response to the authentication status changes.

const getUserRef = userId => firebase.database().ref(`/users/${userId}`);

firebase.auth().onAuthStateChanged(user => {
   if (user) {
      const userRef = getUserRef(user.uid);

      return userRef
         .onDisconnect()
         .set({
            is_online: false,
            last_seen: firebase.database.ServerValue.TIMESTAMP
         })
         .then(() =>
            // This sets the flag to true once `onDisconnect()` has been attached to the user's ref.
            userRef.set({
               is_online: true,
               last_seen: firebase.database.ServerValue.TIMESTAMP
            });
         );
   }
});
```

<p>After <code>onDisconnect()</code> has been correctly set, you'll have to ensure the user's session if it tries kicking off a sign-in alongside another active session, for which, forward a request to the database and check against the corresponding flag. Consequently, recognizing multiple sessions takes up a bit more time than usual due to this additional round-trip, hence the UI should be adjusted accordingly.</p>

<pre class="lang-js prettyprint-override"><code>const ensureUserSession = userId => {
   const userRef = getUserRef(userId);

   return userRef.once("value").then(snapshot => {
      if (!snapshot.exists()) {
         // If the user entry does not exist, create it and return with the promise.
         return userRef.set({
            last_seen: firebase.database.ServerValue.TIMESTAMP
         });
      }

      const user = snapshot.data();

      if (user.is_online) {
         // If the user is already signed in, throw a custom error to differentiate from other potential errors.
         throw new SessionAlreadyExists(...);
      }

      // Otherwise, return with a resolved promise to permit the sign-in.
      return Promise.resolve();
   });
};
</code>```

Combining these two snippets together results in https://pastebin.com/jWYu53Up.

Body:
TL;DR

https://pastebin.com/jWYu53Up

We've come across this topic as well. Despite the thread's obsolescence and the fact that it doesn't entirely outline our exact same desire we wanted to achieve, yet we could soak some of the general concepts of @kato's answer up. The conceptions have roughly remained the same but this thread definitely deserves a more up-to-date answer.

Heads-up: before you read this explanation right off the bat, be aware of the fact you'll likely find it a bit out of context because it doesn't entirely cover the original SO question. In fact, it's rather a different mental model to assemble a system to prevent multiple sessions at the same time. To be more precise, it's our mental model that fits our scenario. :)

For example, when you are in an authenticated session in one computer, starting a new session on another computer and authenticating with firebase on our app will log out the other session on the first computer.

Maintaining this type of "simultaneous-login-prevention" implies 1) the active sessions of each client should be differentiated even if it's from the same device 2) the client should be signed out from a particular device which AFAICT Firebase isn't capable of. FWIW you can revoke tokens to explicitly make ALL of the refresh tokens of the specified user expired and, therefore, it's prompted to sign in again but the downside of doing so is that it ruins ALL of the existing sessions(even the one that's just been activated).

These "overheads" led to approaching the problem in a slightly different manner. It differs in that 1) there's no need to keep track of concrete devices 2) the client is signed out programmatically without unnecessarily destroying any of its active sessions to enhance the user experience.

Leverage Firebase Presence to pass the heavy-lifting of keeping track of connection status changes of clients(even if the connection is terminated for some weird reason) but here's the catch: it does not natively come with Firestore. Refer to Connecting to Cloud Firestore to keep the databases in sync. It's also worthwhile to note we don't set a reference to the special .info/connected path compared to their examples. Instead, we take advantage of the onAuthStateChanged() observer to act in response to the authentication status changes.

const getUserRef = userId => firebase.database().ref(`/users/${userId}`);

firebase.auth().onAuthStateChanged(user => {
   if (user) {
      const userRef = getUserRef(user.uid);

      return userRef
         .onDisconnect()
         .set({
            is_online: false,
            last_seen: firebase.database.ServerValue.TIMESTAMP
         })
         .then(() =>
            // This sets the flag to true once `onDisconnect()` has been attached to the user's ref.
            userRef.set({
               is_online: true,
               last_seen: firebase.database.ServerValue.TIMESTAMP
            });
         );
   }
});

After onDisconnect() has been correctly set, you'll have to ensure the user's session if it tries kicking off a sign-in alongside another active session, for which, forward a request to the database and check against the corresponding flag. Consequently, recognizing multiple sessions takes up a bit more time than usual due to this additional round-trip, hence the UI should be adjusted accordingly.

const ensureUserSession = userId => {
   const userRef = getUserRef(userId);

   return userRef.once("value").then(snapshot => {
      if (!snapshot.exists()) {
         // If the user entry does not exist, create it and return with the promise.
         return userRef.set({
            last_seen: firebase.database.ServerValue.TIMESTAMP
         });
      }

      const user = snapshot.data();

      if (user.is_online) {
         // If the user is already signed in, throw a custom error to differentiate from other potential errors.
         throw new SessionAlreadyExists(...);
      }

      // Otherwise, return with a resolved promise to permit the sign-in.
      return Promise.resolve();
   });
};

Combining these two snippets together results in https://pastebin.com/jWYu53Up.


问:
Error: Environment /Users/myuser/.virtualenvs/iron does not contain activation script
I am running python 3.7.6 on macOS Catalina version 10.15.1 and I am trying to install and set up virtualenvwrapper which I have installed with pip3 install virtualenvwrapper.

I have the following lines in my .bash_profile:

```<code>export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV=/Users/maxcarey/Library/Python/3.7/bin/virtualenv
export WORKON_HOME=$HOME/.virtualenvs
source /Users/maxcarey/Library/Python/3.7/bin/virtualenvwrapper.sh
</code>```

These are configuration steps I have followed from:
https://stackoverflow.com/a/42643313/5420796. As well as other tutorials (like this one)

So you can see I'm attemping to point these export variables to the right place, in my terminal, the output of which python3 is /usr/local/bin/python3
The output of which virtualenv is: /Users/maxcarey/Library/Python/3.7/bin/virtualenv.
The output of which virtualenvwrapper.sh is /Users/maxcarey/Library/Python/3.7/bin/virtualenvwrapper.sh

Here is the problem: when I run: mkvirtualenv iron  to create a new virtual environment (called iron in this case), the output of the command is:

created virtual environment in 193ms CPython3Posix(dest=/Users/maxcarey/.virtualenvs/iron, clear=False, global=False) with seeder FromAppData pip=latest setuptools=latest wheel=latest app_data_dir=/Users/maxcarey/Library/Application Support/virtualenv/seed-v1 via=copy
virtualenvwrapper.user_scripts creating /Users/maxcarey/.virtualenvs/iron/bin/predeactivate
ERROR: Environment '/Users/maxcarey/.virtualenvs/iron' does not contain an activate script.

You can see that a virtual environment is indeed created, however, I get an error saying there is no activation script. However, when I navigate to ~/.virtualenvs, I can indeed see the activation scripts. Here is the output of tree inside the new folder iron/local/:

```<code>└── local
    └── bin
        ├── activate
        ├── activate.csh
        ├── activate.fish
        ├── activate.ps1
        ├── activate.xsh
        ├── activate_this.py
        ├── easy_install
        ├── easy_install-3.7
        ├── easy_install3
        ├── pip
        ├── pip-3.7
        ├── pip3
        ├── python -> /Library/Developer/CommandLineTools/usr/bin/python3
        ├── python3 -> python
        ├── python3.7 -> python
        ├── wheel
        ├── wheel-3.7
        └── wheel3

</code>```

It does indeed appear that there are activation scripts. So I am stumped about why I get the activation script error (which I also get when running workon iron). I have tried simply destroying and recreating the virtual environment with rmvirtualenv iron, which works, however, when creating the environment again I still get the same error. Thank You

答:
I was just hitting this, downgrading my virtualenv version to 20.0.3 allowed me to get around the issue.

pip3 uninstall virtualenv && pip3 install 'virtualenv==20.0.3'

Body:
I am running python 3.7.6 on macOS Catalina version 10.15.1 and I am trying to install and set up virtualenvwrapper which I have installed with pip3 install virtualenvwrapper.

I have the following lines in my .bash_profile:

export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV=/Users/maxcarey/Library/Python/3.7/bin/virtualenv
export WORKON_HOME=$HOME/.virtualenvs
source /Users/maxcarey/Library/Python/3.7/bin/virtualenvwrapper.sh

These are configuration steps I have followed from:
https://stackoverflow.com/a/42643313/5420796. As well as other tutorials (like this one)

So you can see I'm attemping to point these export variables to the right place, in my terminal, the output of which python3 is /usr/local/bin/python3
The output of which virtualenv is: /Users/maxcarey/Library/Python/3.7/bin/virtualenv.
The output of which virtualenvwrapper.sh is /Users/maxcarey/Library/Python/3.7/bin/virtualenvwrapper.sh

Here is the problem: when I run: mkvirtualenv iron  to create a new virtual environment (called iron in this case), the output of the command is:

created virtual environment in 193ms CPython3Posix(dest=/Users/maxcarey/.virtualenvs/iron, clear=False, global=False) with seeder FromAppData pip=latest setuptools=latest wheel=latest app_data_dir=/Users/maxcarey/Library/Application Support/virtualenv/seed-v1 via=copy
virtualenvwrapper.user_scripts creating /Users/maxcarey/.virtualenvs/iron/bin/predeactivate
ERROR: Environment '/Users/maxcarey/.virtualenvs/iron' does not contain an activate script.

You can see that a virtual environment is indeed created, however, I get an error saying there is no activation script. However, when I navigate to ~/.virtualenvs, I can indeed see the activation scripts. Here is the output of tree inside the new folder iron/local/:

└── local
    └── bin
        ├── activate
        ├── activate.csh
        ├── activate.fish
        ├── activate.ps1
        ├── activate.xsh
        ├── activate_this.py
        ├── easy_install
        ├── easy_install-3.7
        ├── easy_install3
        ├── pip
        ├── pip-3.7
        ├── pip3
        ├── python -> /Library/Developer/CommandLineTools/usr/bin/python3
        ├── python3 -> python
        ├── python3.7 -> python
        ├── wheel
        ├── wheel-3.7
        └── wheel3

It does indeed appear that there are activation scripts. So I am stumped about why I get the activation script error (which I also get when running workon iron). I have tried simply destroying and recreating the virtual environment with rmvirtualenv iron, which works, however, when creating the environment again I still get the same error. Thank You


问:
How do I get a cursor on every line in VS Code?
I'm trying to use the multi-cursor functionality of Visual Studio Code on a large(ish) file.

The file is too large to select every line individually with ctrl alt up or ctrl alt down.

In Sublime Text, I would select everything and press ctrl shift L.

Is there a similar thing in VS Code?
I've tried using a regex search for ^ (caret), but that gives me an error stating "Expression matches everything".

答:
Hold Alt+Shift+i

Hold Home (fn+-> Mac) for right-most or End for left most(fn+<- Mac)


问:
Gradle doesn't run tests
In my Gradle project I have a very simple JUnit test:

```<code>import org.junit.jupiter.api.Test
import static org.junit.jupiter.api.Assertions.fail

class ApiCallerTest {

    @Test
    void testSetApiKey() {
        fail();
    }
}
</code>```

When I run the test in IntelliJ, I get a list of tasks with the message that the build was successful. Eg.:

```<code>Testing started at 19:52 ...
> Task :cleanTest UP-TO-DATE
> Task :compileJava UP-TO-DATE
> Task :compileGroovy NO-SOURCE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava NO-SOURCE
> Task :compileTestGroovy NO-SOURCE
> Task :processTestResources NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test NO-SOURCE
BUILD SUCCESSFUL in 0s
</code>```

This should not happen since I am expecting the test to fail. I also get a message "Test events were not received".

This is my gradle.build file:

```<code>plugins {
    id 'groovy'
    id 'java'
}

group 'com.ipdive'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.0')
}
</code>```

According to suggestions on the internet I tried adding this code to the gradle.build file.

```<code>test {
    useJUnitPlatform()
}
</code>```

But that didn't help.

I also tried changing the Gradle setting to "Run tests using" -> "IntelliJ IDEA". When I run the test after this change, I get an error message:

```<code>Internal Error occurred.
org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:189)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:168)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.junit.platform.commons.JUnitException: MethodSelector [className = 'ApiCallerTest', methodName = 'testSetApiKey', methodParameterTypes = ''] resolution failed
    at org.junit.platform.launcher.listeners.discovery.AbortOnFailureLauncherDiscoveryListener.selectorProcessed(AbortOnFailureLauncherDiscoveryListener.java:39)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:102)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.run(EngineDiscoveryRequestResolution.java:82)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolver.resolve(EngineDiscoveryRequestResolver.java:113)
    at org.junit.jupiter.engine.discovery.DiscoverySelectorResolver.resolveSelectors(DiscoverySelectorResolver.java:45)
    at org.junit.jupiter.engine.JupiterTestEngine.discover(JupiterTestEngine.java:69)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:181)
    ... 6 more
Caused by: org.junit.platform.commons.PreconditionViolationException: Could not load class with name: ApiCallerTest
...
...
</code>```

Can you please tell me what to do so I can run my unit-tests with Gradle?

EDIT: Added screenshot of the project structure.

答:
You can use the configuration from the official junit5-samples. There you can find the junit5-jupiter-starter-gradle-groovy project that uses the following configuration:

```<code>plugins {
    id 'groovy'
    id 'eclipse' // optional (to generate Eclipse project files)
    id 'idea' // optional (to generate IntelliJ IDEA project files)
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(localGroovy())
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.0')
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}
</code>```

It works with Gradle 6.0.1, Java 8 and 11.

In order to run the tests you can use the following command:
gradle test or configure in your IDE as depicted:

You will see something like:

```<code>Testing started at 17:34 ...
> Task :cleanTest
> Task :compileJava NO-SOURCE
> Task :compileGroovy UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava UP-TO-DATE
> Task :compileTestGroovy UP-TO-DATE
> Task :processTestResources NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass$3$1 (file:/C:/Users/jmoreno/.gradle/caches/modules-2/files-2.1/org.codehaus.groovy/groovy-all/2.3.11/f6b34997d04c1538ce451d3955298f46fdb4dbd4/groovy-all-2.3.11.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass$3$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
com.example.project.CalculatorTestsJava > addsTwoNumbers() PASSED
com.example.project.CalculatorTestsJava > add(int, int, int)[1] PASSED
com.example.project.CalculatorTestsJava > add(int, int, int)[2] PASSED
com.example.project.CalculatorTestsJava > add(int, int, int)[3] PASSED
com.example.project.CalculatorTestsJava > add(int, int, int)[4] PASSED
com.example.project.CalculatorTests > add(int, int, int)[1] PASSED
com.example.project.CalculatorTests > add(int, int, int)[2] PASSED
com.example.project.CalculatorTests > add(int, int, int)[3] PASSED
com.example.project.CalculatorTests > add(int, int, int)[4] PASSED
com.example.project.CalculatorTests > 1 + 1 = 2() PASSED
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 3s
5 actionable tasks: 2 executed, 3 up-to-date
17:34:08: Tasks execution finished ':cleanTest :test --tests *'.
</code>```

Another point to take into account is the location of the classes.  According to documentation when we use the groovy plugin we can mix java & groovy files only in the groovy folder, in this case, the groovy class is in the java folder where we can only put java files.

It's important to use the correct dependencies too if you declare different versions of groovy it could generate compilation errors.

Title: Gradle doesn't run tests

Body:
In my Gradle project I have a very simple JUnit test:

import org.junit.jupiter.api.Test
import static org.junit.jupiter.api.Assertions.fail

class ApiCallerTest {

    @Test
    void testSetApiKey() {
        fail();
    }
}

When I run the test in IntelliJ, I get a list of tasks with the message that the build was successful. Eg.:

Testing started at 19:52 ...
> Task :cleanTest UP-TO-DATE
> Task :compileJava UP-TO-DATE
> Task :compileGroovy NO-SOURCE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava NO-SOURCE
> Task :compileTestGroovy NO-SOURCE
> Task :processTestResources NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test NO-SOURCE
BUILD SUCCESSFUL in 0s

This should not happen since I am expecting the test to fail. I also get a message "Test events were not received".

This is my gradle.build file:

plugins {
    id 'groovy'
    id 'java'
}

group 'com.ipdive'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.0')
}

According to suggestions on the internet I tried adding this code to the gradle.build file.

test {
    useJUnitPlatform()
}

But that didn't help.

I also tried changing the Gradle setting to "Run tests using" -> "IntelliJ IDEA". When I run the test after this change, I get an error message:

Internal Error occurred.
org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:189)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:168)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: org.junit.platform.commons.JUnitException: MethodSelector [className = 'ApiCallerTest', methodName = 'testSetApiKey', methodParameterTypes = ''] resolution failed
    at org.junit.platform.launcher.listeners.discovery.AbortOnFailureLauncherDiscoveryListener.selectorProcessed(AbortOnFailureLauncherDiscoveryListener.java:39)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.resolveCompletely(EngineDiscoveryRequestResolution.java:102)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolution.run(EngineDiscoveryRequestResolution.java:82)
    at org.junit.platform.engine.support.discovery.EngineDiscoveryRequestResolver.resolve(EngineDiscoveryRequestResolver.java:113)
    at org.junit.jupiter.engine.discovery.DiscoverySelectorResolver.resolveSelectors(DiscoverySelectorResolver.java:45)
    at org.junit.jupiter.engine.JupiterTestEngine.discover(JupiterTestEngine.java:69)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:181)
    ... 6 more
Caused by: org.junit.platform.commons.PreconditionViolationException: Could not load class with name: ApiCallerTest
...
...

Can you please tell me what to do so I can run my unit-tests with Gradle?

EDIT: Added screenshot of the project structure.

Body:
You can use the configuration from the official junit5-samples. There you can find the junit5-jupiter-starter-gradle-groovy project that uses the following configuration:

plugins {
    id 'groovy'
    id 'eclipse' // optional (to generate Eclipse project files)
    id 'idea' // optional (to generate IntelliJ IDEA project files)
}

repositories {
    mavenCentral()
}

dependencies {
    implementation(localGroovy())
    testImplementation('org.junit.jupiter:junit-jupiter:5.6.0')
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "skipped", "failed"
    }
}

It works with Gradle 6.0.1, Java 8 and 11.

In order to run the tests you can use the following command:
gradle test or configure in your IDE as depicted:

You will see something like:

Testing started at 17:34 ...
> Task :cleanTest
> Task :compileJava NO-SOURCE
> Task :compileGroovy UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava UP-TO-DATE
> Task :compileTestGroovy UP-TO-DATE
> Task :processTestResources NO-SOURCE
> Task :testClasses UP-TO-DATE
> Task :test
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass$3$1 (file:/C:/Users/jmoreno/.gradle/caches/modules-2/files-2.1/org.codehaus.groovy/groovy-all/2.3.11/f6b34997d04c1538ce451d3955298f46fdb4dbd4/groovy-all-2.3.11.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass$3$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
com.example.project.CalculatorTestsJava > addsTwoNumbers() PASSED
com.example.project.CalculatorTestsJava > add(int, int, int)[1] PASSED
com.example.project.CalculatorTestsJava > add(int, int, int)[2] PASSED
com.example.project.CalculatorTestsJava > add(int, int, int)[3] PASSED
com.example.project.CalculatorTestsJava > add(int, int, int)[4] PASSED
com.example.project.CalculatorTests > add(int, int, int)[1] PASSED
com.example.project.CalculatorTests > add(int, int, int)[2] PASSED
com.example.project.CalculatorTests > add(int, int, int)[3] PASSED
com.example.project.CalculatorTests > add(int, int, int)[4] PASSED
com.example.project.CalculatorTests > 1 + 1 = 2() PASSED
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 3s
5 actionable tasks: 2 executed, 3 up-to-date
17:34:08: Tasks execution finished ':cleanTest :test --tests *'.

Another point to take into account is the location of the classes.  According to documentation when we use the groovy plugin we can mix java & groovy files only in the groovy folder, in this case, the groovy class is in the java folder where we can only put java files.

It's important to use the correct dependencies too if you declare different versions of groovy it could generate compilation errors.


问:
How can I program a loop so that it does not stop upon failure?
I have a loop that is doing a GPG verification, serially. When it gets to a failure however, it exits the loop. How can I program this loop so that it does not?

Currently I have:

```<code>while read -r line;
gpg --verify $line
do
  if gpg --verify $line; then
   echo "success";
  else
   echo "failed gpg check";
  fi
done < gpg_verify.txt
</code>```

I want the failure to be acknowledged but I don't want it to stop.

答:
Don't use the verification to decide when to exit the loop. Also, fix your quoting.

while read -r line
do
  if gpg --verify "$line"; then
   echo "success";
  else
   echo "failed gpg check";
  fi
done < gpg_verify.txt
```

Just to spell this out, while x; y stops whenever y fails, and won't stop when x fails. Perhaps you meant while x && y but here, just put y inside the loop if that's what you actually want.

Body:
I have a loop that is doing a GPG verification, serially. When it gets to a failure however, it exits the loop. How can I program this loop so that it does not?

Currently I have:

while read -r line;
gpg --verify $line
do
  if gpg --verify $line; then
   echo "success";
  else
   echo "failed gpg check";
  fi
done < gpg_verify.txt

I want the failure to be acknowledged but I don't want it to stop.

Body:
Don't use the verification to decide when to exit the loop. Also, fix your quoting.

while read -r line
do
  if gpg --verify "$line"; then
   echo "success";
  else
   echo "failed gpg check";
  fi
done < gpg_verify.txt

Just to spell this out, while x; y stops whenever y fails, and won't stop when x fails. Perhaps you meant while x && y but here, just put y inside the loop if that's what you actually want.


问:
BSON map to database models struct
Struggling to figure out the correct way to do this. Right now I can convert a bson map to my database model structs individually. But now I'm just repeating a lot of the same code. So is there a better way to do this?

Example of code:

```<code>type Agent struct {
    FirstName      string   `bson:"firstName,omitempty" json:"firstName,omitempty"`
    LastName       string   `bson:"lastName,omitempty" json:"lastName,omitempty"`
    ProfileImage   string   `bson:"profileImage,omitempty" json:"profileImage,omitempty"`
}

func BSONToAgent(bsonMap primitive.M) (agent Agent, err error) {
    bsonBytes, err := bson.Marshal(bsonMap)
    if err != nil {
        return agent, err
    }
    bson.Unmarshal(bsonBytes, &agent)
    return agent, nil
}

func BSONArrayToAgents(bsonMap []primitive.M) (agents []Agent, err error) {
    for _, item := range bsonMap {
        agent, err := BSONToAgent(item)
        if err != nil {
            return agents, err
        }
        agents = append(agents, agent)
    }
    return agents, nil
}

type Form struct {
    UserID        primitive.ObjectID `bson:"userId,omitempty" json:"userId,omitempty"`
    Name          string             `bson:"name,omitempty" json:"name,omitempty"`
    CreatedAt     time.Time          `bson:"createdAt,omitempty" json:"createdAt,omitempty"`
    UpdatedAt     time.Time          `bson:"updatedAt,omitempty" json:"updatedAt,omitempty"`
}

func BSONArrayToForms(bsonMap []primitive.M) (forms []Form, err error) {
    for _, item := range bsonMap {
        form, err := BSONToForm(item)
        if err != nil {
            return forms, err
        }
        forms = append(forms, form)
    }
    return forms, nil
}

func BSONToForm(bsonMap primitive.M) (form Form, err error) {
    bsonBytes, err := bson.Marshal(bsonMap)
    if err != nil {
        return form, err
    }
    bson.Unmarshal(bsonBytes, &form)
    return form, nil
}

</code>```

If you look at functions BSONToAgent and BSONToForm they are pretty much the same function just with a different Type that it returns. And the same goes for BSONArrayToAgents and BSONArrayToForms. Now I want to implement these functions on all my database models to make it easy to convert a primitive.M (bson map) that is returned when querying the database.

Is there a better way to do this? Maybe using an interface?

答:
If you're using marshal/unmarshal as a means to translating bson, you can do:

```<code>func BSONToForm(bsonMap primitive.M, out interface{}) (err error) {
    bsonBytes, err := bson.Marshal(bsonMap)
    if err != nil {
        return form, err
    }
    return bson.Unmarshal(bsonBytes, out)
}

var v Form
BSONToForm(bsonMap,&v)
</code>```

This doesn't work as nicely for arrays though, so you can do something like this:

```<code>func BSONArrayToForms(bsonMap []primitive.M, newItem func() interface{}, add func(interface{})) (err error) {
    for _, item := range bsonMap {
        n:=newItem()
        err := BSONToForm(item,n)
        if err != nil {
            return forms, err
        }
        add(n)
    }
    return nil
}

forms:=make([]Form,0)
BSONArrayToForms(bsonArr,func() interface{} {return &Form{}},func(in interface{}) {
   forms=append(forms,*(in.(*Form)))
})
</code>```

Or a single-func variant:

```<code>func BSONArrayToForms(bsonMap []primitive.M, newItem func() interface{}) (err error) {
    for _, item := range bsonMap {
        n:=newItem()
        err := BSONToForm(item,n)
        if err != nil {
            return forms, err
        }
    }
    return nil
}

forms:=make([]Form,0)
BSONArrayToForms(bsonArr,func() interface{} {
   forms=append(forms,Form{})
   return &forms[len(forms)-1]})

</code>```

This version has to make sure that the returned pointer is also stored in the array.

Title: BSON map to database models struct

Body:
Struggling to figure out the correct way to do this. Right now I can convert a bson map to my database model structs individually. But now I'm just repeating a lot of the same code. So is there a better way to do this?

Example of code:

type Agent struct {
    FirstName      string   `bson:"firstName,omitempty" json:"firstName,omitempty"`
    LastName       string   `bson:"lastName,omitempty" json:"lastName,omitempty"`
    ProfileImage   string   `bson:"profileImage,omitempty" json:"profileImage,omitempty"`
}

func BSONToAgent(bsonMap primitive.M) (agent Agent, err error) {
    bsonBytes, err := bson.Marshal(bsonMap)
    if err != nil {
        return agent, err
    }
    bson.Unmarshal(bsonBytes, &agent)
    return agent, nil
}

func BSONArrayToAgents(bsonMap []primitive.M) (agents []Agent, err error) {
    for _, item := range bsonMap {
        agent, err := BSONToAgent(item)
        if err != nil {
            return agents, err
        }
        agents = append(agents, agent)
    }
    return agents, nil
}

type Form struct {
    UserID        primitive.ObjectID `bson:"userId,omitempty" json:"userId,omitempty"`
    Name          string             `bson:"name,omitempty" json:"name,omitempty"`
    CreatedAt     time.Time          `bson:"createdAt,omitempty" json:"createdAt,omitempty"`
    UpdatedAt     time.Time          `bson:"updatedAt,omitempty" json:"updatedAt,omitempty"`
}

func BSONArrayToForms(bsonMap []primitive.M) (forms []Form, err error) {
    for _, item := range bsonMap {
        form, err := BSONToForm(item)
        if err != nil {
            return forms, err
        }
        forms = append(forms, form)
    }
    return forms, nil
}

func BSONToForm(bsonMap primitive.M) (form Form, err error) {
    bsonBytes, err := bson.Marshal(bsonMap)
    if err != nil {
        return form, err
    }
    bson.Unmarshal(bsonBytes, &form)
    return form, nil
}

If you look at functions BSONToAgent and BSONToForm they are pretty much the same function just with a different Type that it returns. And the same goes for BSONArrayToAgents and BSONArrayToForms. Now I want to implement these functions on all my database models to make it easy to convert a primitive.M (bson map) that is returned when querying the database.

Is there a better way to do this? Maybe using an interface?

Body:
If you're using marshal/unmarshal as a means to translating bson, you can do:

func BSONToForm(bsonMap primitive.M, out interface{}) (err error) {
    bsonBytes, err := bson.Marshal(bsonMap)
    if err != nil {
        return form, err
    }
    return bson.Unmarshal(bsonBytes, out)
}

var v Form
BSONToForm(bsonMap,&v)

This doesn't work as nicely for arrays though, so you can do something like this:

func BSONArrayToForms(bsonMap []primitive.M, newItem func() interface{}, add func(interface{})) (err error) {
    for _, item := range bsonMap {
        n:=newItem()
        err := BSONToForm(item,n)
        if err != nil {
            return forms, err
        }
        add(n)
    }
    return nil
}

forms:=make([]Form,0)
BSONArrayToForms(bsonArr,func() interface{} {return &Form{}},func(in interface{}) {
   forms=append(forms,*(in.(*Form)))
})

Or a single-func variant:

func BSONArrayToForms(bsonMap []primitive.M, newItem func() interface{}) (err error) {
    for _, item := range bsonMap {
        n:=newItem()
        err := BSONToForm(item,n)
        if err != nil {
            return forms, err
        }
    }
    return nil
}

forms:=make([]Form,0)
BSONArrayToForms(bsonArr,func() interface{} {
   forms=append(forms,Form{})
   return &forms[len(forms)-1]})

This version has to make sure that the returned pointer is also stored in the array.


问:
How to play a video from either a local or a server URL in iOS
How can I play a .mp4 or .mov video from either an Internet URL or a local file in iOS?</p>

答:
1.First of all add MediaPlayer.Framework in XCode

2.Then add #import < MediaPlayer/MediaPlayer.h > in your viewController's .h file

3.Now implement this code in your viewDidLoad Method

```<code>     //NSString *filepath = [[NSBundle mainBundle] pathForResource:@"aaa" ofType:@"mp4"];
     //NSURL    *fileURL = [NSURL fileURLWithPath:filepath];

     NSURL *fileURL = [NSURL URLWithString:@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"];

     moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
     [moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)];
     [self.view addSubview:moviePlayerController.view];
     moviePlayerController.fullscreen = YES;
     [moviePlayerController play];
</code>```

For Orientation Please add this code

```<code> - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
     // Return YES for supported orientations
          if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
         [moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)];
     } else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
         [moviePlayerController.view setFrame:CGRectMake(0, 0, 480, 320)];
     }
     return YES;
 }
</code>```

In this code moviePlayerController is MPMoviePlayerController declared in .h file

Body:
1.First of all add MediaPlayer.Framework in XCode

2.Then add #import < MediaPlayer/MediaPlayer.h > in your viewController's .h file

3.Now implement this code in your viewDidLoad Method

     //NSString *filepath = [[NSBundle mainBundle] pathForResource:@"aaa" ofType:@"mp4"];
     //NSURL    *fileURL = [NSURL fileURLWithPath:filepath];

     NSURL *fileURL = [NSURL URLWithString:@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"];

     moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
     [moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)];
     [self.view addSubview:moviePlayerController.view];
     moviePlayerController.fullscreen = YES;
     [moviePlayerController play];

For Orientation Please add this code

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
     // Return YES for supported orientations
          if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
         [moviePlayerController.view setFrame:CGRectMake(0, 70, 320, 270)];
     } else if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
         [moviePlayerController.view setFrame:CGRectMake(0, 0, 480, 320)];
     }
     return YES;
 }

In this code moviePlayerController is MPMoviePlayerController declared in .h file


问:
Navbar dropdown menu href links not a working properly (Django+Bootstrap)
I am creating a small web application with using Django and Bootstrap4. In my Project Folder in Django, I have the templates and one of them is the base template. The other templates extend the base template. I have added the Bootstrap CDN to the base template and is working fine. I have created Bootstrap Navbar which get a dropdown when adjusted to screen size.

The issue is when I click a nav-link it adds the path in its href to the current path displayed in my browser i.e the location of the previous nav-link and searches for that. Hence it gives me an error. Upon clicking it should only take the path of only the clicked nav-link. My code is below. The href links are coming from my urls.py file. Please advise how to resolve this. Thanks.

base.html code

答:
This has nothing to do with Django. The problem is you are using relative urls, instead of absolute, or root-relative urls. Here are examples of all three:

some-page/

This is a relative url. It will take you to whatever page you're on plus "some-page/"

https://example.com/some-page/

This is an absolute url. It will take you to the exact url no matter where you are on the site.

/some-page/

This is a root-relative url. It will take you to your root domain (https://example.com in this case), plus the url given. This is the preferred option, because you don't have to change it from development (it will take you to 127.0.0.1:8000/some-page/) to production.

Now, since you're using Django, you can do something even better: use Django's built-in url templatetag. You would modify your href to be something like this, using the name of each path given in your urls.py file:

Login

```

Doing it this way is best, because if later you want to change the exact url (say, to 'profile/log-in/'), you only need to do so in your urls.py file, and not in any HTML files you have the old url defined.

Body:
This has nothing to do with Django. The problem is you are using relative urls, instead of absolute, or root-relative urls. Here are examples of all three:

some-page/

This is a relative url. It will take you to whatever page you're on plus "some-page/"

https://example.com/some-page/

This is an absolute url. It will take you to the exact url no matter where you are on the site.

/some-page/

This is a root-relative url. It will take you to your root domain (https://example.com in this case), plus the url given. This is the preferred option, because you don't have to change it from development (it will take you to 127.0.0.1:8000/some-page/) to production.

Now, since you're using Django, you can do something even better: use Django's built-in url templatetag. You would modify your href to be something like this, using the name of each path given in your urls.py file:

<a href="{% url 'login' %}">Login</a>
<!-- OR <a href="{% url 'profiles:login' %}">Login</a> if the url is in your profiles/urls.py file -->

Doing it this way is best, because if later you want to change the exact url (say, to 'profile/log-in/'), you only need to do so in your urls.py file, and not in any HTML files you have the old url defined.


问:
Can't re-open Component Tree on Android Studio
I just downloaded Android Studio, and while I was trying to familiarize myself with the setup, I accidentally closed the Component Tree. I'm at very beginner level, and in all of the results I've come across, I didn't understand or it didn't work for me. How do I find the Component Tree again?

Edit: Here's a screenshot:

答: If you mean the "Component Tree" of the XML preview, this can be collapsed & expanded alike all other sidebars; it might be at the bottom-left of the XML preview window, where "Palette" is. It just sometimes requires double-clicking, in order to expand that panel. I tried, but I didn't manage to hide or remove it; if it is really missing, the Android Studio installation might be broken (needs reinstall).</p>


问:
Check if the JSON from the Response is NULL or not
I am trying to check if the response from the API GET method is Null. The response is like

```<code>{
    "@odata.context": "https://dev.com/data/$metadata#Customers",
    "value": []
}
</code>```

I need to check if the value array is null or not and do the necessary steps below is what I tried

```<code>public class deserializeData
{
    public String @odata_context {get;set;} // in json: @odata.context
    public List<Value> value {get;set;}
}

public class getDataFromExternalSystem{
  public string getDataFrom(){
    .......
    Http http1 = new Http();
    HttpRequest req1 = new HttpRequest();
    req1.setEndpoint(endPoint);
    req1.setMethod('GET');
    req1.setHeader('Authorization','Bearer '+atoken);
    HttpResponse res1 = http1.send(req1);
    System.debug('Response Body=========' + res1.getBody());

    deserializeData dsData = (deserializeData)JSON.deserialize(res1.getbody(),deserializeData.class);

    if(dsData.value.size = null) {
       ......
    }
    else{
       ......
    }}
</code>```

But I get below error like

答:
@odata_context is not a legal identifier in Apex. @ is used to introduce annotations.

If you're using JSON2Apex, which appears to be the case, you'll need to change the name of the property to something legal for Apex (like odata_context), and make the corresponding change in the parser method. E.g., where JSON2Apex generates

```<code>                if (text == '@odata.context') {
                    @odata_context = parser.getText();
</code>```

you'll need to replace that identifier with the new one you choose.

Body:
I am trying to check if the response from the API GET method is Null. The response is like

{
    "@odata.context": "https://dev.com/data/$metadata#Customers",
    "value": []
}

I need to check if the value array is null or not and do the necessary steps below is what I tried

public class deserializeData
{
    public String @odata_context {get;set;} // in json: @odata.context
    public List<Value> value {get;set;}
}

public class getDataFromExternalSystem{
  public string getDataFrom(){
    .......
    Http http1 = new Http();
    HttpRequest req1 = new HttpRequest();
    req1.setEndpoint(endPoint);
    req1.setMethod('GET');
    req1.setHeader('Authorization','Bearer '+atoken);
    HttpResponse res1 = http1.send(req1);
    System.debug('Response Body=========' + res1.getBody());

    deserializeData dsData = (deserializeData)JSON.deserialize(res1.getbody(),deserializeData.class);

    if(dsData.value.size = null) {
       ......
    }
    else{
       ......
    }}

But I get below error like

Body:
@odata_context is not a legal identifier in Apex. @ is used to introduce annotations.

If you're using JSON2Apex, which appears to be the case, you'll need to change the name of the property to something legal for Apex (like odata_context), and make the corresponding change in the parser method. E.g., where JSON2Apex generates

                if (text == '@odata.context') {
                    @odata_context = parser.getText();

you'll need to replace that identifier with the new one you choose.


问:
Rank and unrank combinations to distribute k balls into n bins of different capacities
I want to distribute k balls into n bins of different capacities. How can I rank and unrank the distributions given n, k, and the bin capacities?

Example:

n := 3

k := 4

bin capacities := 3,2,1

Balls in bins:

1,2,1, 2,1,1, 2,2,0, 3,0,1, 3,1,0 := 5

Is there a formula?

答:
You can define the number of such combinations recursively. Given k balls and bin capacities q_1, ..., q_n, for each j between 0 andq_1, place j balls in q_1 and allocate the remaining k-j balls among other bins.

Here is a quick Python implementation:

```<code>from functools import lru_cache

@lru_cache(None)
def f(n, *qs):
  if not qs:
    return 1 if n == 0 else 0
  q = qs[0]
  return sum(f(n-j, *qs[1:]) for j in range(q+1))

f(4, 3, 2, 1)
# 5
</code>```

Body:
You can define the number of such combinations recursively. Given k balls and bin capacities q_1, ..., q_n, for each j between 0 andq_1, place j balls in q_1 and allocate the remaining k-j balls among other bins.

Here is a quick Python implementation:

from functools import lru_cache

@lru_cache(None)
def f(n, *qs):
  if not qs:
    return 1 if n == 0 else 0
  q = qs[0]
  return sum(f(n-j, *qs[1:]) for j in range(q+1))

f(4, 3, 2, 1)
# 5


问:
I can't find a way to select items from a list, each made of three text fields
I have looked at tens of examples and tutorials, and I have tried to repeat the same steps, but it is not working.

In my activity, I have four onClickListeners that work perfectly fine and are related to four buttons on the top part of my layout. The problem arises when, in addition, I try to set an onItemClickListener for the items of the ListView in the bottom part of the same layout. Each item of this ListView is made of three textViews, and I have written a custom adapter for them. They show up perfectly, but when I click on them nothing happens (the onItemClick instructions are never reached).

This is the layout, the problem is with the "ingredients_list_view" towards the end:
(by the way, the very last item, @android:id/list", is there only because otherwise I get a compile error in my activity, I haven't yet figured out why - otherwise I don't need it, and it is not supposed to show or do anything at all)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_recipe_name"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextTitle"
        android:layout_gravity="top"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_servings"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextServings"
        android:layout_gravity="top"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_cake_size"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextSize"
        android:layout_gravity="top"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/btnEditDelete"
            android:orientation="horizontal">

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_edit"
                android:id="@+id/btnEdit"/>

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_delete"
                android:id="@+id/btnDelete"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0"
            android:id="@+id/btnSaveCancel"
            android:orientation="horizontal">

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_save"
                android:id="@+id/btnSave"/>

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_cancel"
                android:id="@+id/btnCancel"/>

        </LinearLayout>
    </LinearLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ingredients_list_view"
        android:divider="#48C"
        android:dividerHeight="1dp"
        android:layout_weight="1" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:id="@android:id/list"/>

</LinearLayout>
</code>```

This is the layout for each item of the listView

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/ingredient_list_item"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
    <EditText
        android:id="@+id/quantity_list_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
    <EditText
        android:id="@+id/unit_list_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
</LinearLayout>
</code>```

... and  these are the relevant sections of the main activity:

```<code>
public class Recipe extends ListActivity implements View.OnClickListener {

    public static final String TABLE = "Recipes";

    public static final String KEY_ID = "recipeID";
    public static final String KEY_title = "title";
    public static final String KEY_servings = "servings";
    public static final String KEY_size = "size";

    public int recipeID;
    public String title;
    public String servings;
    public String size;

    Button btnEdit, btnDelete, btnSave, btnCancel;
    LinearLayout btnEditDelete, btnSaveCancel;
    EditText editTextTitle;
    EditText editTextServings;
    EditText editTextSize;

    int _Recipe_Id;
    int editMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_view);
        redraw();
    }

    @Override
    public void onClick(View view) {
// These work perfectly fine (except for the last one)
        RecipeDBOps repo = new RecipeDBOps(this);
        ArrayList<HashMap<String, String>> recipeList = repo.getRecipeList(); // so far not used
        if (view == findViewById(R.id.btnDelete)) {
            MixDBOps.delete(_Recipe_Id);
            RecipeDBOps.delete(_Recipe_Id);
            finish();
        }
        else if (view == findViewById(R.id.btnEdit)) { // Changes the fields to "editable" and switches button
            setEditMode();
        }
        else if (view == findViewById(R.id.btnCancel)) {
            finish();
        }
        else if (view == findViewById(R.id.btnSave)){
            Recipe recipe = RecipeDBOps.getRecipeById(_Recipe_Id);
            recipe.title = editTextTitle.getText().toString();
            recipe.servings = editTextServings.getText().toString();
            recipe.size = editTextSize.getText().toString();
            RecipeDBOps.update (recipe);
            finish();
        }
        else if (view == findViewById(R.id.ingredients_list_view)){
            System.out.println("OK2"); // Tried, but doesn't work
        }
    }

    public void setWeight (LinearLayout ll, LinearLayout.LayoutParams visibility){...}

    public void setReadOnlyMode(){...}

    public void setEditMode(){...}

    public void redraw(){
        editTextTitle = (EditText) findViewById(R.id.editTextTitle);
        editTextServings = (EditText) findViewById(R.id.editTextServings);
        editTextSize = (EditText) findViewById(R.id.editTextSize);
        btnEdit = (Button) findViewById(R.id.btnEdit);
        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnSave = (Button) findViewById(R.id.btnSave);
        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnEditDelete = (LinearLayout) findViewById(R.id.btnEditDelete);
        btnSaveCancel = (LinearLayout) findViewById(R.id.btnSaveCancel);

        setReadOnlyMode();

        //
        // Populate recipe fields
        //
        Intent intent = getIntent();
        _Recipe_Id = intent.getIntExtra("recipe_ID", 0);
        editMode = intent.getIntExtra("editMode", 0);
        RecipeDBOps repo = new RecipeDBOps(this);
        Recipe recipe;
        recipe = repo.getRecipeById(_Recipe_Id);

        if (recipe.title != null) {
            editTextTitle.setText(recipe.title);
            editTextServings.setText(recipe.servings);
            editTextSize.setText(recipe.size);
        }

        //
        // Populate recipe and ingredient fields
        //
        ArrayList<Entry> arrayOfEntries = new ArrayList<Entry>();
        EntryAdapter adapter = new EntryAdapter(this, arrayOfEntries);
        ListView listView = (ListView) findViewById(R.id.ingredients_list_view);
        listView.setAdapter(adapter);
////////////////////////////////////////////////////////////////////////////////////
        // This is the part that does not work
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ListView clickedObj = (ListView) parent.getItemAtPosition(position);
            // Once I am able to activate this onItemClick I will write the rest of the code to deal with clickdObj
            System.out.println("OK1");
        }});
////////////////////////////////////////////////////////////////////////////////////

        HashMap<String, String> h;
        MixDBOps repoMix = new MixDBOps(this); // repo represents the DB
        ArrayList<HashMap<String, String>> entryList = repoMix.getMixById(_Recipe_Id); // recipeList is the output of the SQL query
        Entry[] ent = new Entry[entryList.size()];

        for (int i = 0; i < entryList.size(); i++) {
            h = entryList.get(i);
            ent[i] = new Entry();
            ent[i].recipe_name = recipe.title;
            ent[i].ingredient_name = h.get("ingredient_name"); // temporarily replaced by spinner
            ent[i].quantity= Integer.parseInt(h.get("quantity"));
            ent[i].unit_name= h.get("unit_name");
            adapter.add(ent[i]);
        }

        btnEdit = (Button) findViewById(R.id.btnEdit);
        btnEdit.setOnClickListener(this);

        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(this);

        btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);

        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(this);

        if (editMode == 1){
            setEditMode();
        }
    }
}

</code>```

Is anybody able to help me?

答:
add two attribute in each edit text of item of list view </p>

```<code>    android:focusable="false"
    android:clickable="false"
</code>```

Body:
I have looked at tens of examples and tutorials, and I have tried to repeat the same steps, but it is not working.

In my activity, I have four onClickListeners that work perfectly fine and are related to four buttons on the top part of my layout. The problem arises when, in addition, I try to set an onItemClickListener for the items of the ListView in the bottom part of the same layout. Each item of this ListView is made of three textViews, and I have written a custom adapter for them. They show up perfectly, but when I click on them nothing happens (the onItemClick instructions are never reached).

This is the layout, the problem is with the "ingredients_list_view" towards the end:
(by the way, the very last item, @android:id/list", is there only because otherwise I get a compile error in my activity, I haven't yet figured out why - otherwise I don't need it, and it is not supposed to show or do anything at all)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_recipe_name"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextTitle"
        android:layout_gravity="top"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_servings"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextServings"
        android:layout_gravity="top"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/label_cake_size"
        android:layout_gravity="top"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:id="@+id/editTextSize"
        android:layout_gravity="top"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/btnEditDelete"
            android:orientation="horizontal">

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_edit"
                android:id="@+id/btnEdit"/>

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_delete"
                android:id="@+id/btnDelete"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0"
            android:id="@+id/btnSaveCancel"
            android:orientation="horizontal">

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_save"
                android:id="@+id/btnSave"/>

            <Button
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_cancel"
                android:id="@+id/btnCancel"/>

        </LinearLayout>
    </LinearLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ingredients_list_view"
        android:divider="#48C"
        android:dividerHeight="1dp"
        android:layout_weight="1" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:id="@android:id/list"/>

</LinearLayout>

This is the layout for each item of the listView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/ingredient_list_item"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
    <EditText
        android:id="@+id/quantity_list_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
    <EditText
        android:id="@+id/unit_list_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="22sp"
        android:textStyle="bold" />
</LinearLayout>

... and  these are the relevant sections of the main activity:

public class Recipe extends ListActivity implements View.OnClickListener {

    public static final String TABLE = "Recipes";

    public static final String KEY_ID = "recipeID";
    public static final String KEY_title = "title";
    public static final String KEY_servings = "servings";
    public static final String KEY_size = "size";

    public int recipeID;
    public String title;
    public String servings;
    public String size;

    Button btnEdit, btnDelete, btnSave, btnCancel;
    LinearLayout btnEditDelete, btnSaveCancel;
    EditText editTextTitle;
    EditText editTextServings;
    EditText editTextSize;

    int _Recipe_Id;
    int editMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_view);
        redraw();
    }

    @Override
    public void onClick(View view) {
// These work perfectly fine (except for the last one)
        RecipeDBOps repo = new RecipeDBOps(this);
        ArrayList<HashMap<String, String>> recipeList = repo.getRecipeList(); // so far not used
        if (view == findViewById(R.id.btnDelete)) {
            MixDBOps.delete(_Recipe_Id);
            RecipeDBOps.delete(_Recipe_Id);
            finish();
        }
        else if (view == findViewById(R.id.btnEdit)) { // Changes the fields to "editable" and switches button
            setEditMode();
        }
        else if (view == findViewById(R.id.btnCancel)) {
            finish();
        }
        else if (view == findViewById(R.id.btnSave)){
            Recipe recipe = RecipeDBOps.getRecipeById(_Recipe_Id);
            recipe.title = editTextTitle.getText().toString();
            recipe.servings = editTextServings.getText().toString();
            recipe.size = editTextSize.getText().toString();
            RecipeDBOps.update (recipe);
            finish();
        }
        else if (view == findViewById(R.id.ingredients_list_view)){
            System.out.println("OK2"); // Tried, but doesn't work
        }
    }

    public void setWeight (LinearLayout ll, LinearLayout.LayoutParams visibility){...}

    public void setReadOnlyMode(){...}

    public void setEditMode(){...}

    public void redraw(){
        editTextTitle = (EditText) findViewById(R.id.editTextTitle);
        editTextServings = (EditText) findViewById(R.id.editTextServings);
        editTextSize = (EditText) findViewById(R.id.editTextSize);
        btnEdit = (Button) findViewById(R.id.btnEdit);
        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnSave = (Button) findViewById(R.id.btnSave);
        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnEditDelete = (LinearLayout) findViewById(R.id.btnEditDelete);
        btnSaveCancel = (LinearLayout) findViewById(R.id.btnSaveCancel);

        setReadOnlyMode();

        //
        // Populate recipe fields
        //
        Intent intent = getIntent();
        _Recipe_Id = intent.getIntExtra("recipe_ID", 0);
        editMode = intent.getIntExtra("editMode", 0);
        RecipeDBOps repo = new RecipeDBOps(this);
        Recipe recipe;
        recipe = repo.getRecipeById(_Recipe_Id);

        if (recipe.title != null) {
            editTextTitle.setText(recipe.title);
            editTextServings.setText(recipe.servings);
            editTextSize.setText(recipe.size);
        }

        //
        // Populate recipe and ingredient fields
        //
        ArrayList<Entry> arrayOfEntries = new ArrayList<Entry>();
        EntryAdapter adapter = new EntryAdapter(this, arrayOfEntries);
        ListView listView = (ListView) findViewById(R.id.ingredients_list_view);
        listView.setAdapter(adapter);
////////////////////////////////////////////////////////////////////////////////////
        // This is the part that does not work
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ListView clickedObj = (ListView) parent.getItemAtPosition(position);
            // Once I am able to activate this onItemClick I will write the rest of the code to deal with clickdObj
            System.out.println("OK1");
        }});
////////////////////////////////////////////////////////////////////////////////////

        HashMap<String, String> h;
        MixDBOps repoMix = new MixDBOps(this); // repo represents the DB
        ArrayList<HashMap<String, String>> entryList = repoMix.getMixById(_Recipe_Id); // recipeList is the output of the SQL query
        Entry[] ent = new Entry[entryList.size()];

        for (int i = 0; i < entryList.size(); i++) {
            h = entryList.get(i);
            ent[i] = new Entry();
            ent[i].recipe_name = recipe.title;
            ent[i].ingredient_name = h.get("ingredient_name"); // temporarily replaced by spinner
            ent[i].quantity= Integer.parseInt(h.get("quantity"));
            ent[i].unit_name= h.get("unit_name");
            adapter.add(ent[i]);
        }

        btnEdit = (Button) findViewById(R.id.btnEdit);
        btnEdit.setOnClickListener(this);

        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(this);

        btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);

        btnCancel = (Button) findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(this);

        if (editMode == 1){
            setEditMode();
        }
    }
}

Is anybody able to help me?

Body:
add two attribute in each edit text of item of list view

    android:focusable="false"
    android:clickable="false"


答:
In urls.py, add a name to your each URL.

```<code>     path('profile/login', views.login, name='login')
</code>```

In template add this as href:

```<code>href="{% url 'login' %}"
</code>```

Title: Navbar dropdown menu href links not a working properly (Django+Bootstrap)

Body:
I am creating a small web application with using Django and Bootstrap4. In my Project Folder in Django, I have the templates and one of them is the base template. The other templates extend the base template. I have added the Bootstrap CDN to the base template and is working fine. I have created Bootstrap Navbar which get a dropdown when adjusted to screen size.

The issue is when I click a nav-link it adds the path in its href to the current path displayed in my browser i.e the location of the previous nav-link and searches for that. Hence it gives me an error. Upon clicking it should only take the path of only the clicked nav-link. My code is below. The href links are coming from my urls.py file. Please advise how to resolve this. Thanks.

base.html code

Body:
In urls.py, add a name to your each URL.

     path('profile/login', views.login, name='login')

In template add this as href:

href="{% url 'login' %}"


问:
Angular Routing not working when adding ID as a parameter in URL
new to Angular here. I have the following in my app.module.ts

```<code>RouterModule.forRoot()
{
...
      {
        path : "posts/:id",
        component: PostprofileComponent
      },
      {
        path : "posts",
        component: PostsComponent
      },
...
}
</code>```

The following is redirecting correctly to PostprofileComponent.

http://localhost:4200/posts/2

However this link does not... it redirects to PostsComponent.

http://localhost:4200/posts?id=2

Shouldn't they behave the same? What am i doing wrong?

答:
In your RouterModule:

```<code>RouterModule.forRoot()
{
...
    {
        path : "posts/details/:id",
        component: PostprofileComponent
    },
    {
        path : "posts/details",
        component: PostprofileComponent
    },
    {
        path : "posts",
        component: PostsComponent
    },
...
}
</code>```

Usage example using query params: (More info here)

this.router.navigate(['/posts/details'], { queryParams: { id: '2' } });

URL: http://localhost:4200/posts/details?id=2 return to => PostprofileComponent

Usage example using route params:

this.router.navigate(['/posts/details', '2']);

URL: http://localhost:4200/posts/details/2 return to => PostprofileComponent

then http://localhost:4200/posts return to => PostsComponent

Body:
new to Angular here. I have the following in my app.module.ts

RouterModule.forRoot()
{
...
      {
        path : "posts/:id",
        component: PostprofileComponent
      },
      {
        path : "posts",
        component: PostsComponent
      },
...
}

The following is redirecting correctly to PostprofileComponent.

http://localhost:4200/posts/2

However this link does not... it redirects to PostsComponent.

http://localhost:4200/posts?id=2

Shouldn't they behave the same? What am i doing wrong?

Body:
In your RouterModule:

RouterModule.forRoot()
{
...
    {
        path : "posts/details/:id",
        component: PostprofileComponent
    },
    {
        path : "posts/details",
        component: PostprofileComponent
    },
    {
        path : "posts",
        component: PostsComponent
    },
...
}

Usage example using query params: (More info here)

this.router.navigate(['/posts/details'], { queryParams: { id: '2' } });

URL: http://localhost:4200/posts/details?id=2 return to => PostprofileComponent

Usage example using route params:

this.router.navigate(['/posts/details', '2']);

URL: http://localhost:4200/posts/details/2 return to => PostprofileComponent

then http://localhost:4200/posts return to => PostsComponent


问:
Accept NaN as result of calculation with undefined
I got very attached to JavaScript’s way of handling undefined in calculations. For example:

```<code>function (a) {
    let c = a.b - 1;
    console.log(c || '');
}
</code>```

But I am now working on a TypeScript project with strict mode enabled. So, I tried this:

```<code>function (a:{b?:number}) {
    let c:number = a.b - 1;
    console.log(c || '');
}
</code>```

The compiler complains that a.b is “possibly undefined.” Well, I know that a.b will be undefined quite often. But I am also sure that I can deal with the resulting NaN for c.

What’s the most elegant solution here?

答:
A quick and dirty was is to tell the compiler a.b is not defined:

```<code>let c = a.b! - 1
</code>```

A slightly longer way is to add an undefined check into the calculation:

```<code>let c = a.b?a.b - 1:undefined
</code>```

Body:
I got very attached to JavaScript’s way of handling undefined in calculations. For example:

function (a) {
    let c = a.b - 1;
    console.log(c || '');
}

But I am now working on a TypeScript project with strict mode enabled. So, I tried this:

function (a:{b?:number}) {
    let c:number = a.b - 1;
    console.log(c || '');
}

The compiler complains that a.b is “possibly undefined.” Well, I know that a.b will be undefined quite often. But I am also sure that I can deal with the resulting NaN for c.

What’s the most elegant solution here?

Body:
A quick and dirty was is to tell the compiler a.b is not defined:

let c = a.b! - 1

A slightly longer way is to add an undefined check into the calculation:

let c = a.b?a.b - 1:undefined