问:
Python requirements conflict with PyPi
I have a project that needs some DevOps TLC, so I am finally building my installation script. This will eventually be a package that will be install-able by pip locally, but may not end up in PyPI.

It has a dependency for a module called u2py. It is this package, created for U2 Database operations, not this package, for... something else. The one I want is only ever installed by a 3rd party vendor (Rocket), the one I don't want is in PyPI.

What should be the expected behavior of my package in this case? I will include a blurb about this in my readme doc, but is that sufficient?

I've thought about throwing an exception to identify when the wrong package is present, but that makes me feel weird. It seems that maybe the most pythonic thing is to NOT add this to my install script, and blindly assume import u2py results in a module I can use. If it quacks like a duck, parses DynArrays like a duck, and call()s SUBROUTINEs like a duck, then it's a duck, right? Otherwise, if there is an error the user will just go and actually read the docs.

I've looked a classifiers, but not sure if they apply here.

答:
It's a case where it would be nice if Python projects had namespaces (pip install com.rocket.u2py and import com.rocket.u2py as u2py).

From my point of view there are 2 aspects to consider: at the project level, at the package level.

1. project (distribution package)

I believe it is a bad practice to force alternative download sources onto the end user of your project. By default, pip should download from PyPI and nowhere else, unless the user decides it themselves (via --find-links or similar options, which you could instruct your users to do in your documentation).

Since it is such a niche dependency, I think I would simply not add it to install_requires. I would assume the end users of your project know about the dependency already and are able to install it themselves directly.

Also I don't believe it is possible to check reliably at install-time if the correct dependency is installed, since setup.py does not always run (overriding the bdist_wheel command can help, but probably not 100% effective).

2. package (importable package)

I am not sure some specific action is needed. The code would most likely fail sooner or later naturally, because of module or function is not importable. Which might be okay-ish, maybe?

But probably detecting if the dependency is installed (and it is the correct one), is relatively easy and would provide a better user experience. Either check that some specific modules or functions are importable. Or inspect the meta-data (import importlib_metadata; importlib_metadata.distribution('u2py').metadata['Author']).

In case of an application, I would try to fail gracefully as soon as possible. In case of a library I would try to find one strategic spot to place the check and raise a custom exception (CannotFindU2pyException).

Links:

Prevent pip from caching a package

https://docs.python.org/3/library/importlib.metadata.html#distribution-metadata

https://github.com/pypa/pip/issues/4187#issuecomment-415067034

Equivalent for `--find-links` in `setup.py`

Title: Python requirements conflict with PyPi


来源: stackexchange

问:
when I use the dialog to show a new page, it can be used only once and always show the same thing in the page
Hello this is the first time I'm using dialog. Here is my code:

```<code>       $("#dialog").dialog({
        autoOpen: false,
        closeOnWscape: true,
        show: "blind",
        width: 800,
        buttons: {
            close: function () {
                alert("close");
                $(this).dialog("close");

            }
        }

    });

    $('p#pp').click(function () {

        //jQuery('#fpoint').dialog();
        //$("#dialog").load("Agrandir.aspx").dialog("open");
        //var tid = $("#Label1").text.toString();
        alert("open");
        //$("#fpoint").dialog("open");
        $("#dialog").load("Agrandir.aspx).dialog("open");
        //  window.open("Agrandir.aspx");
    })
</code>```

In the dialog will show a new page, in the page will show an execl. In the parent page there is an dropdownlist, when the button click this.session["id"] will get the value of the selected value, the Agrandir.aspx will use the session. Then click to open a dialog. But the dialog alway shows the same dialog which is created at the first time.

答:
Place this script on your pages to prevent jQuery ajax calls from caching their responses.

```<code>$(function() {
   $.ajaxSetup({ cache: false });
});
</code>```

jquery.load() will cache responses without it.

See this for more information.

ContentLicense: CC BY-SA 3.0

Body:
Hello this is the first time I'm using dialog. Here is my code:

       $("#dialog").dialog({
        autoOpen: false,
        closeOnWscape: true,
        show: "blind",
        width: 800,
        buttons: {
            close: function () {
                alert("close");
                $(this).dialog("close");

            }
        }

    });

    $('p#pp').click(function () {

        //jQuery('#fpoint').dialog();
        //$("#dialog").load("Agrandir.aspx").dialog("open");
        //var tid = $("#Label1").text.toString();
        alert("open");
        //$("#fpoint").dialog("open");
        $("#dialog").load("Agrandir.aspx).dialog("open");
        //  window.open("Agrandir.aspx");
    })

In the dialog will show a new page, in the page will show an execl. In the parent page there is an dropdownlist, when the button click this.session["id"] will get the value of the selected value, the Agrandir.aspx will use the session. Then click to open a dialog. But the dialog alway shows the same dialog which is created at the first time.

Body:
Place this script on your pages to prevent jQuery ajax calls from caching their responses.

$(function() {
   $.ajaxSetup({ cache: false });
});

jquery.load() will cache responses without it.

See this for more information.


问:
How to find the longest chain of consecutively recurring character groupings in file
I'm new to this site (and programming) but would really appreciate some help with a challenge I'm having.

I'm trying to write a program to search through a provided long .txt file and look for instances where a particular grouping of characters is repeating consecutively, then calculate the highest example of that and compare it with another file (this isn't important right now).

So with a file with the following long line:

'dtcdtcdtcuiouiouiodtcdtcdtcdtcdtcuiouioiodtcdtc'

I would want to find the highest instance of 'dtc' repeated consecutively. At the start of the line, it does so three times. Then around the middle it does so four times. Then at the end it does so twice. So I would want my stored information to be 4.

I'm struggling to implement this, however. As I said, I am new and have been trying to search for the best way to achieve this. I have so far started to consider options like:

```<code>read = textfile.read()
counter = 0

for i in range(len(read)):
        if (read[i:i + 2]) == 'dtc':
           counter += 1
</code>```

But yeah, I'm struggling to figure out the best way to implement the required algorithm. If you could even point me in the right direction, I would be grateful.

Many thanks

答:
I'm not sure if it's more efficient or not, but you could use a regular expression:

```<code>s = open('file.txt').read()
found = re.findall(r'((dtc)+)', s, re.MULTILINE)
found.sort(key=lambda x: x[0])
biggest = found.pop()[0]
</code>```

Otherwise, there isn't much you can do other than a more elegant looking version of what you have.

ContentLicense: CC BY-SA 4.0

Body:
I'm new to this site (and programming) but would really appreciate some help with a challenge I'm having.

I'm trying to write a program to search through a provided long .txt file and look for instances where a particular grouping of characters is repeating consecutively, then calculate the highest example of that and compare it with another file (this isn't important right now).

So with a file with the following long line:

'dtcdtcdtcuiouiouiodtcdtcdtcdtcdtcuiouioiodtcdtc'

I would want to find the highest instance of 'dtc' repeated consecutively. At the start of the line, it does so three times. Then around the middle it does so four times. Then at the end it does so twice. So I would want my stored information to be 4.

I'm struggling to implement this, however. As I said, I am new and have been trying to search for the best way to achieve this. I have so far started to consider options like:

read = textfile.read()
counter = 0

for i in range(len(read)):
        if (read[i:i + 2]) == 'dtc':
           counter += 1

But yeah, I'm struggling to figure out the best way to implement the required algorithm. If you could even point me in the right direction, I would be grateful.

Many thanks

Body:
I'm not sure if it's more efficient or not, but you could use a regular expression:

s = open('file.txt').read()
found = re.findall(r'((dtc)+)', s, re.MULTILINE)
found.sort(key=lambda x: x[0])
biggest = found.pop()[0]

Otherwise, there isn't much you can do other than a more elegant looking version of what you have.


问:
Getting ORA-00918: column ambiguously defined error which try to open django admin page after upgrading to django 3.03 from 2.0
Getting django.db.utils.DatabaseError: ORA-00918: column ambiguously defined error when I try to open Django admin page. Here is the error:

raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/venomscribe/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/venomscribe/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 514, in execute
    return self.cursor.execute(query, self._param_generator(params))
django.db.utils.DatabaseError: ORA-00918: column ambiguously defined

Query is

```<code>SELECT "DJANGO_ADMIN_LOG"."ID",
       "DJANGO_ADMIN_LOG"."ACTION_TIME",
       "DJANGO_ADMIN_LOG"."USER_ID",
       "DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID",
       "DJANGO_ADMIN_LOG"."OBJECT_ID",
       "DJANGO_ADMIN_LOG"."OBJECT_REPR",
       "DJANGO_ADMIN_LOG"."ACTION_FLAG",
       "DJANGO_ADMIN_LOG"."CHANGE_MESSAGE",
       "AUTH_USER"."ID",
       "AUTH_USER"."PASSWORD",
       "AUTH_USER"."LAST_LOGIN",
       "AUTH_USER"."IS_SUPERUSER",
       "AUTH_USER"."USERNAME",
       "AUTH_USER"."FIRST_NAME",
       "AUTH_USER"."LAST_NAME",
       "AUTH_USER"."EMAIL",
       "AUTH_USER"."IS_STAFF",
       "AUTH_USER"."IS_ACTIVE",
       "AUTH_USER"."DATE_JOINED",
       "DJANGO_CONTENT_TYPE"."ID",
       "DJANGO_CONTENT_TYPE"."APP_LABEL",
       "DJANGO_CONTENT_TYPE"."MODEL"
  FROM "DJANGO_ADMIN_LOG"
  INNER JOIN "AUTH_USER"
    ON ("DJANGO_ADMIN_LOG"."USER_ID" = "AUTH_USER"."ID")
  LEFT OUTER JOIN "DJANGO_CONTENT_TYPE"
    ON ("DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID" = "DJANGO_CONTENT_TYPE"."ID")
  WHERE "DJANGO_ADMIN_LOG"."USER_ID" = :arg0
  ORDER BY "DJANGO_ADMIN_LOG"."ACTION_TIME" DESC
  FETCH FIRST 10 ROWS ONLY
</code>```

答: It was system requirement issue. I was using oracle 12.1 which is not compatible with django 3.0.3. Downgrading to 2.2 resolved the issue. </p>

Body:
Getting django.db.utils.DatabaseError: ORA-00918: column ambiguously defined error when I try to open Django admin page. Here is the error:

raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/venomscribe/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/venomscribe/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 514, in execute
    return self.cursor.execute(query, self._param_generator(params))
django.db.utils.DatabaseError: ORA-00918: column ambiguously defined

Query is

SELECT "DJANGO_ADMIN_LOG"."ID",
       "DJANGO_ADMIN_LOG"."ACTION_TIME",
       "DJANGO_ADMIN_LOG"."USER_ID",
       "DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID",
       "DJANGO_ADMIN_LOG"."OBJECT_ID",
       "DJANGO_ADMIN_LOG"."OBJECT_REPR",
       "DJANGO_ADMIN_LOG"."ACTION_FLAG",
       "DJANGO_ADMIN_LOG"."CHANGE_MESSAGE",
       "AUTH_USER"."ID",
       "AUTH_USER"."PASSWORD",
       "AUTH_USER"."LAST_LOGIN",
       "AUTH_USER"."IS_SUPERUSER",
       "AUTH_USER"."USERNAME",
       "AUTH_USER"."FIRST_NAME",
       "AUTH_USER"."LAST_NAME",
       "AUTH_USER"."EMAIL",
       "AUTH_USER"."IS_STAFF",
       "AUTH_USER"."IS_ACTIVE",
       "AUTH_USER"."DATE_JOINED",
       "DJANGO_CONTENT_TYPE"."ID",
       "DJANGO_CONTENT_TYPE"."APP_LABEL",
       "DJANGO_CONTENT_TYPE"."MODEL"
  FROM "DJANGO_ADMIN_LOG"
  INNER JOIN "AUTH_USER"
    ON ("DJANGO_ADMIN_LOG"."USER_ID" = "AUTH_USER"."ID")
  LEFT OUTER JOIN "DJANGO_CONTENT_TYPE"
    ON ("DJANGO_ADMIN_LOG"."CONTENT_TYPE_ID" = "DJANGO_CONTENT_TYPE"."ID")
  WHERE "DJANGO_ADMIN_LOG"."USER_ID" = :arg0
  ORDER BY "DJANGO_ADMIN_LOG"."ACTION_TIME" DESC
  FETCH FIRST 10 ROWS ONLY


问:
Python requests hangs whereas CURL doesn't (same request)
I'm getting a permanent hang when trying to read a response using requests to access a particular site, most likely due to blocking of some sort. What I'm unsure about is how CURL, which is successfully receiving a response, is different to my Python get request which never receives any response.

Note: the curl command is expected to return an error as i'm not sending required info like cookies
curl:

```<code>curl 'https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'
</code>```

successfully gets response

Python:

```<code>import requests
r = requests.get('https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'})
</code>```

hangs on read forever

答:
There maybe subtle differences in the ways requests are made. For example Python requests will automatically add a few headers:

'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'

(You can see them by executing: r.request.headers)

Whereas Curl will add: Accept: */* but not gzip unless you ask for it. But the site in question seems to support gzip so the problem must lie elsewhere.

Suggestion: add a timeout in your request, and catch possible exceptions ie:

```<code>try:
    r = requests...

except requests.exceptions.RequestException as e:
    print (e)
</code>```

Body:
I'm getting a permanent hang when trying to read a response using requests to access a particular site, most likely due to blocking of some sort. What I'm unsure about is how CURL, which is successfully receiving a response, is different to my Python get request which never receives any response.

Note: the curl command is expected to return an error as i'm not sending required info like cookies
curl:

curl 'https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'

successfully gets response

Python:

import requests
r = requests.get('https://www.yellowpages.com.au/search/listings?clue=Programmer&locationClue=All+States&pageNumber=3&referredBy=UNKNOWN&&eventType=pagination', headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0'})

hangs on read forever

Body:
There maybe subtle differences in the ways requests are made. For example Python requests will automatically add a few headers:

'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'

(You can see them by executing: r.request.headers)

Whereas Curl will add: Accept: */* but not gzip unless you ask for it. But the site in question seems to support gzip so the problem must lie elsewhere.

Suggestion: add a timeout in your request, and catch possible exceptions ie:

try:
    r = requests...

except requests.exceptions.RequestException as e:
    print (e)


问:
Regular expression for youtube links
Does someone have a regular expression that gets a link to a Youtube video (not embedded object) from (almost) all the possible ways of linking to Youtube?

I think this is a pretty common problem and I'm sure there are a lot of ways to link that.

A starting point would be:

http://www.youtube.com/watch?v=iwGFalTRHDA

http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related

http://youtu.be/iwGFalTRHDA

http://youtu.be/n17B_uFF4cA

http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4

http://www.youtube.com/watch?v=t-ZRX8984sc

http://youtu.be/t-ZRX8984sc

... please add more possible links and/or regular expressions to detect them.

答:
Youtube video URL Change to iframe supported link:

REGEX: https://regex101.com/r/LeZ9WH/2/

```<code>http://www.youtube.com/watch?v=iwGFalTRHDA
http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
http://youtu.be/iwGFalTRHDA
http://youtu.be/n17B_uFF4cA
http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
http://www.youtube.com/watch?v=t-ZRX8984sc
http://youtu.be/t-ZRX8984sc
https://youtu.be/2sFlFPmUfNo?t=1
</code>```

Php function example:

```<code>if (!function_exists('clean_youtube_link')) {

        /**
         * @param $link
         * @return string|string[]|null
         */
        function clean_youtube_link($link)
        {
            return preg_replace(
                '#(.+?)(\/)(watch\x3Fv=)?(embed\/watch\x3Ffeature\=player_embedded\x26v=)?([a-zA-Z0-9_-]{11})+#',
                "https://www.youtube.com/embed/$5",
                $link
            );
        }
}
</code>```

Title: Regular expression for youtube links

Body:
Youtube video URL Change to iframe supported link:

REGEX: https://regex101.com/r/LeZ9WH/2/

http://www.youtube.com/watch?v=iwGFalTRHDA
http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
http://youtu.be/iwGFalTRHDA
http://youtu.be/n17B_uFF4cA
http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
http://www.youtube.com/watch?v=t-ZRX8984sc
http://youtu.be/t-ZRX8984sc
https://youtu.be/2sFlFPmUfNo?t=1

Php function example:

if (!function_exists('clean_youtube_link')) {

        /**
         * @param $link
         * @return string|string[]|null
         */
        function clean_youtube_link($link)
        {
            return preg_replace(
                '#(.+?)(\/)(watch\x3Fv=)?(embed\/watch\x3Ffeature\=player_embedded\x26v=)?([a-zA-Z0-9_-]{11})+#',
                "https://www.youtube.com/embed/$5",
                $link
            );
        }
}


问:
Transpose and change position in data set in (Python 3 and Pandas)
I am trying to switch the cell positions of large data set by using pandas
as picture shows

snapshot of the data set

the data as follow at csv file:

```<code>Trace  event
1         Triage
1         Register
1         Check
1         X-Ray
1         Visit
1         Check
1         Final Visit
1         Check
1         Prepare
10        Triage
10        Register
10        Visit
10        Check
10        X-Ray
10        Check
10        Final Visit
10        Prepare
10        Check
..         .
..         .
..         .
..         .

</code>```

and, I want them like this format

```<code>
trace     event
1         Triage  Register  Check  X-Ray  Visit  Check  Final Visit  Check  Prepare
10        Triage  Register  Visit  Check  X-Ray  Check  Final Visit  Prepare  Check
..        ..      ..        ..     ..     ..     ..    ..          ..

</code>```

and so on
Thus, if any one has suggestion as function or for loop I will appreciated.

Thanks all

答:
Try:

df["events"]=df.groupby("trace")["event"].cumcount().add(1)
df=df.pivot(index="trace", columns="events", values="event")
df.columns=[f"event{col}" for col in df.columns]
```

It will put events into consecutive columns event1, event2, event3, ...

Body:
I am trying to switch the cell positions of large data set by using pandas
as picture shows

snapshot of the data set

the data as follow at csv file:

Trace  event
1         Triage
1         Register
1         Check
1         X-Ray
1         Visit
1         Check
1         Final Visit
1         Check
1         Prepare
10        Triage
10        Register
10        Visit
10        Check
10        X-Ray
10        Check
10        Final Visit
10        Prepare
10        Check
..         .
..         .
..         .
..         .

and, I want them like this format

trace     event
1         Triage  Register  Check  X-Ray  Visit  Check  Final Visit  Check  Prepare
10        Triage  Register  Visit  Check  X-Ray  Check  Final Visit  Prepare  Check
..        ..      ..        ..     ..     ..     ..    ..          ..

and so on
Thus, if any one has suggestion as function or for loop I will appreciated.

Thanks all

Body:
Try:

df["events"]=df.groupby("trace")["event"].cumcount().add(1)
df=df.pivot(index="trace", columns="events", values="event")
df.columns=[f"event{col}" for col in df.columns]

It will put events into consecutive columns event1, event2, event3, ...


问:
java.io.IOException: Cannot make changes to file
I am using JAudioTagger library for reading and writing tags for an audio file. I am able to read the tags but unable to write them.

I am retrieving audio file path like this :

```<code> private String getSongPath(long songId) {
        String path = null;
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Audio.Media.DATA};
        String selection = MediaStore.Audio.Media._ID + " == ?";
        String[] selectionArgs = {String.valueOf(songId)};

        Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);

        if (cursor != null) {
            int pathCol = cursor.getColumnIndexOrThrow(projection[0]);
            cursor.moveToFirst();
            path = cursor.getString(pathCol);
            cursor.close();
        }

        return path;
    }
</code>```

Then to write tags using JAudioTagger :

```<code>File songFile = new File(path); // path looks like /storage/3932-3434/Music/xyz.mp3
AudioFile audiofile = = AudioFileIO.read(songFile);
Tag tag = = audiofile.getTag();
tag.setField(FieldKey.TITLE, title);
// some more setField calls for different feilds
audiofile.commit();
</code>```

The commit() method is giving following Exception :

org.jaudiotagger.audio.exceptions.CannotWriteException:
  java.io.IOException: Cannot make changes to file xyz.mp3 at
  org.jaudiotagger.audio.mp3.MP3File.commit(MP3File.java:799) at
  com.techapps.musicplayerplus.MainActivity$17.onClick(MainActivity.java:2125)
  at
  android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
  at android.os.Handler.dispatchMessage(Handler.java:102)  at
  android.os.Looper.loop(Looper.java:148)  at
  android.app.ActivityThread.main(ActivityThread.java:5417) 06-18
  10:59:48.134 8802-8802/com.techapps.musicplayerplus W/System.err:

  at java.lang.reflect.Method.invoke(Native Method) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused
  by: java.io.IOException: Cannot make changes to file Saibo.mp3  at
  org.jaudiotagger.audio.mp3.MP3File.precheck(MP3File.java:824)  at
  org.jaudiotagger.audio.mp3.MP3File.save(MP3File.java:850) at
  org.jaudiotagger.audio.mp3.MP3File.save(MP3File.java:783) at
  org.jaudiotagger.audio.mp3.MP3File.commit(MP3File.java:795)

I am running this code on Android 6 while my app is targeted at SDK 22. I have also mentioned following permission in manifest.

android.permission.WRITE_EXTERNAL_STORAGE

Still I am unable to write to SD card. Please help me. Thanks in advance.

答:
I saw that you already created an issue in the JAudioTagger GitHub repository which was advisable, but never got a universally working solution. My findings so far:

The answer mentioning SAF is correct, but it won't help you as SAF will provide a DocumentFile, not a File.

You might try to modify JAudioTagger to your needs, replacing File with DocumentFile, but the latter one has not all functions you will need.

Also InputStream and OutputStream will not help you, as JAudioTagger needs File and internally heavily uses RandomAccessFile which is not available either.

Google "forgot" to provide some getRandomAccessFileFromUri() which makes things even worse (Yes, there are hacks using Java reflection to work around this limitation...).

The "/proc/self/fd" method (How to handle SAF when I can only handle File or file-path?) will also not work immediately, as JAudioTagger needs copy and renaming functions that are not applicable to this kind of files. Particularly JAudioTagger will not find a suitable file name extension like ".m4a". Of course you could try to change JAudioTagger accordingly.

You might follow the advice to make a copy of the file to your personal storage, then apply JAudioTagger to it and finally copy it back to SD card, but:

If you want to use JAudioTagger to read from SD card, this will, as announced by Google, fail with Android 10. Starting with that version, you will not even have read access to the SD card via the File interface.

Further, the File interface gives you read access to SD cards with Android 9 and below, but not to other SAF devices, like USB OTG memory or SMB shares etc.

Of course you could also copy each file in order to read its metadata, but this will be awfully slow and is not suitable if you have more than a few files.

So my current advices are:

Try the "/proc/self/fd" method and modify JAudioTagger accordingly.

If the changes are too heavy, use the fd method for reading the tags and the copy method for writing.

BTW: I am currently modifying an older version of JAudioTagger for using both File and DocumentFile transparently, but the changes are tremendous, bear a high risk, need some help classes, and the work is unfinished, yet.

BTSW: The DocumentFile functions are painfully slow, compared to the File functions.

Body:
I am using JAudioTagger library for reading and writing tags for an audio file. I am able to read the tags but unable to write them.

I am retrieving audio file path like this :

 private String getSongPath(long songId) {
        String path = null;
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Audio.Media.DATA};
        String selection = MediaStore.Audio.Media._ID + " == ?";
        String[] selectionArgs = {String.valueOf(songId)};

        Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, null);

        if (cursor != null) {
            int pathCol = cursor.getColumnIndexOrThrow(projection[0]);
            cursor.moveToFirst();
            path = cursor.getString(pathCol);
            cursor.close();
        }

        return path;
    }

Then to write tags using JAudioTagger :

File songFile = new File(path); // path looks like /storage/3932-3434/Music/xyz.mp3
AudioFile audiofile = = AudioFileIO.read(songFile);
Tag tag = = audiofile.getTag();
tag.setField(FieldKey.TITLE, title);
// some more setField calls for different feilds
audiofile.commit();

The commit() method is giving following Exception :

org.jaudiotagger.audio.exceptions.CannotWriteException:
  java.io.IOException: Cannot make changes to file xyz.mp3 at
  org.jaudiotagger.audio.mp3.MP3File.commit(MP3File.java:799) at
  com.techapps.musicplayerplus.MainActivity$17.onClick(MainActivity.java:2125)
  at
  android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
  at android.os.Handler.dispatchMessage(Handler.java:102)  at
  android.os.Looper.loop(Looper.java:148)  at
  android.app.ActivityThread.main(ActivityThread.java:5417) 06-18
  10:59:48.134 8802-8802/com.techapps.musicplayerplus W/System.err:

  at java.lang.reflect.Method.invoke(Native Method) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused
  by: java.io.IOException: Cannot make changes to file Saibo.mp3  at
  org.jaudiotagger.audio.mp3.MP3File.precheck(MP3File.java:824)  at
  org.jaudiotagger.audio.mp3.MP3File.save(MP3File.java:850) at
  org.jaudiotagger.audio.mp3.MP3File.save(MP3File.java:783) at
  org.jaudiotagger.audio.mp3.MP3File.commit(MP3File.java:795)

I am running this code on Android 6 while my app is targeted at SDK 22. I have also mentioned following permission in manifest.

android.permission.WRITE_EXTERNAL_STORAGE

Still I am unable to write to SD card. Please help me. Thanks in advance.


问:
ASP.NET Core Shared Cookie Issue
I have read the MS instructions and several threads here on SO.... and I am out of ideas. I have 2 .net core 3.0 web applications. I use Okta for identity management and want to be able to SSO between my apps - which all works just fine locally.

However, when I deploy it to my development environment in Azure, it doesn't work because the cookies written by site 1 can't be read by site 2. I thought, oh, of course, the solution is to just fix the cookie domain. But that didn't work either.

So here is where I am at:

Site one: dev-app.mysite.com
Site two: dev.mysite.com

If I don't explicitly set the cookie domain, site 1 will write the cookie with dev-app.mysite.com as the cookie.

If I do explicitly set the cookie domain to ".mysite.com" (per the documentaiton), then I have an even bigger problem - which is that site 1 can't see it at all!

Here is the relevant code (same in both apps)

```<code>            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
                options.Secure = CookieSecurePolicy.Always;
            });
</code>```

and where I setup the authentication cookie:

```<code>            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath = new PathString("/Account/SignIn");
                options.Cookie.Name = cookieName;
                options.Cookie.Domain = cookieDomain;
            })
            .AddOktaMvc(oktaMvcOptions);
</code>```

Note I already have taken care of the cookie application name, the shared data protection keys, etc. The only thing that is holding this up is whatever the domain problem is.

答:
This may be the strangest thing I have ever seen. I have found that if I do this, it works:

```<code>options.Cookie.Domain = "mydomain.com";
</code>```

However, if I put that very same value into appSettings.json and read it from there. The same exact value, it doesn't work.

I debugged it locally and discovered that somehow my variable:

```<code>                var cookieName = Configuration.GetValue<string>("SharedCookies:CookieName");

</code>```

which is declared right before the call here, goes out of scope where I am using it.... even though a variable I declared right next to it is totally fine. I have no clue how this is even possible, so I thought I'd try moving the declarations:

```<code>            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                var cookieDomain = Configuration.GetValue<string>("SharedCookies:CookieDomain");
                var cookieName = Configuration.GetValue<string>("SharedCookies:CookieName");

                options.LoginPath = new PathString("/Account/SignIn");
                options.Cookie.Name = cookieName;
                options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
                options.Cookie.Domain = cookieDomain;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            })
            .AddOktaMvc(oktaMvcOptions);

</code>```

And... nope, still does not work. The only way I can get it to work is to actually type the domain in directly. If I step through the code line by line I am setting it to the same exact value as that of the variable. This is so bizarre.

If anyone has any ideas on how this is possible, please let me know.

Title: ASP.NET Core Shared Cookie Issue

Body:
I have read the MS instructions and several threads here on SO.... and I am out of ideas. I have 2 .net core 3.0 web applications. I use Okta for identity management and want to be able to SSO between my apps - which all works just fine locally.

However, when I deploy it to my development environment in Azure, it doesn't work because the cookies written by site 1 can't be read by site 2. I thought, oh, of course, the solution is to just fix the cookie domain. But that didn't work either.

So here is where I am at:

Site one: dev-app.mysite.com
Site two: dev.mysite.com

If I don't explicitly set the cookie domain, site 1 will write the cookie with dev-app.mysite.com as the cookie.

If I do explicitly set the cookie domain to ".mysite.com" (per the documentaiton), then I have an even bigger problem - which is that site 1 can't see it at all!

Here is the relevant code (same in both apps)

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
                options.Secure = CookieSecurePolicy.Always;
            });

and where I setup the authentication cookie:

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath = new PathString("/Account/SignIn");
                options.Cookie.Name = cookieName;
                options.Cookie.Domain = cookieDomain;
            })
            .AddOktaMvc(oktaMvcOptions);

Note I already have taken care of the cookie application name, the shared data protection keys, etc. The only thing that is holding this up is whatever the domain problem is.

Body:
This may be the strangest thing I have ever seen. I have found that if I do this, it works:

options.Cookie.Domain = "mydomain.com";

However, if I put that very same value into appSettings.json and read it from there. The same exact value, it doesn't work.

I debugged it locally and discovered that somehow my variable:

                var cookieName = Configuration.GetValue<string>("SharedCookies:CookieName");

which is declared right before the call here, goes out of scope where I am using it.... even though a variable I declared right next to it is totally fine. I have no clue how this is even possible, so I thought I'd try moving the declarations:

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                var cookieDomain = Configuration.GetValue<string>("SharedCookies:CookieDomain");
                var cookieName = Configuration.GetValue<string>("SharedCookies:CookieName");

                options.LoginPath = new PathString("/Account/SignIn");
                options.Cookie.Name = cookieName;
                options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
                options.Cookie.Domain = cookieDomain;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            })
            .AddOktaMvc(oktaMvcOptions);

And... nope, still does not work. The only way I can get it to work is to actually type the domain in directly. If I step through the code line by line I am setting it to the same exact value as that of the variable. This is so bizarre.

If anyone has any ideas on how this is possible, please let me know.


问:
is this possible to send parameters to binding events from xml views
I'm trying to use DataBinding in Android.
But i have a question in my mind.

I want to send edittext's text to binding functions inside xml.
I mean; When the login button is clicked, I want to get the current username and password from the xml IDs. Is it possible?

Here what I want:

```<code>android:onClick="@{() -> login.onLogin(login_edt_username.text, login_edt_password.text)}"
</code>```

My Current Usage:

Code:

```<code>@Override
protected void onStart() {
    super.onStart();
    binding= DataBindingUtil.setContentView(this,R.layout.activity_login);
}

@Override
public void onLogin() {
    login(binding.loginEdtUserName.getText(),binding.loginEdtPassword.getText());
}
</code>```

Xml:

```<code><layout>

<data>

    <variable
        name="login"
        type="interfaces.login.LoginInterface" />

</data>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.friends.LoginActivity">

    <EditText
        android:id="@+id/login_edt_user_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Username" />

    <EditText
        android:id="@+id/login_edt_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/login_edt_user_name"
        android:hint="Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/login_btn_sign_in"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="@{() -> login.onLogin()}"
        android:layout_below="@+id/login_edt_password"
        android:text="SIGN IN" />

    <Button
        android:id="@+id/login_btn_register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="@{() -> login.onRegister()}"
        android:layout_below="@+id/login_btn_sign_in"
        android:text="REGISTER" />

</RelativeLayout>
</code>```

Thanks in advance.

答:
There's some conflict when +id uses the "login_edt_user_name" format. Make sure identifiers use camelCase so they can be properly accessed:

Correct:

android:onClick="@{() -> login.onLogin(loginEdtUserName.getText(), loginEdtPassword.getText())}"

Wrong:

android:onClick="@{() -> login.onLogin(login_edt_user_name.getText(), login_edt_password.getText())}"

Body:
I'm trying to use DataBinding in Android.
But i have a question in my mind.

I want to send edittext's text to binding functions inside xml.
I mean; When the login button is clicked, I want to get the current username and password from the xml IDs. Is it possible?

Here what I want:

android:onClick="@{() -> login.onLogin(login_edt_username.text, login_edt_password.text)}"

My Current Usage:

Code:

@Override
protected void onStart() {
    super.onStart();
    binding= DataBindingUtil.setContentView(this,R.layout.activity_login);
}

@Override
public void onLogin() {
    login(binding.loginEdtUserName.getText(),binding.loginEdtPassword.getText());
}

Xml:

<layout>

<data>

    <variable
        name="login"
        type="interfaces.login.LoginInterface" />

</data>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.friends.LoginActivity">

    <EditText
        android:id="@+id/login_edt_user_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Username" />

    <EditText
        android:id="@+id/login_edt_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/login_edt_user_name"
        android:hint="Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/login_btn_sign_in"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="@{() -> login.onLogin()}"
        android:layout_below="@+id/login_edt_password"
        android:text="SIGN IN" />

    <Button
        android:id="@+id/login_btn_register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="@{() -> login.onRegister()}"
        android:layout_below="@+id/login_btn_sign_in"
        android:text="REGISTER" />

</RelativeLayout>

Thanks in advance.


问:
In a blazor app, is it possible to get the requested path, if the render mode is set to "server"?
I created a Blazor client app and and within this app I have a number of authorization policies with custom requirements and handlers. One of them checks the ID requested in the URL and checks whether the logged in user can view this resource.

For example, through the client, the user navigates to https://localhost/resource/1f28e41c-bc75-44d6-9eef-d46b66b649c7   which is a resource on my API.

I’m using the following code to see the request path:

```<code>var httpContext = _httpContextAccessor.HttpContext;
string requestedPath = httpContext.Request.Path.ToString();
</code>```

This used to work and requestedPath would indeed contain the value “1f28e41c-bc75-44d6-9eef-d46b66b649c7”

However, in the _Host.cshtml I have changed the render mode from "ServerPrerendered" to "Server". This was due to the fact that the code was executed twice at different places during page invocation.

And since I changed this, the requestedPath value is always "/_blazor".

So I was wondering, in a blazor app, is it possible to get the requested path if the render mode is set to "server"?

答:
I created a Blazor client app

No you didn't. Your application is a Blazor Server App (also known as server-side Blazor app).

As your app is WebSocket-connection-based, and not HTTP-based, you cannot and should not try to access the HttpContext object. HttpContext does not exist in SignalR-based application like the one you use (Blazor Server App).

The following code snippet creates a Razor Component named Profile, with a parameter (route value) named ID, which you should pass to your IAuthorizationHandler

Profile.razor

```<code>@page "/profile"
@page "/profile/{id}"

 <AuthorizeView Policy="Place here the name of your policy"
                                                Resource="@ID">
      <NotAuthorized>
        <h2 class="mt-5">You are not authorized to view this page</h2>
      </NotAuthorized>
      <Authorized>
        <div class="container my-profile">
            <h2>My Profile</h2>
            --- Place here all the content you want your user to view ----
        </div>
      </Authorized>
</AuthorizeView>

@code {

   [Parameter]
   public string ID { get; set; }
</code>```

}

Note to remember: The profile ID is passed to your handler method through the AuthorizeView.Resource attribute

And in the handler method you can do something like this:

```<code> public Task HandleAsync(AuthorizationHandlerContext context)
    {
        if (context == null) return Task.CompletedTask;

        // get the profile id from resource, passed in from the profile page
        // component
        var resource = context.Resource?.ToString();
        var hasParsed = int.TryParse(resource, out int profileID);
        if (hasParsed)
        {
            // compare the requested profileID to the user's actual claim of
            // profileID
            var isAuthorized = profileID == context.User.GetProfileIDClaim();
            -- --- I can't code blindly any more-----
        }

    }
</code>```

Hope this helps..

Body:
I created a Blazor client app and and within this app I have a number of authorization policies with custom requirements and handlers. One of them checks the ID requested in the URL and checks whether the logged in user can view this resource.

For example, through the client, the user navigates to https://localhost/resource/1f28e41c-bc75-44d6-9eef-d46b66b649c7   which is a resource on my API.

I’m using the following code to see the request path:

var httpContext = _httpContextAccessor.HttpContext;
string requestedPath = httpContext.Request.Path.ToString();

This used to work and requestedPath would indeed contain the value “1f28e41c-bc75-44d6-9eef-d46b66b649c7”

However, in the _Host.cshtml I have changed the render mode from "ServerPrerendered" to "Server". This was due to the fact that the code was executed twice at different places during page invocation.

And since I changed this, the requestedPath value is always "/_blazor".

So I was wondering, in a blazor app, is it possible to get the requested path if the render mode is set to "server"?

Body:
I created a Blazor client app

No you didn't. Your application is a Blazor Server App (also known as server-side Blazor app).

As your app is WebSocket-connection-based, and not HTTP-based, you cannot and should not try to access the HttpContext object. HttpContext does not exist in SignalR-based application like the one you use (Blazor Server App).

The following code snippet creates a Razor Component named Profile, with a parameter (route value) named ID, which you should pass to your IAuthorizationHandler

Profile.razor

@page "/profile"
@page "/profile/{id}"

 <AuthorizeView Policy="Place here the name of your policy"
                                                Resource="@ID">
      <NotAuthorized>
        <h2 class="mt-5">You are not authorized to view this page</h2>
      </NotAuthorized>
      <Authorized>
        <div class="container my-profile">
            <h2>My Profile</h2>
            --- Place here all the content you want your user to view ----
        </div>
      </Authorized>
</AuthorizeView>

@code {

   [Parameter]
   public string ID { get; set; }

}

Note to remember: The profile ID is passed to your handler method through the AuthorizeView.Resource attribute

And in the handler method you can do something like this:

 public Task HandleAsync(AuthorizationHandlerContext context)
    {
        if (context == null) return Task.CompletedTask;

        // get the profile id from resource, passed in from the profile page
        // component
        var resource = context.Resource?.ToString();
        var hasParsed = int.TryParse(resource, out int profileID);
        if (hasParsed)
        {
            // compare the requested profileID to the user's actual claim of
            // profileID
            var isAuthorized = profileID == context.User.GetProfileIDClaim();
            -- --- I can't code blindly any more-----
        }

    }

Hope this helps..


问:
Android: how to open a Google Map?
I have an activity which extends MapActivity. After running the activity, the Google Map should be shown on the emulator.
How can I do that?</p>

答:
http://www.vogella.de/articles/AndroidLocationAPI/article.html#overview_maps

This link got what u need.

i did it. and it works for me as well..

Just move to the 4th topic from the Index. (Google Maps)

Thanks

UPDATED:

Menifest File:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.locationapi.maps" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".ShowMap" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <uses-library android:required="true" android:name="com.google.android.maps"></uses-library>

</application>
</code>```

XML LayoutFile:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<com.google.android.maps.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="Your Maps API Key"
/>

</RelativeLayout>
</code>```

ACtivity:

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class ShowMap extends MapActivity {

```<code>private MapController mapController;
private MapView mapView;
private LocationManager locationManager;

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.main); // bind the layout to the activity

    // create a map view
    RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.setStreetView(true);
    mapController = mapView.getController();
    mapController.setZoom(14); // Zoon 1 is world view
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, new GeoUpdateHandler());
}

@Override
protected boolean isRouteDisplayed() {
    return false;
}

public class GeoUpdateHandler implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {
        int lat = (int) (location.getLatitude() * 1E6);
        int lng = (int) (location.getLongitude() * 1E6);
        GeoPoint point = new GeoPoint(lat, lng);
        mapController.animateTo(point); //  mapController.setCenter(point);
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}
}
</code>```

Title: Android: how to open a Google Map?

Body:
http://www.vogella.de/articles/AndroidLocationAPI/article.html#overview_maps

This link got what u need.

i did it. and it works for me as well..

Just move to the 4th topic from the Index. (Google Maps)

Thanks

UPDATED:

Menifest File:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.locationapi.maps" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".ShowMap" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <uses-library android:required="true" android:name="com.google.android.maps"></uses-library>

</application>

XML LayoutFile:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<com.google.android.maps.MapView
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="Your Maps API Key"
/>

</RelativeLayout>

ACtivity:

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class ShowMap extends MapActivity {

private MapController mapController;
private MapView mapView;
private LocationManager locationManager;

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.main); // bind the layout to the activity

    // create a map view
    RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
    mapView = (MapView) findViewById(R.id.mapview);
    mapView.setBuiltInZoomControls(true);
    mapView.setStreetView(true);
    mapController = mapView.getController();
    mapController.setZoom(14); // Zoon 1 is world view
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, new GeoUpdateHandler());
}

@Override
protected boolean isRouteDisplayed() {
    return false;
}

public class GeoUpdateHandler implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {
        int lat = (int) (location.getLatitude() * 1E6);
        int lng = (int) (location.getLongitude() * 1E6);
        GeoPoint point = new GeoPoint(lat, lng);
        mapController.animateTo(point); //  mapController.setCenter(point);
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}
}


问:
How can I add content to an existing JavaScript variable?
So I want to add content like a string or another variable to a variable that already exists. I know this isn't right, but this is what I have.</p>

```<code>var variable = "Variable";

function dispVar1() {
    let p = document.createElement("p");

    p.innerHTML = variable;
}

function dispVar2() {
    let p = document.createElement("p");
    let alteredVar = variable + " that has been altered";
    /* Also, could I do "" + variable to make string go before the variable? */

    p.innerHTML = alteredVar;
}
</code>```

```<code><input type="button" value="Original" onclick="dispVar1();">
<input type="button" value="Altered" onclick="dispVar2();">
</code>```

答:
You can simply use the + assignment operator to concatenate strings. You can see in the example I am creating a variable newValue that concats your original variable plus some additional text:

var variable = "Variable";
var targetEl = document.querySelector('#target');

function dispVar1() {
  target.innerHTML = '';
  let p = document.createElement("p");

  p.innerHTML = variable;
  target.appendChild(p);
}

function dispVar2() {
  target.innerHTML = '';
  let p = document.createElement("p");

  const newValue = variable + ' (here\'s some added text)';
  p.innerHTML = newValue;
  target.appendChild(p);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" value="Original" onclick="dispVar1();">
<input type="button" value="Altered" onclick="dispVar2();">
<div id="target"></div></code>```

Alternatively, you can take advantage of String.prototype.concat to achieve the same thing - but MDN doesn't recommend it:

It is strongly recommended that the assignment operators (+, +=) are
  used instead of the concat() method.

According to this performance test, the assignment operators are several times faster.

Body:
So I want to add content like a string or another variable to a variable that already exists. I know this isn't right, but this is what I have.

var variable = "Variable";

function dispVar1() {
    let p = document.createElement("p");

    p.innerHTML = variable;
}

function dispVar2() {
    let p = document.createElement("p");
    let alteredVar = variable + " that has been altered";
    /* Also, could I do "" + variable to make string go before the variable? */

    p.innerHTML = alteredVar;
}

<input type="button" value="Original" onclick="dispVar1();">
<input type="button" value="Altered" onclick="dispVar2();">

Body:
You can simply use the + assignment operator to concatenate strings. You can see in the example I am creating a variable newValue that concats your original variable plus some additional text:

var variable = "Variable";
var targetEl = document.querySelector('#target');

function dispVar1() {
  target.innerHTML = '';
  let p = document.createElement("p");

  p.innerHTML = variable;
  target.appendChild(p);
}

function dispVar2() {
  target.innerHTML = '';
  let p = document.createElement("p");

  const newValue = variable + ' (here\'s some added text)';
  p.innerHTML = newValue;
  target.appendChild(p);
}

<input type="button" value="Original" onclick="dispVar1();">
<input type="button" value="Altered" onclick="dispVar2();">
<div id="target"></div>

Alternatively, you can take advantage of String.prototype.concat to achieve the same thing - but MDN doesn't recommend it:

It is strongly recommended that the assignment operators (+, +=) are
  used instead of the concat() method.

According to this performance test, the assignment operators are several times faster.


问:
Getting rid of redundant 2D points without losing order
I have the following points:

```<code>import numpy as np
points = np.array([[49.8, 66.35],
 [49.79, 66.35],
 [49.79, 66.35],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.48, 67.24],
 [44.63, 67.21],
 [44.68, 67.2],
 [49.69, 66.21],
 [49.85, 66.17],
 [50.51, 66.04],
 [49.8, 66.35]])
</code>```

When I plot them, I get this shape:

```<code>import matplotlib.pyplot as plt
x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)
</code>```

As you can see from the list of points, some of them are redundant (i.e look at point 1 and 2 (starting at 0)).

To only keep the non-redundant points, I reverted to the answer from this question:
Removing duplicate columns and rows from a NumPy  2D array

```<code>def unique_2D(a):
    order = np.lexsort(a.T)
    a = a[order]
    diff = np.diff(a, axis=0)
    ui = np.ones(len(a), 'bool')
    ui[1:] = (diff != 0).any(axis=1)
    return a[ui]
</code>```

I apply this function to my points and I get:

```<code>non_redundant_points = unique_2D(points)
</code>```

Here is the printed list of retained points:

```<code>[[ 50.51  66.04]
 [ 49.85  66.17]
 [ 49.69  66.21]
 [ 49.79  66.35]
 [ 49.8   66.35]
 [ 44.68  67.2 ]
 [ 44.63  67.21]
 [ 44.48  67.24]
 [ 44.65  67.25]]
</code>```

However, now I face the following issue: When I plot them, the order is somehow not preserved...

```<code>x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)
</code>```

Do you know how I could solve this?

For easier copy and paste, here is the full code:

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

points = np.array([[49.8, 66.35],
 [49.79, 66.35],
 [49.79, 66.35],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.48, 67.24],
 [44.63, 67.21],
 [44.68, 67.2],
 [49.69, 66.21],
 [49.85, 66.17],
 [50.51, 66.04],
 [49.8, 66.35]])

x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)

def unique_2D(a):
        order = np.lexsort(a.T)
        a = a[order]
        diff = np.diff(a, axis=0)
        ui = np.ones(len(a), 'bool')
        ui[1:] = (diff != 0).any(axis=1)
        return a[ui]

x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)
</code>```

Body:
I have the following points:

import numpy as np
points = np.array([[49.8, 66.35],
 [49.79, 66.35],
 [49.79, 66.35],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.48, 67.24],
 [44.63, 67.21],
 [44.68, 67.2],
 [49.69, 66.21],
 [49.85, 66.17],
 [50.51, 66.04],
 [49.8, 66.35]])

When I plot them, I get this shape:

import matplotlib.pyplot as plt
x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)

As you can see from the list of points, some of them are redundant (i.e look at point 1 and 2 (starting at 0)).

To only keep the non-redundant points, I reverted to the answer from this question:
Removing duplicate columns and rows from a NumPy  2D array

def unique_2D(a):
    order = np.lexsort(a.T)
    a = a[order]
    diff = np.diff(a, axis=0)
    ui = np.ones(len(a), 'bool')
    ui[1:] = (diff != 0).any(axis=1)
    return a[ui]

I apply this function to my points and I get:

non_redundant_points = unique_2D(points)

Here is the printed list of retained points:

[[ 50.51  66.04]
 [ 49.85  66.17]
 [ 49.69  66.21]
 [ 49.79  66.35]
 [ 49.8   66.35]
 [ 44.68  67.2 ]
 [ 44.63  67.21]
 [ 44.48  67.24]
 [ 44.65  67.25]]

However, now I face the following issue: When I plot them, the order is somehow not preserved...

x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)

Do you know how I could solve this?

For easier copy and paste, here is the full code:

import numpy as np
import matplotlib.pyplot as plt

points = np.array([[49.8, 66.35],
 [49.79, 66.35],
 [49.79, 66.35],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.65, 67.25],
 [44.48, 67.24],
 [44.63, 67.21],
 [44.68, 67.2],
 [49.69, 66.21],
 [49.85, 66.17],
 [50.51, 66.04],
 [49.8, 66.35]])

x = [a[0] for a in points ]
y = [a[1] for a in points ]
plt.plot(x,y)

def unique_2D(a):
        order = np.lexsort(a.T)
        a = a[order]
        diff = np.diff(a, axis=0)
        ui = np.ones(len(a), 'bool')
        ui[1:] = (diff != 0).any(axis=1)
        return a[ui]

x_nr = [a[0] for a in non_redundant_points ]
y_nr = [a[1] for a in non_redundant_points ]
plt.plot(x_nr,y_nr)

Body:
You can keep track of what points already exist in a set that you've seen. To do this you can create a class that allows for hashing and comparing points:

In [93]: class Point:
...:     def __init__(self, x, y):
...:         self.x=x
...:         self.y=y
...:     def __hash__(self):
...:         return hash((self.x, self.y))
...:     def __eq__(self, other):
...:         return self.x == other.x and self.y == other.y
...:     def __str__(self):
...:         return f'({self.x}, {self.y})'
...:     def __repr__(self):
...:         return str(self)
...:

In [94]: points = [[49.8, 66.35],
...:  [49.79, 66.35],
...:  [49.79, 66.35],
...:  [44.65, 67.25],
...:  [44.65, 67.25],
...:  [44.65, 67.25],
...:  [44.48, 67.24],
...:  [44.63, 67.21],
...:  [44.68, 67.2],
...:  [49.69, 66.21],
...:  [49.85, 66.17],
...:  [50.51, 66.04],
...:  [49.8, 66.35]]

Now we can convert the points to an array of Point's

In [95]: points = [Point(*p) for p in points]
In [96]: points
Out[96]:
[(49.8, 66.35),
 (49.79, 66.35),
 (49.79, 66.35),
 (44.65, 67.25),
 (44.65, 67.25),
 (44.65, 67.25),
 (44.48, 67.24),
 (44.63, 67.21),
 (44.68, 67.2),
 (49.69, 66.21),
 (49.85, 66.17),
 (50.51, 66.04),
 (49.8, 66.35)]

All we need to do now is just loop through the points and add it to a unique list if we haven't seen it yet

In [102]: seen = set()

In [103]: new_points = []

In [104]: for point in points:
     ...:     if point not in seen:
     ...:         new_points.append(point)
     ...:         seen.add(point)
     ...:

In [105]: new_points
Out[105]:
[(49.8, 66.35),
 (49.79, 66.35),
 (44.65, 67.25),
 (44.48, 67.24),
 (44.63, 67.21),
 (44.68, 67.2),
 (49.69, 66.21),
 (49.85, 66.17),
 (50.51, 66.04)]

Now you have order maintained without repeating points.

EDIT: I think I misread part of the question. I think you just want to ignore sequential sets? As in, only repeating points immediately following another point, but if it's at the end then you want to keep it. If that's the case you can do:

In [114]: new_points = [points[0]]

In [115]: repeat = new_points[0]

In [116]: for point in points[1:]:
     ...:     # New point found, i.e. not a repeat from previous sequential set
     ...:     if point != repeat:
     ...:         repeat = point
     ...:         new_points.append(point)
     ...:

In [117]: new_points
Out[117]:
[(49.8, 66.35),
 (49.79, 66.35),
 (44.65, 67.25),
 (44.48, 67.24),
 (44.63, 67.21),
 (44.68, 67.2),
 (49.69, 66.21),
 (49.85, 66.17),
 (50.51, 66.04),
 (49.8, 66.35)]

And then to convert it for plotting:

points = np.array([[p.x, p.y] for p in new_points])
plt.plot(points[:,0], points[:,1])


问:
Can a Firebase Storage upload error result in a partial/corrupted file in storage?
Can a Firebase Storage upload error ever result in a partially-uploaded (or otherwise corrupted) file in cloud storage? Or does any error or inability to return metadata (after an attempted upload) guarantee that nothing was written to storage? I couldn't find anything in documentation.</p>

答: No, a partial upload will never be committed as an object in a storage bucket.  The upload must finish successfully, or fail completely.  A partial object would cause problems with downstream processing of that object, for example, in Cloud Functions triggers, security rules, or other parts of the system that rely on complete object data.  So that's simply not allowed.</p>


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
If the collection that is being returned is read-only, meaning you never want the elements to in the collection to be changed, then use IEnumerable<T>.  This is the most basic representation of a read-only sequence of immutable (at least from the perspective of the enumeration itself) elements.

If you want it to be a self-contained collection that can be changed, then use ICollection<T> or IList<T>.

For example, if you wanted to return the results of searching for a particular set of files, then return IEnumerable<FileInfo>.

However, if you wanted to expose the files in a directory, however, you would expose IList/ICollection<FileInfo> as it makes sense that you would want to possibly change the contents of the collection.

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: casperOne


问:
How to read NETCDF files in julia?
I am trying to open a netcdf file but I'm getting the following error:</p>

```<code>error compiling #Dataset#19: error compiling nc_open: could not load library "/Users/kanwal/.julia/conda/3/lib/libnetcdf.dylib"
dlopen(/Users/kanwal/.julia/conda/3/lib/libnetcdf.dylib, 1): image not found

Stacktrace:
 [1] Type at /Users/kanwal/.julia/packages/NCDatasets/uW2kc/src/NCDatasets.jl:482 [inlined] (repeats 2 times)
 [2] top-level scope at In[27]:1
</code>```

答:
Try installing libnetcdf to your Conda environment manually:

```<code>using Pkg
pkg"add Conda"
Conda.runconda(`install -c anaconda libnetcdf`)
</code>```

Title: How to read NETCDF files in julia?

Body:
I am trying to open a netcdf file but I'm getting the following error:

error compiling #Dataset#19: error compiling nc_open: could not load library "/Users/kanwal/.julia/conda/3/lib/libnetcdf.dylib"
dlopen(/Users/kanwal/.julia/conda/3/lib/libnetcdf.dylib, 1): image not found

Stacktrace:
 [1] Type at /Users/kanwal/.julia/packages/NCDatasets/uW2kc/src/NCDatasets.jl:482 [inlined] (repeats 2 times)
 [2] top-level scope at In[27]:1

Body:
Try installing libnetcdf to your Conda environment manually:

using Pkg
pkg"add Conda"
Conda.runconda(`install -c anaconda libnetcdf`)


答:
Your initial code works:

```<code>let alteredVar = variable + " that has been altered";
</code>```

An alternative using template literals with placeholders is more fashionable than concatenation because it removes the necessity of escaping certain characters, is more flexible, and arguably more readable:

```<code>let alteredVar = `${variable} that has been altered`;
</code>```

Title: How can I add content to an existing JavaScript variable?

Body:
Your initial code works:

let alteredVar = variable + " that has been altered";

An alternative using template literals with placeholders is more fashionable than concatenation because it removes the necessity of escaping certain characters, is more flexible, and arguably more readable:

let alteredVar = `${variable} that has been altered`;


问:
How to capture every SQL call made via .net Entity Framework 6.2
Looking to capture and log every calls to the DB made by entity framework. What's the best way of doing this? is that the best way https://www.entityframeworktutorial.net/entityframework6/database-command-interception.aspx ?

Thanks!

答:
You can capture it from the DB via the sys.processes</p>

```<code>    With AllJobsRan(SPID,LastBatch,SourceProgram,HostName,LoginCredentials, script)
    as (
    select
        P.spid
    ,   P.last_batch
    ,   P.program_name
    ,   P.hostname
    ,   P.loginame
    ,   sql_handle
    from master.dbo.sysprocesses P
    where
    --and      P.status not in ('background', 'sleeping')
    --and      P.cmd not in ('AWAITING COMMAND'
                        --,'MIRROR HANDLER'
                        --,'LAZY WRITER'
                        --,'CHECKPOINT SLEEP'
                        --,'RA MANAGER')
                        -- AND
                        p.last_batch > '2/17/2020'
                        AND p.last_batch < '2/18/2020'
    ),
    Scripts(byteScript)
    as (
        select script from AllJobsRan
    )
select
    AllJobsRan.SPID,
    AllJobsRan.LastBatch,
    AllJobsRan.HostName,
    AllJobsRan.LoginCredentials,
    LEN([SQLText].text) as [ScriptLength],
    [SQLText].text from AllJobsRan
CROSS APPLY
    sys.dm_exec_sql_text(AllJobsRan.[script]) as [SQLText]
order by
    LastBatch,[ScriptLength] desc
</code>```

Body:
You can capture it from the DB via the sys.processes

    With AllJobsRan(SPID,LastBatch,SourceProgram,HostName,LoginCredentials, script)
    as (
    select
        P.spid
    ,   P.last_batch
    ,   P.program_name
    ,   P.hostname
    ,   P.loginame
    ,   sql_handle
    from master.dbo.sysprocesses P
    where
    --and      P.status not in ('background', 'sleeping')
    --and      P.cmd not in ('AWAITING COMMAND'
                        --,'MIRROR HANDLER'
                        --,'LAZY WRITER'
                        --,'CHECKPOINT SLEEP'
                        --,'RA MANAGER')
                        -- AND
                        p.last_batch > '2/17/2020'
                        AND p.last_batch < '2/18/2020'
    ),
    Scripts(byteScript)
    as (
        select script from AllJobsRan
    )
select
    AllJobsRan.SPID,
    AllJobsRan.LastBatch,
    AllJobsRan.HostName,
    AllJobsRan.LoginCredentials,
    LEN([SQLText].text) as [ScriptLength],
    [SQLText].text from AllJobsRan
CROSS APPLY
    sys.dm_exec_sql_text(AllJobsRan.[script]) as [SQLText]
order by
    LastBatch,[ScriptLength] desc


问:
Does windows have same maximum path lengths (name of directory entry) for different filesystems it mounts?
I have to know if a specific vulnerablity in TCL 8.4 affects Windows platform

The vulnerability is: http://www.securityfocus.com/bid/15259/info
As per the link:

Operating systems with no difference in the maximum path lengths among differing file systems are not affected by this issue

I am using TCL on windows and want to know if this vulnerablity affects TCL on windows and how ?

Further, how can a person exploit this vulnerability on Windows ?

Thanks

答: While there exist common conventions regarding maximum file name and path length, certain file system drivers (or third-party file system implementations) might have their own limits which can be lower, than the commonly used ones. </p>


问:
How to display a div/element on mouse hover using external JavaScript?
My divs are nested so i understand i cant display an element if its already hidden. I want the information(p1 inside my html code)to display once the mouse hovers over another element(h1 in my html. I have already made my paragraph 1 style to none in JavaScript, now i need it to re-appear, i have tried the following code to attempt to make it re-appear document.getElementById("1").onmouseover.style.display = "block"; but with no success.

This is My HTML code, ignore the order im new to web dev lol

This is the code i have tried but it doesnt seem to work

This is the end result i want, the circled text on hover display the paragraph

答:
Yes, this is doable without javascript but since the question asked how to do it with, hopefully this helps get OP on the right track.

```<code>  <div id="bioBlock" style="display:none">
    <h2 id="1">
      Cameron Lodge
    </h2>
    <p1 id="para">Im an avid learner of anything computers....</p1>
  </div>

  function showBioBlock() {
    document.getElementById("bioBlock").style.display = "block";
  }
</code>```

https://jsfiddle.net/avL3j765/

Body:
Yes, this is doable without javascript but since the question asked how to do it with, hopefully this helps get OP on the right track.

  <div id="bioBlock" style="display:none">
    <h2 id="1">
      Cameron Lodge
    </h2>
    <p1 id="para">Im an avid learner of anything computers....</p1>
  </div>

  function showBioBlock() {
    document.getElementById("bioBlock").style.display = "block";
  }

https://jsfiddle.net/avL3j765/


问:
Open CV trivial circle detection -- how to get least squares instead of a contour?
My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv

This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitting is prioritizing matching the contour rather than something like a least squares approach.

I've alternatively averaged many fits in something like this:

My issue here is I like to quickly scan to make sure the circle fit is appropriate. The trade off is the more fits I have, the more realistic the fit, the fewer I have the easier is to make sure the number is correct. My circles aren't always as pretty and circular as this one so it's important to me.

Here's the piece of my script fitting circles if you could take a look and tell me how to do more of a least squares approach on the order of 5 circles. I don't want to use minimum circle detection because a fluid is flowing through this hole so I'd like it to be more like a hydraulic diameter-- thanks!

```<code>(thresh, blackAndWhiteImage0) = cv2.threshold(img0, 100, 255, cv2.THRESH_BINARY) #make black + white
median0 = cv2.medianBlur(blackAndWhiteImage0, 151) #get rid of noise
circles0 = cv2.HoughCircles(median0,cv2.HOUGH_GRADIENT,1,minDist=5,param1= 25, param2=10, minRadius=min_radius_small,maxRadius=max_radius_small) #fit circles to image
</code>```

答:
One suggestion I have is looking at cv2.fitEllipse()

Hopefully you can use the aspect ratio between ellipse witdth/height to tell the odd ones out.

Body:
My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv

This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitting is prioritizing matching the contour rather than something like a least squares approach.

I've alternatively averaged many fits in something like this:

My issue here is I like to quickly scan to make sure the circle fit is appropriate. The trade off is the more fits I have, the more realistic the fit, the fewer I have the easier is to make sure the number is correct. My circles aren't always as pretty and circular as this one so it's important to me.

Here's the piece of my script fitting circles if you could take a look and tell me how to do more of a least squares approach on the order of 5 circles. I don't want to use minimum circle detection because a fluid is flowing through this hole so I'd like it to be more like a hydraulic diameter-- thanks!

(thresh, blackAndWhiteImage0) = cv2.threshold(img0, 100, 255, cv2.THRESH_BINARY) #make black + white
median0 = cv2.medianBlur(blackAndWhiteImage0, 151) #get rid of noise
circles0 = cv2.HoughCircles(median0,cv2.HOUGH_GRADIENT,1,minDist=5,param1= 25, param2=10, minRadius=min_radius_small,maxRadius=max_radius_small) #fit circles to image


问:
What are the scopes to select in mapbox token access geocoding?
I am using WordPress to build my website. As part of the custom theme, I can choose Mapbox API for my location based search results. However, I am not entirely sure what "scope" to select when creating a token access. Attached is the screenshot. I am looking for the Mapbox Geocoding feature.

答:
All tokens are able to geocode locations, so you do not need to set a particular scope to use the Geocoding API.

Disclaimer - I work at Mapbox.


问:
Select distinct on one column and return all other columns
I'm trying to find distinct orders based on the modified date. I want to sort it and find the latest modified order.

I tried to do as in postgreSQL.
select distinct on (orders) * from the table;
But this throws an error in case of mariaDB

```<code>Orders          Modified Date
------          ---------------
23031185    2019-09-24 19:36:51
23031185    2019-09-24 22:01:57
23031185    2019-09-24 19:32:28
23031185    2019-09-24 19:33:25
23031185    2019-09-24 19:33:18

The expected output should be the latest one

Orders          Modified Date
------          ---------------
23031185    2019-09-24 22:01:57

</code>```

I also have other columns. I need to get all distinct rows based on orders column with all other columns.

答:
Is it simply</p>

```<code>SELECT  Orders,
        MAX(Modified Date) AS LatestDate
    FROM table
    GROUP BY Orders;
</code>```

Body:
I'm trying to find distinct orders based on the modified date. I want to sort it and find the latest modified order.

I tried to do as in postgreSQL.
select distinct on (orders) * from the table;
But this throws an error in case of mariaDB

Orders          Modified Date
------          ---------------
23031185    2019-09-24 19:36:51
23031185    2019-09-24 22:01:57
23031185    2019-09-24 19:32:28
23031185    2019-09-24 19:33:25
23031185    2019-09-24 19:33:18

The expected output should be the latest one

Orders          Modified Date
------          ---------------
23031185    2019-09-24 22:01:57

I also have other columns. I need to get all distinct rows based on orders column with all other columns.

Body:
Is it simply

SELECT  Orders,
        MAX(Modified Date) AS LatestDate
    FROM table
    GROUP BY Orders;


问:
C# How do i get the Right(String) based on one character?
I have this:

```<code>MyString = @"C:\\Somepath\otherpath\etc\string";
</code>```

And i need this string (which can be longer than a group of characters)

How can i do something like:

```<code>NewString = MyString.Right(string, when last "\" is found) ?
</code>```

答:
Depending on your environment, you might be able to use the new indices and range features that came with C# 8.0

```<code>var result = MyString.Split('\\')[^1];
</code>```

Indices and Ranges

Body:
I have this:

MyString = @"C:\\Somepath\otherpath\etc\string";

And i need this string (which can be longer than a group of characters)

How can i do something like:

NewString = MyString.Right(string, when last "\" is found) ?

Body:
Depending on your environment, you might be able to use the new indices and range features that came with C# 8.0

var result = MyString.Split('\\')[^1];

Indices and Ranges


问:
How to get text outside the div?
```<code><div class="amlocator-store-information" style="" xpath="1">
  <div class="amlocator-title" style="">The Better Health Store</div>
  2420 E-Stadium Ann Arbor MI 48104
  <br><br>
  (613) 975-6613
  <div style="" class="amasty_distance" id="amasty_distance_1">Distance:
    <span class="amasty_distance_number"></span>
  </div>
</div>
</code>```

I am using selenium with python and trying to get the address from the DOM but I can't,
I have used

```<code>store_block_list  = '//div[@class="amlocator-store-information"]'
store_block_list = '//div[@class="amlocator-title"]'
</code>```

to capture the elements but cant get the address out as you can see the address is outside the //div element
Please note it is a list of elements and I then use for loop to loop around the element list

答:
To extract the address i.e. 2420 E-Stadium Ann Arbor MI 48104 as it is a Text Node you need to induce WebDriverWait for the visibility_of_element_located() using execute_script() method and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>print(driver.execute_script('return arguments[0].childNodes[2].textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.amlocator-store-information")))).strip())
</code>```

Using XPATH:

```<code>print(driver.execute_script('return arguments[0].childNodes[2].textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='amlocator-store-information']")))).strip())
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Title: How to get text outside the div?

Body:
The Better Health Store

  2420 E-Stadium Ann Arbor MI 48104

  (613) 975-6613

Distance:

I am using selenium with python and trying to get the address from the DOM but I can't,
I have used

store_block_list  = '//div[@class="amlocator-store-information"]'
store_block_list = '//div[@class="amlocator-title"]'

to capture the elements but cant get the address out as you can see the address is outside the //div element
Please note it is a list of elements and I then use for loop to loop around the element list

Body:
To extract the address i.e. 2420 E-Stadium Ann Arbor MI 48104 as it is a Text Node you need to induce WebDriverWait for the visibility_of_element_located() using execute_script() method and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

print(driver.execute_script('return arguments[0].childNodes[2].textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.amlocator-store-information")))).strip())

Using XPATH:

print(driver.execute_script('return arguments[0].childNodes[2].textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='amlocator-store-information']")))).strip())

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
How do I change the name of an existing project in Visual Studio 2008?
How to change the name of a project in VS 2008 to something else? I have already created a project and now I want to change its name.</p>

答: Right mouse click the project and choose rename.</p>


问:
AsyncTask Android example
I was reading about AsyncTask, and I tried the simple program below. But it does not seem to work. How can I make it work?

```<code>public class AsyncTaskActivity extends Activity {

    Button btn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener) this);
    }

    public void onClick(View view){
        new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            for(int i=0;i<5;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}
</code>```

I am just trying to change the label after 5 seconds in the background process.

This is my main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="10dip">
    </ProgressBar>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" >
    </Button>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace"/>
</LinearLayout>
</code>```

答:
if you open AsyncTask class you can see below code.

```<code>public abstract class AsyncTask<Params, Progress, Result> {
    @WorkerThread
    protected abstract Result doInBackground(Params... params);
    @MainThread
    protected void onPreExecute() {
    }
    @SuppressWarnings({"UnusedDeclaration"})
    @MainThread
    protected void onPostExecute(Result result) {
    }
}
</code>```

AsyncTask features

AsyncTask is abstract class

AsyncTask is have 3 generic params.

AsyncTask has abstract method of doInBackground, onPreExecute, onPostExecute

doInBackground is WorkerThread (you can't update UI)

onPreExecute is MainThread

onPostExecute is MainThread (you can update UI)

example

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email);

    AsyncTask<Void, Void, Post> asyncTask = new AsyncTask<Void, Void, Post>() {
        @Override
        protected Post doInBackground(Void... params) {
            try {
                ApiClient defaultClient = Configuration.getDefaultApiClient();
                String authorization = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1ODIxMzM4MTB9.bA3Byc_SuB6jzqUGAY4Pyt4oBNg0VfDRctZ8-PcPlYg"; // String | JWT token for Authorization
                ApiKeyAuth Bearer = (ApiKeyAuth) defaultClient.getAuthentication("Bearer");
                Bearer.setApiKey(authorization);
                PostApi apiInstance = new PostApi();
                String id = "1"; // String | id
                Integer commentPage = 1; // Integer | Page number for Comment
                Integer commentPer = 10; // Integer | Per page number For Comment
                Post result;
                try {
                    result = apiInstance.apiV1PostsIdGet(id, authorization, commentPage, commentPer);
                } catch (ApiException e) {
                    e.printStackTrace();
                    result = new Post();
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                return new Post();
            }
        }

        @Override
        protected void onPostExecute(Post post) {
            super.onPostExecute(post);
            if (post != null) {
                mEmailView.setText(post.getBody());
                System.out.print(post);
            }
        }
    };
    asyncTask.execute();
}
</code>```

Title: AsyncTask Android example

Body:
I was reading about AsyncTask, and I tried the simple program below. But it does not seem to work. How can I make it work?

public class AsyncTaskActivity extends Activity {

    Button btn;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener((OnClickListener) this);
    }

    public void onClick(View view){
        new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            for(int i=0;i<5;i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText("Executed");
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }
}

I am just trying to change the label after 5 seconds in the background process.

This is my main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="vertical" >
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="10dip">
    </ProgressBar>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Progress" >
    </Button>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Replace"/>
</LinearLayout>

Body:
if you open AsyncTask class you can see below code.

public abstract class AsyncTask<Params, Progress, Result> {
    @WorkerThread
    protected abstract Result doInBackground(Params... params);
    @MainThread
    protected void onPreExecute() {
    }
    @SuppressWarnings({"UnusedDeclaration"})
    @MainThread
    protected void onPostExecute(Result result) {
    }
}

AsyncTask features

AsyncTask is abstract class

AsyncTask is have 3 generic params.

AsyncTask has abstract method of doInBackground, onPreExecute, onPostExecute

doInBackground is WorkerThread (you can't update UI)

onPreExecute is MainThread

onPostExecute is MainThread (you can update UI)

example

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    mEmailView = (AutoCompleteTextView) findViewById(R.id.email);

    AsyncTask<Void, Void, Post> asyncTask = new AsyncTask<Void, Void, Post>() {
        @Override
        protected Post doInBackground(Void... params) {
            try {
                ApiClient defaultClient = Configuration.getDefaultApiClient();
                String authorization = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1ODIxMzM4MTB9.bA3Byc_SuB6jzqUGAY4Pyt4oBNg0VfDRctZ8-PcPlYg"; // String | JWT token for Authorization
                ApiKeyAuth Bearer = (ApiKeyAuth) defaultClient.getAuthentication("Bearer");
                Bearer.setApiKey(authorization);
                PostApi apiInstance = new PostApi();
                String id = "1"; // String | id
                Integer commentPage = 1; // Integer | Page number for Comment
                Integer commentPer = 10; // Integer | Per page number For Comment
                Post result;
                try {
                    result = apiInstance.apiV1PostsIdGet(id, authorization, commentPage, commentPer);
                } catch (ApiException e) {
                    e.printStackTrace();
                    result = new Post();
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                return new Post();
            }
        }

        @Override
        protected void onPostExecute(Post post) {
            super.onPostExecute(post);
            if (post != null) {
                mEmailView.setText(post.getBody());
                System.out.print(post);
            }
        }
    };
    asyncTask.execute();
}


问:
Heroku: ! [rejected] master -> master (non-fast-forward)
I get and error whenever I try to push rails app to heroku. What do I do to fix this? I did git init, git add ., git commit -m "complete", and git push heroku master</p>

```<code>To https://git.heroku.com/shuabe.git
! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://git.heroku.com/james.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

答:
I fixed by:

```<code>git pull heroku master
</code>```

After that, console shows:

```<code>From https://git.heroku.com/myweb
 * branch            master     -> FETCH_HEAD
Auto-merging views/layout.hbs
CONFLICT (content): Merge conflict in views/layout.hbs
Auto-merging views/ads/list.hbs
Auto-merging controllers/users.controller.js
CONFLICT (content): Merge conflict in controllers/users.controller.js
Auto-merging config/db.config.js
CONFLICT (content): Merge conflict in config/db.config.js
Automatic merge failed; fix conflicts and then commit the result.
</code>```

I accepted every change, and after that:

```<code>git push heroku master
</code>```

Body:
I get and error whenever I try to push rails app to heroku. What do I do to fix this? I did git init, git add ., git commit -m "complete", and git push heroku master

To https://git.heroku.com/shuabe.git
! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://git.heroku.com/james.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Body:
I fixed by:

git pull heroku master

After that, console shows:

From https://git.heroku.com/myweb
 * branch            master     -> FETCH_HEAD
Auto-merging views/layout.hbs
CONFLICT (content): Merge conflict in views/layout.hbs
Auto-merging views/ads/list.hbs
Auto-merging controllers/users.controller.js
CONFLICT (content): Merge conflict in controllers/users.controller.js
Auto-merging config/db.config.js
CONFLICT (content): Merge conflict in config/db.config.js
Automatic merge failed; fix conflicts and then commit the result.

I accepted every change, and after that:

git push heroku master


问:
how to make $beforeValidate wait till async operation has completed
I want the $beforeValidate to wait for the async operation to complete as it updates the object to make it pass validation. But currently the $beforeValidate completes and rejects the record as it is not waiting for the async operation to complete.

```<code>class Label extends Model {
 async $beforeValidate() {
  if(this.name === undefined){
    const res = await axios.get('/getSomeName')
    console.log(res.body)
    this.name = res.body
  }
 }
 static get jsonSchema () {
    return {
      type: 'object',
      required: ['name'],
      properties: {
        id: { type: 'integer' },
        name: { type: 'string' }
      }
    }
 }
}

</code>```

Now when i insert a label with name undefined I can see that the validation error is raised before the async API call has even finished

```<code>await Label.query().insert({name: undefined})
</code>```

答:
Unfortunately $beforeValidate is a synchronous operation.

You can check it on the Official Documentation. Even there is an issue about it.

Body:
I want the $beforeValidate to wait for the async operation to complete as it updates the object to make it pass validation. But currently the $beforeValidate completes and rejects the record as it is not waiting for the async operation to complete.

class Label extends Model {
 async $beforeValidate() {
  if(this.name === undefined){
    const res = await axios.get('/getSomeName')
    console.log(res.body)
    this.name = res.body
  }
 }
 static get jsonSchema () {
    return {
      type: 'object',
      required: ['name'],
      properties: {
        id: { type: 'integer' },
        name: { type: 'string' }
      }
    }
 }
}

Now when i insert a label with name undefined I can see that the validation error is raised before the async API call has even finished

await Label.query().insert({name: undefined})