问:
avoiding garbage data while reading data using a byte buffer
I am trying to write a program to transfer a file between client and server using java tcp sockets I am using buffer size of 64K but The problem I am facing is that when when the tcp sometimes fail to send the whole 64K it sends the remaing part for example 32K in anther go
There for A garbage data of some Spaces or so is being taken by the buffer at reading side to make 64K complete and thus unnecessary data is making the file useless at receiving side.
Is there any solution to overcome this problem ???

I am using TCP protocol this code is using to send data to client

Server-side code

File transferFile = new File ("Document.txt");
byte [] bytearray = new byte [1024];
int byRead=0;
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
OutputStream os = socket.getOutputStream();
while(byRead>-1) {
  byRead=bin.read(bytearray,0,bytearray.length);
  os.write(bytearray,0,bytearray.length);
  os.flush();
}
```

<h3>Client-side code</h3>

<pre class="lang-java prettyprint-override"><code>byte [] bytearray = new byte [1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\NetBeansProjects\\"+filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead; System.out.println("Data is being read ...");
do {
  bytesRead = is.read(bytearray, 0, (bytearray.length));
  if(bytesRead == 0) continue;
  if(bytesRead >= 0) currentTot += bytesRead;
  bos.write(bytearray,0,bytearray.length);
} while(bytesRead > -1);
</code>```

here I tried to skip the loop if the byte is empty by continue; statement but it is not
working.

答:
use CLIENT Side Code as below to get the total write bytes without garbage

int availableByte = socket.available();
if (availableByte > 0) {
  byte[] buffer = new byte[availableByte];
  int bytesRead = socketInputStream.read(buffer);
  FileOutputStream fileOutputStream = new FileOutputStream(FilePath, true);
  OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
  BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
  bufferedWriter.write(buffer.toString());
  bufferedWriter.close();
}
```

Body:
I am trying to write a program to transfer a file between client and server using java tcp sockets I am using buffer size of 64K but The problem I am facing is that when when the tcp sometimes fail to send the whole 64K it sends the remaing part for example 32K in anther go
There for A garbage data of some Spaces or so is being taken by the buffer at reading side to make 64K complete and thus unnecessary data is making the file useless at receiving side.
Is there any solution to overcome this problem ???

I am using TCP protocol this code is using to send data to client

Server-side code

File transferFile = new File ("Document.txt");
byte [] bytearray = new byte [1024];
int byRead=0;
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
OutputStream os = socket.getOutputStream();
while(byRead>-1) {
  byRead=bin.read(bytearray,0,bytearray.length);
  os.write(bytearray,0,bytearray.length);
  os.flush();
}

Client-side code

byte [] bytearray = new byte [1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\NetBeansProjects\\"+filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead; System.out.println("Data is being read ...");
do {
  bytesRead = is.read(bytearray, 0, (bytearray.length));
  if(bytesRead == 0) continue;
  if(bytesRead >= 0) currentTot += bytesRead;
  bos.write(bytearray,0,bytearray.length);
} while(bytesRead > -1);

here I tried to skip the loop if the byte is empty by continue; statement but it is not
working.


来源: stackexchange

问:
Retrieve part of a string from a full text
I hve a string variable which contains a text along with some dates in it. Now I would like to retrieve the date from the text. How I can do it.

```<code>String a ="I am ready at time -S 2019-06-16:00:00:00 and be there"
</code>```

Now I would like to retrieve 2019-06-16:00:00:00 from there. Date format will always be in the same format but I need to retrieve the date only from the text.

答:
```<code>String str = "I am ready at time -S 2019-06-16:00:00:00 and be there";
Pattern pattern = Pattern.compile("(?<date>\\d{4}-\\d{2}-\\d{2}):(?<time>\\d{2}:\\d{2}:\\d{2})");
Matcher matcher = pattern.matcher(str);

if(matcher.matches()) {
    System.out.println(matcher.group("date"));  // 2019-06-16
    System.out.println(matcher.group("time"));  // 00:00:00
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I hve a string variable which contains a text along with some dates in it. Now I would like to retrieve the date from the text. How I can do it.

String a ="I am ready at time -S 2019-06-16:00:00:00 and be there"

Now I would like to retrieve 2019-06-16:00:00:00 from there. Date format will always be in the same format but I need to retrieve the date only from the text.


答:
Use the regular expression to retrieve the date from the text.</p>

```<code>public static void main(String[] args) {
    String a = "I am ready at time -S 2019-06-16:00:00:00 and be there";
    Pattern pattern = Pattern.compile("[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}");
    Matcher matcher = pattern.matcher(a);
    while(matcher.find()){
        System.out.println(matcher.group());
    }
}
</code>```

Title: Retrieve part of a string from a full text

Body:
Use the regular expression to retrieve the date from the text.

public static void main(String[] args) {
    String a = "I am ready at time -S 2019-06-16:00:00:00 and be there";
    Pattern pattern = Pattern.compile("[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}");
    Matcher matcher = pattern.matcher(a);
    while(matcher.find()){
        System.out.println(matcher.group());
    }
}


问:
Bot Framework v3: How to properly perform a user signout?
I'm currently using Bot Framework v3 SDK for C#. My issue occurs when I sign a user out, it doesn't clear out the user's login credentials from the pop up window (Note: the pop up window opens up an in-app browser, not my browser). So when my bot prompts the user to sign in again (using a Sign In Card), the login prompt for Microsoft accounts (https://login.microsoftonline.com/common) shows up for a brief second or two before automatically closing. My bot then receives an access token based on the previously signed out user. My testing environments are Microsoft Teams and Bot Emulator.

To sign in, I'm using GetTokenDialog in the Microsoft.Bot.Builder.Dialogs namespace which handles the user sign in and exchanging the authorization token for an access token. This part is working correctly as I'm able to make MS Graph calls with this access token.

To sign out, I'm currently using the Extensions library provided in Microsoft.Bot.Builder.Dialogs namespace.

```<code>bool success = await context.SignOutUserAsync(ConnectionName);
</code>```

where context is a IDialogContext object and ConnectionName is a string of my AAD's OAuth Connection Name.

Using Fiddler, I know that this single code statement makes a HTTP DELETE request to token.botframework.com to delete the token from Azure Bot Service. It returns a boolean value depending on the HTTP response status code and I'm always getting true value. My token is removed from Azure Bot Service but the pop up window for login automatically signs the user based on previous credentials. This leads me to believe that await context.SignOutUserAsync(ConnectionName); doesn't make a logout call to Microsoft Online to graciously log my user out but instead only deletes the token from the Azure Bot Service.

Any documentation and samples I found online makes use of this single code statement to sign out a user. Is there something wrong/missing with what I'm doing? Are there any alternatives to circumvent this issue?

答:
This might be because you are selecting the 'keep me signed in' option.

On the call of SignOutUserAsync(), the token is deleted from Azure. But the user credentials are still cached inside the popup window browser.

Body:
I'm currently using Bot Framework v3 SDK for C#. My issue occurs when I sign a user out, it doesn't clear out the user's login credentials from the pop up window (Note: the pop up window opens up an in-app browser, not my browser). So when my bot prompts the user to sign in again (using a Sign In Card), the login prompt for Microsoft accounts (https://login.microsoftonline.com/common) shows up for a brief second or two before automatically closing. My bot then receives an access token based on the previously signed out user. My testing environments are Microsoft Teams and Bot Emulator.

To sign in, I'm using GetTokenDialog in the Microsoft.Bot.Builder.Dialogs namespace which handles the user sign in and exchanging the authorization token for an access token. This part is working correctly as I'm able to make MS Graph calls with this access token.

To sign out, I'm currently using the Extensions library provided in Microsoft.Bot.Builder.Dialogs namespace.

bool success = await context.SignOutUserAsync(ConnectionName);

where context is a IDialogContext object and ConnectionName is a string of my AAD's OAuth Connection Name.

Using Fiddler, I know that this single code statement makes a HTTP DELETE request to token.botframework.com to delete the token from Azure Bot Service. It returns a boolean value depending on the HTTP response status code and I'm always getting true value. My token is removed from Azure Bot Service but the pop up window for login automatically signs the user based on previous credentials. This leads me to believe that await context.SignOutUserAsync(ConnectionName); doesn't make a logout call to Microsoft Online to graciously log my user out but instead only deletes the token from the Azure Bot Service.

Any documentation and samples I found online makes use of this single code statement to sign out a user. Is there something wrong/missing with what I'm doing? Are there any alternatives to circumvent this issue?


问:
Update query is not working in the function created but that same query when runs manually working
I am creating function in which update command is used consecutively two times the first update is working and the second one is not

Have tried execute format () for the second update not working

While running the function the updation2 is not working but when I manually run this updation command the table get updated...

The code is as follows:

```<code>update edmonton.weekly_pmt_report
  set permit_number = pmt.prnum
  from(select permit_details,
        split_part(permit_details,'-',1) as prnum
       from edmonton.weekly_pmt_report) as pmt
  where edmonton.weekly_pmt_report.permit_details =
    pmt.permit_details;

execute format('update edmonton.weekly_pmt_report
  set address = ds_dt.adr,
      job_description = ds_dt.job,
      applicant = ds_dt.apnt
  from(select split_part(per_num,''-'',1) as job_id,
        job_des as job,addr as adr, applic as apnt
        from edmonton.descriptive_details ) as ds_dt
  where edmonton.weekly_pmt_report.permit_number =
    ds_dt.job_id');
</code>```

答: That the second update query has value only 400 out of 1000 so the null columns are on the Top, that's why It seemed to be not working...</p>

Body:
I am creating function in which update command is used consecutively two times the first update is working and the second one is not

Have tried execute format () for the second update not working

While running the function the updation2 is not working but when I manually run this updation command the table get updated...

The code is as follows:

update edmonton.weekly_pmt_report
  set permit_number = pmt.prnum
  from(select permit_details,
        split_part(permit_details,'-',1) as prnum
       from edmonton.weekly_pmt_report) as pmt
  where edmonton.weekly_pmt_report.permit_details =
    pmt.permit_details;

execute format('update edmonton.weekly_pmt_report
  set address = ds_dt.adr,
      job_description = ds_dt.job,
      applicant = ds_dt.apnt
  from(select split_part(per_num,''-'',1) as job_id,
        job_des as job,addr as adr, applic as apnt
        from edmonton.descriptive_details ) as ds_dt
  where edmonton.weekly_pmt_report.permit_number =
    ds_dt.job_id');


问:
Run application after click on the Finish button (not after install)
I have a setup for installing my application, and I need to run the application after successfully installing. I used postinstall to do this.

but it shows a checkbox and the user can uncheck it. I need to run the application without asking because of it kinda service which needs to runs at startup. if the user unchecked it he needs to restart the PC to launch.

So I can use the Filename: "{app}\myapp.exe" code without any flags in the Run section to launch the application but the problem is, It runs immediately after installing not after the finish button clicked.

The first issue is my application has an instruction window. it shows up at the launch so the setup window goes to the back. And the second issue is my application does not allow terminating unless uninstall becouse it need to run in the background. Setup waiting to process end to finish.

Is there any way to run the application after the finish button click in inno setup?

答:
Add code section to your script like this:

```<code>[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
  ResultCode: Integer;
begin
  if CurStep = ssDone then
    Exec(ExpandConstant('{app}\MyProg.exe'), '', '', SW_SHOW, ewNoWait, ResultCode);
end;
</code>```

It will be triggered only on a success installation.

Use ExecAsOriginalUser instead of Exec if you don't want the exe run as admin.

Body:
Add code section to your script like this:

[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
  ResultCode: Integer;
begin
  if CurStep = ssDone then
    Exec(ExpandConstant('{app}\MyProg.exe'), '', '', SW_SHOW, ewNoWait, ResultCode);
end;

It will be triggered only on a success installation.

Use ExecAsOriginalUser instead of Exec if you don't want the exe run as admin.


问:
Sonata page URL
What is concept creating url / path for sonata page - I want create not hardcoded path in template. In doc https://sonata-project.org/bundles/page/master/doc/reference/twig_helpers.html  have

```<code>8.1. URL
Render a page url

{{ path(page) }} => /absolute/path/to/url

{{ path(page, {}, true) }} => ../relative/path/to/url

{{ url(page) }} => https://sonata-project.org/absolute/url/to/url

{{ url(page, {}, true) }} => //sonata-project.org/network/path/to/url
</code>```

what is page ?

i try page id , slug get error.

答:
I have try it.

Variable page was not defined - so i think its just an example in sonata doc.

If you type in shell (symfony-root-folder)

```<code> php bin/console debug:router
</code>```

You will get a list of all defined routes in your app.

You can use any name from this list as parameter. Eg: {{ url('sonata_admin_dashboard')}}

... and will get the Path from this list as path or url: Eg. http://localhost:8000/admin/dashboard

More Info:

https://symfony.com/doc/current/routing/debug.html

https://symfony.com/doc/current/routing.html

Title: Sonata page URL

Body:
What is concept creating url / path for sonata page - I want create not hardcoded path in template. In doc https://sonata-project.org/bundles/page/master/doc/reference/twig_helpers.html  have

8.1. URL
Render a page url

{{ path(page) }} => /absolute/path/to/url

{{ path(page, {}, true) }} => ../relative/path/to/url

{{ url(page) }} => https://sonata-project.org/absolute/url/to/url

{{ url(page, {}, true) }} => //sonata-project.org/network/path/to/url

what is page ?

i try page id , slug get error.

Body:
I have try it.

Variable page was not defined - so i think its just an example in sonata doc.

If you type in shell (symfony-root-folder)

 php bin/console debug:router

You will get a list of all defined routes in your app.

You can use any name from this list as parameter. Eg: {{ url('sonata_admin_dashboard')}}

... and will get the Path from this list as path or url: Eg. http://localhost:8000/admin/dashboard

More Info:

https://symfony.com/doc/current/routing/debug.html

https://symfony.com/doc/current/routing.html


问:
"allow create" not working for certain collection in Firestore Rules
I am having a database in Firestore which have the number of collections for which I have defined security rules with read, create, update and delete operations.

Till Saturday noon, all the rules with given condition was allowing to read and write the data to the collections but suddenly after that in one specific collection named "locations" it giving PERMISSION DENIED exception only for creating document in the same collection but read, update and delete works.

So I changed rule for that collection like for testing as below

```<code>match /locations/{locationID} {
    allow read: if true;
    allow create: if true; //Condition commented...
    allow update: if <condition>;
    allow delete: if false;
}
</code>```

and in Android Client I have coded as

```<code>database.collection("locations").add(mapData)
            .addOnCompleteListener {
                 if (it.isSuccessful) {
                     //Success
                 } else {
                     //Exception
                 }
             }
</code>```

Even though, making to allow create: if true, it gives the same exception of Missing or Insufficient Permission. but when I change it to "allow write: if true" it works and document is added

When I changed collection name to test in both Rules and Client Code, it creates new document in the same collection but when I changed collection name to locationData, location and locations, it won't work.

Is this an issue in Firestore rule or What can be the solution for this?

答:
It seems like your update rule is triggered while trying to save the dataMap to Firestore.

Please note that add() is basically a doc.set().

The behavior of set() is that it tries to overwrite the doc if it already exists and will perform an update operation thereby triggering the update rule in your security rules.

You have two options:

1) Check the data you're trying to save already exist in the locations collection.

2) Set the update rule to allow true so that you can verify that the document already exists.

Hope that helps.

Body:
I am having a database in Firestore which have the number of collections for which I have defined security rules with read, create, update and delete operations.

Till Saturday noon, all the rules with given condition was allowing to read and write the data to the collections but suddenly after that in one specific collection named "locations" it giving PERMISSION DENIED exception only for creating document in the same collection but read, update and delete works.

So I changed rule for that collection like for testing as below

match /locations/{locationID} {
    allow read: if true;
    allow create: if true; //Condition commented...
    allow update: if <condition>;
    allow delete: if false;
}

and in Android Client I have coded as

database.collection("locations").add(mapData)
            .addOnCompleteListener {
                 if (it.isSuccessful) {
                     //Success
                 } else {
                     //Exception
                 }
             }

Even though, making to allow create: if true, it gives the same exception of Missing or Insufficient Permission. but when I change it to "allow write: if true" it works and document is added

When I changed collection name to test in both Rules and Client Code, it creates new document in the same collection but when I changed collection name to locationData, location and locations, it won't work.

Is this an issue in Firestore rule or What can be the solution for this?


问:
How to get the correct element from a unicode string?
I want to get specific letters from an unicode string using index. However, it doesn't work as expected.

Example:

var handwriting = `1234567890`
var normal = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`

console.log(normal[3]) // gives 'd' but
console.log(handwriting[3]) // gives '�' instead of ''```

also length doesn't work as expected normal.length gives correct value as 62 but handwriting.length gives 114.

Indexing doesn't work as expected. How can I access the elements of unicode array?

I tried this on python it works perfectly but in Javascript it is not working.

I need exact characters from the unicode string like an expected output of 'd' '' for index 3

答:
In Javascript, a string is a sequence of 16-bit code points. Since these characters are encoded above the Basic Multilingual Plane, it means that they are represented by a pair of code points, also known as a surrogate pair.

Reference

Unicode number of  is U+1D586. And 0x1D586 is greater than 0xFFFF (2^16). So,  is  represented by a pair of code points, also known as a surrogate pair

console.log("".length)
console.log("" === "\uD835\uDD86")```
</div>
</div>
</p>

<p>One way is to create an array of characters using the spread syntax or <code>Array.from()</code> and then get the index you need</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var handwriting = `1234567890`

console.log([...handwriting][3])
console.log(Array.from(handwriting)[3])</code>```

Body:
I want to get specific letters from an unicode string using index. However, it doesn't work as expected.

Example:

var handwriting = `1234567890`
var normal = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`

console.log(normal[3]) // gives 'd' but
console.log(handwriting[3]) // gives '�' instead of ''

also length doesn't work as expected normal.length gives correct value as 62 but handwriting.length gives 114.

Indexing doesn't work as expected. How can I access the elements of unicode array?

I tried this on python it works perfectly but in Javascript it is not working.

I need exact characters from the unicode string like an expected output of 'd' '' for index 3

Body:
In Javascript, a string is a sequence of 16-bit code points. Since these characters are encoded above the Basic Multilingual Plane, it means that they are represented by a pair of code points, also known as a surrogate pair.

Reference

Unicode number of  is U+1D586. And 0x1D586 is greater than 0xFFFF (2^16). So,  is  represented by a pair of code points, also known as a surrogate pair

console.log("".length)
console.log("" === "\uD835\uDD86")

One way is to create an array of characters using the spread syntax or Array.from() and then get the index you need

var handwriting = `1234567890`

console.log([...handwriting][3])
console.log(Array.from(handwriting)[3])


问:
How to optimize mysql join query, Not using join
I am trying to optimize the below query it yields me the following result

```<code>EXPLAIN UPDATE table1 a
JOIN table2 b
    ON a.id=b.ref_id
SET a.value=b.value;
</code>```

When i try to explain the query, I get the following result.

```<code>ID  select_type     table   type    possible_keys   key         key_len ref         rows    Extra
1   SIMPLE          b       ALL     idx_ref_id                                      10785
1   SIMPLE          a       ref     idx_id          idx_id      4       b.ref_id    24
</code>```

As far as i understand query is using only one index i.e idx_id and not idx_ref_id.

Edit:

Here is the table structure.

```<code>SHOW CREATE TABLE table1;

CREATE TABLE table_1 (
  `id` int(11) NOT NULL DEFAULT '0',
  `companyname` varchar(100) NOT NULL DEFAULT '',
  `value` varchar(100) NOT NULL DEFAULT '',
  `sve_value` varchar(100) NOT NULL DEFAULT '',
  KEY `idx_id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

SHOW CREATE TABLE table2;

CREATE TABLE `table2` (
  `value` varchar(255) DEFAULT NULL,
  `suggested_value_enrichement` varchar(255) DEFAULT NULL,
  `tags` varchar(255) DEFAULT NULL,
  `ref_id` int(11) NOT NULL DEFAULT '0',
  KEY `idx_ref_id` (`ref_id`),
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
</code>```

Please help me, Also please correct me if am wrong.

Thanks.

答:
Issue with query was there were many process running on the server which choked the resources. Also there were many ideal connection to the database to precise around 150.

So by killing the process and terminating the ideal connection solved the issue.

Query execution finished within a minute.

Body:
I am trying to optimize the below query it yields me the following result

EXPLAIN UPDATE table1 a
JOIN table2 b
    ON a.id=b.ref_id
SET a.value=b.value;

When i try to explain the query, I get the following result.

ID  select_type     table   type    possible_keys   key         key_len ref         rows    Extra
1   SIMPLE          b       ALL     idx_ref_id                                      10785
1   SIMPLE          a       ref     idx_id          idx_id      4       b.ref_id    24

As far as i understand query is using only one index i.e idx_id and not idx_ref_id.

Edit:

Here is the table structure.

SHOW CREATE TABLE table1;

CREATE TABLE table_1 (
  `id` int(11) NOT NULL DEFAULT '0',
  `companyname` varchar(100) NOT NULL DEFAULT '',
  `value` varchar(100) NOT NULL DEFAULT '',
  `sve_value` varchar(100) NOT NULL DEFAULT '',
  KEY `idx_id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

SHOW CREATE TABLE table2;

CREATE TABLE `table2` (
  `value` varchar(255) DEFAULT NULL,
  `suggested_value_enrichement` varchar(255) DEFAULT NULL,
  `tags` varchar(255) DEFAULT NULL,
  `ref_id` int(11) NOT NULL DEFAULT '0',
  KEY `idx_ref_id` (`ref_id`),
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Please help me, Also please correct me if am wrong.

Thanks.


问:
Is there a way to simulate a click on an alert in JavaScript?
I have a page with an iframe whose source page is in a separate domain. From time to time, the source page generates an alert. When it does so, it stops what it is doing until the user clicks OK to the alert.

What I would like to do is programmatically click OK on this alert so the source page can get back to being useful. Is this possible?

答:
JavaScript is single-threaded, which means when you call a function, it blocks until it returns. When you call alert(), that passes control to the browser which decides how to handle it. It is not Javascript which is popping the UI dialog, it is the browser. alert() does not return until the browser receives the "OK" event and returns control. The javascript thread is halted until that happens.

So for at least two different reasons stated in the above paragraph, the answer is no :)

OwnerDisplayName: moffdub

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rex M


问:
Best way to handle background process
I got my first android phone since two week
And I'm starting my first real App.
My phone is a LG Optimus 2X and one of the missing thing is a
notification led for when there is a missed call, sms, email ect ...

So I'm wondering what's the best way to do this.

For know I've a broatcastreceiver for incoming sms, and the I call a
service that will light the phone buttons (don't bother about this
part, it's working).
But seems that this method will workin only for sms, phone calls, not
emails.

So know I'm thinking to used Listeners instead for everything, but
this mean having a service running  nonstop. Not sure it's the best
way ...

I hope I'm clear, and that my ennglish is not too bad.
Thx in advance

答:
I recommend you to use the BuzzBox SDK. It has a scheduler that you can configure with a cron string and a simple notification api. You can also add to your app the integrated settings UI that include vibration, blinking and disabling during night time.
Check out: http://hub.buzzbox.com</p>

ContentLicense: CC BY-SA 3.0

Title: Best way to handle background process


问:
How can i send the Map Object in multipart request in flutter
Here I am trying to send the Object Map in the multipart request but my request is going as a string, not in JSON format please suggest me to do correct request. Thanks in advance.

I have tried the multipart request but my request should be in correct form..

```<code>var getApiUrl = 'http://malik-env-test.ap-south-1.elasticbeanstalk.com/webapi/post/create';

  Map userData = {

    "creator": {
      "creatorId": "298",
      "createDate": "2018-12-21 20:44:45.8"
    },
    "info": "$campusInfo",
    "title": "$eventName",
    "postCampusId": "5642"

  };

</code>```

```<code>Uri uri = Uri.parse(getApiUrl);
   http.MultipartRequest request = new http.MultipartRequest('POST', uri);
   request.fields['creator'] = userData['creator'];
   request.fields['info'] = '$campusInfo';
   request.fields['title'] = '$eventName';
   request.fields['postCampusId'] = '5642';
   request.files.add(await http.MultipartFile.fromPath('image_file1', imagePath, contentType: new MediaType('application', 'x-tar')));
//   var body = json.encode(request);
   print(request);
   http.StreamedResponse response = await request.send();
   String jsonData = response.toString();
   print(jsonData);ddd
</code>```

答:
```<code>   var userData = json.encode({
     "creator": {
           "creatorId": "298",
            "createDate": "2018-12-21 20:44:45.8"
       },
      "info": "$campusInfo",
      "title": "$eventName",
      "postCampusId": "5642"
    });
    var client = http.Client();
    client
        .post('https://'+ url ,
            headers: {
              'content-type': 'application/json',
            },
            body: userData )
</code>```

Body:
Here I am trying to send the Object Map in the multipart request but my request is going as a string, not in JSON format please suggest me to do correct request. Thanks in advance.

I have tried the multipart request but my request should be in correct form..

var getApiUrl = 'http://malik-env-test.ap-south-1.elasticbeanstalk.com/webapi/post/create';

  Map userData = {

    "creator": {
      "creatorId": "298",
      "createDate": "2018-12-21 20:44:45.8"
    },
    "info": "$campusInfo",
    "title": "$eventName",
    "postCampusId": "5642"

  };

Uri uri = Uri.parse(getApiUrl);
   http.MultipartRequest request = new http.MultipartRequest('POST', uri);
   request.fields['creator'] = userData['creator'];
   request.fields['info'] = '$campusInfo';
   request.fields['title'] = '$eventName';
   request.fields['postCampusId'] = '5642';
   request.files.add(await http.MultipartFile.fromPath('image_file1', imagePath, contentType: new MediaType('application', 'x-tar')));
//   var body = json.encode(request);
   print(request);
   http.StreamedResponse response = await request.send();
   String jsonData = response.toString();
   print(jsonData);ddd


问:
I want to get data from 3 tables
I have 3 tables employee, jobs and department as below,

```<code>-------------------    ----------------    ------------------
| employee        |    |    jobs      |    |   department    |
-------------------    ----------------    ------------------
| empId           |    | jobId        |    |  deptId         |
| fname           |    | jobTitle     |    |  deptName       |
| lname           |    |              |    |  managerId      |
| jobId           |    |              |    |                 |
| managerId       |    |              |    |                 |
| departmentId    |    |              |    |                 |
-------------------    ----------------    -------------------
</code>```

I want to select all data from employee, the job title through jobId, the deptName through deptId and manager name through managerId and employeeId

```<code>SELECT EMPLOYEES.EMPLOYEE_ID, EMPLOYEES.FIRST_NAME, EMPLOYEES.LAST_NAME,
EMPLOYEES.JOB_ID, JOBS.JOB_TITLE AS JOB_TITLE, EMPLOYEES.SALARY,
DEPARTMENTS.DEPARTMENT_ID, DEPARTMENTS.DEPARTMENT_NAME AS DEPARTMENT_NAME
FROM EMPLOYEES
LEFT JOIN JOBS ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
LEFT JOIN DEPARTMENTS ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
</code>```

what should I do to get the name of the manager using the empId?
or is there any other way to simplify this block of code?

答:
You can use another left join on employee table to get the manager name.</p>

```<code>SELECT (
EMPLOYEES.EMPLOYEE_ID,
EMPLOYEES.FIRST_NAME,
EMPLOYEES.LAST_NAME,
EMPLOYEES.JOB_ID,
JOBS.JOB_TITLE AS JOB_TITLE,
EMPLOYEES.SALARY,
DEPARTMENTS.DEPARTMENT_ID,
DEPARTMENTS.DEPARTMENT_NAME AS DEPARTMENT_NAME,
(MGR.FIRST_NAME + ' ' + MGR.LAST_NAME) AS MANAGER_NAME)
FROM EMPLOYEES
LEFT JOIN JOBS
ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
LEFT JOIN DEPARTMENTS
ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
LEFT JOIN EMPLOYEES MGR
ON EMPLOYEES.MANAGERID = MGR.EMPLOYEE_ID
</code>```

Title: I want to get data from 3 tables

Body:
I have 3 tables employee, jobs and department as below,

-------------------    ----------------    ------------------
| employee        |    |    jobs      |    |   department    |
-------------------    ----------------    ------------------
| empId           |    | jobId        |    |  deptId         |
| fname           |    | jobTitle     |    |  deptName       |
| lname           |    |              |    |  managerId      |
| jobId           |    |              |    |                 |
| managerId       |    |              |    |                 |
| departmentId    |    |              |    |                 |
-------------------    ----------------    -------------------

I want to select all data from employee, the job title through jobId, the deptName through deptId and manager name through managerId and employeeId

SELECT EMPLOYEES.EMPLOYEE_ID, EMPLOYEES.FIRST_NAME, EMPLOYEES.LAST_NAME,
EMPLOYEES.JOB_ID, JOBS.JOB_TITLE AS JOB_TITLE, EMPLOYEES.SALARY,
DEPARTMENTS.DEPARTMENT_ID, DEPARTMENTS.DEPARTMENT_NAME AS DEPARTMENT_NAME
FROM EMPLOYEES
LEFT JOIN JOBS ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
LEFT JOIN DEPARTMENTS ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID

what should I do to get the name of the manager using the empId?
or is there any other way to simplify this block of code?

Body:
You can use another left join on employee table to get the manager name.

SELECT (
EMPLOYEES.EMPLOYEE_ID,
EMPLOYEES.FIRST_NAME,
EMPLOYEES.LAST_NAME,
EMPLOYEES.JOB_ID,
JOBS.JOB_TITLE AS JOB_TITLE,
EMPLOYEES.SALARY,
DEPARTMENTS.DEPARTMENT_ID,
DEPARTMENTS.DEPARTMENT_NAME AS DEPARTMENT_NAME,
(MGR.FIRST_NAME + ' ' + MGR.LAST_NAME) AS MANAGER_NAME)
FROM EMPLOYEES
LEFT JOIN JOBS
ON EMPLOYEES.JOB_ID = JOBS.JOB_ID
LEFT JOIN DEPARTMENTS
ON EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID
LEFT JOIN EMPLOYEES MGR
ON EMPLOYEES.MANAGERID = MGR.EMPLOYEE_ID


问:
Can I 'include' another file in a page xml file
I've got a few pages that are similar - is it possible to include another file including the shared elements.</p>

答:
Yes, You can do it.

https://docs.nativescript.org/ui/basics#custom-components

You can define your own XML namespaces to create custom user interface
  components. The custom components can be created via XML files or via
  code-behind JS/TS implementation.


问:
How to open a webView from assets, by switchcase function?
I have 10 cardview in a fragment, when user click on one it'll open a specific html file within the application. When I try to open this class, the apps always crash .

My MainActivity is here

2nd Activity is here

答:
What you can do to solve your issues is, in your MainActivity's onclick method change like :

```<code>Intent i;
        switch (v.getId()) {
            case R.id.indonesia_card:
                i = new Intent(this, Indonesia.class);
                i.putExtra("isFrom", "Indonesia");
                startaCtivity(i);
            case R.id.mathematika_card:
                i = new Intent(this, Indonesia.class);
                i.putExtra("isFrom", "Mathematika");
                startaCtivity(i);
            case R.id.ipa_card:
                i = new Intent(this, Indonesia.class);
                i.putExtra("isFrom", "IPA");
                startaCtivity(i);
        }
</code>```

Now, In your other Activity receive the intent and set data appropriately.

```<code>String from = getIntent.getStringExtra("isFrom");
        if (isFrom != null) {
            if (isFrom.equals("Indonesia") {
                webview.loadUrl("file:///android_asset/yourfile.html");
            } else if (isFrom.equals("Mathematika") {
                webview.loadUrl("file:///android_asset/yourfile.html");
            }else if (isFrom.equals("IPA") {
                webview.loadUrl("file:///android_asset/yourfile.html");
            }
        }
</code>```

Hope this will help you.

Body:
What you can do to solve your issues is, in your MainActivity's onclick method change like :

Intent i;
        switch (v.getId()) {
            case R.id.indonesia_card:
                i = new Intent(this, Indonesia.class);
                i.putExtra("isFrom", "Indonesia");
                startaCtivity(i);
            case R.id.mathematika_card:
                i = new Intent(this, Indonesia.class);
                i.putExtra("isFrom", "Mathematika");
                startaCtivity(i);
            case R.id.ipa_card:
                i = new Intent(this, Indonesia.class);
                i.putExtra("isFrom", "IPA");
                startaCtivity(i);
        }

Now, In your other Activity receive the intent and set data appropriately.

String from = getIntent.getStringExtra("isFrom");
        if (isFrom != null) {
            if (isFrom.equals("Indonesia") {
                webview.loadUrl("file:///android_asset/yourfile.html");
            } else if (isFrom.equals("Mathematika") {
                webview.loadUrl("file:///android_asset/yourfile.html");
            }else if (isFrom.equals("IPA") {
                webview.loadUrl("file:///android_asset/yourfile.html");
            }
        }

Hope this will help you.


答:
A unicode character looks like '\u00E9' so if your string is longer this is normal.
To have the real length of a unicode string, you have to convert it to an array :

```<code>let charArray = [...handwriting]
console.log(charArray.length) //=62
</code>```

Each item of your array is a char of your string.
charArray[3] will return you the unicode char corresponding to ''

Title: How to get the correct element from a unicode string?

Body:
A unicode character looks like '\u00E9' so if your string is longer this is normal.
To have the real length of a unicode string, you have to convert it to an array :

let charArray = [...handwriting]
console.log(charArray.length) //=62

Each item of your array is a char of your string.
charArray[3] will return you the unicode char corresponding to ''


问:
Groovy enum: switch statement throws error before running relating to static
The following code can be compiled fine in Intellij, but when trying to use Groovy as a script, it throws an error even before running.
I can't find out the crack, since everything is static actually?

```<code>public enum OutputType {
        ABC,
        DEF,
        GHI
    }
    //Just initializing here
        public static OutputType output=OutputType.ABC;

    public static void run() {

        switch (output){
            case ABC:
                runABC();
                break;

            case DEF:
                runDEF();
                break;

            case GHI:
                runGHI();
                break;

            default:
                break;
        }
    }
</code>```

The error:

```<code>org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 50: Apparent variable 'ABC' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'ABC' but left out brackets in a place not allowed by the grammar.
 @ line 50, column 18.
               case ABC:
                    ^

Script1.groovy: 54: Apparent variable 'DEF' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'DEF' but left out brackets in a place not allowed by the grammar.
 @ line 54, column 18.
               case DEF:
                    ^

Script1.groovy: 58: Apparent variable 'GHI' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'GHI' but left out brackets in a place not allowed by the grammar.
 @ line 58, column 18.
               case GHI:
</code>```

答:
So I retried with deleting all static statements before.
Got a new error now. Unfortunately I had to wipe the classname:

```<code>groovy.lang.MissingPropertyException: No such property: OutputType for class: XXXXXXXXXXX.tempscripts.Script1
</code>```

Since this this another issue I marked the answer above as correct.
Thank you!

Body:
The following code can be compiled fine in Intellij, but when trying to use Groovy as a script, it throws an error even before running.
I can't find out the crack, since everything is static actually?

public enum OutputType {
        ABC,
        DEF,
        GHI
    }
    //Just initializing here
        public static OutputType output=OutputType.ABC;

    public static void run() {

        switch (output){
            case ABC:
                runABC();
                break;

            case DEF:
                runDEF();
                break;

            case GHI:
                runGHI();
                break;

            default:
                break;
        }
    }

The error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 50: Apparent variable 'ABC' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'ABC' but left out brackets in a place not allowed by the grammar.
 @ line 50, column 18.
               case ABC:
                    ^

Script1.groovy: 54: Apparent variable 'DEF' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'DEF' but left out brackets in a place not allowed by the grammar.
 @ line 54, column 18.
               case DEF:
                    ^

Script1.groovy: 58: Apparent variable 'GHI' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'GHI' but left out brackets in a place not allowed by the grammar.
 @ line 58, column 18.
               case GHI:

Body:
So I retried with deleting all static statements before.
Got a new error now. Unfortunately I had to wipe the classname:

groovy.lang.MissingPropertyException: No such property: OutputType for class: XXXXXXXXXXX.tempscripts.Script1

Since this this another issue I marked the answer above as correct.
Thank you!


问:
XPath current() for Yang
This is my follow up question for Xpath current() in Yang After the earlier discussion, I implemented a customized function current() for libxml2 with implementation shown below. The function works fine as expected when it evaluates Xpath expressions like:

```<code>leaf test-string {
  type string;
  must "current() > 0";
}
</code>```

But when more complex expressions are involved like Xpath expresion "interface[name=current()/supporting-interface]/type = 'optical'", it does not seem to be working fine. Anything I am missing in the current() implementation.
Given below is my implementation. Also is there a way to print the ultimate Xpath expression that gets constructed by xmlXPathEvalExpression() API?

```<code>/*
 * ext_current () -- Defines the Xpath extension current(),
 * defined by Yang RFC.
 *
 * From Yang RFC 7950:
 *
 * The current() function takes no input parameters and returns a node
 * set with the initial context node as its only member.
 */
static void
ext_current (xmlXPathParserContextPtr ctxt, int nargs)
{
    /*
     * This function takes 0 args.
     */
    if (nargs != 0) {
        return;
    }

    /* Push the current context node onto Xpath Stack */
    valuePush(ctxt, xmlXPathNewNodeSet(ctxt->context->node));
}

/*
 * register_yang_xpath_extensions () -- Registers extensions defined by Yang
 * RFC.
 */
static void
register_yang_xpath_extensions (xmlXPathContextPtr ctxt)
{
    int rc = 0;

    rc = xmlXPathRegisterFunc(ctxt, (const xmlChar *)"current",
                              ext_current);
    if (rc != 0)
        fprintf(stderr, "Error in registering current() func\n");
}
</code>```

答:
. and current() are not the same in YANG, though they may return the same result in certain situations. The result of . changes with XPath path steps (the current context node, as you yourself refer to in your code), while current() always returns the same node no matter where it is used within the same XPath expression - the initial context node.

The initial context node for an XPath expression in YANG depends on where this expression is defined with respect to YANG schema. A combination of rules in RFC7950, Section 6.4.1 and these are used to determine the initial context node:

when statement:

The XPath expression is conceptually evaluated in the following
context, in addition to the definition in Section 6.4.1:

o  If the "when" statement is a child of an "augment" statement, then
the context node is the augment's target node in the data tree, if
the target node is a data node.  Otherwise, the context node is
the closest ancestor node to the target node that is also a data
node.  If no such node exists, the context node is the root node.
The accessible tree is tentatively altered during the processing
of the XPath expression by removing all instances (if any) of the
nodes added by the "augment" statement.

o  If the "when" statement is a child of a "uses", "choice", or
"case" statement, then the context node is the closest ancestor
node to the node with the "when" statement that is also a data
node.  If no such node exists, the context node is the root node.
The accessible tree is tentatively altered during the processing
of the XPath expression by removing all instances (if any) of the
nodes added by the "uses", "choice", or "case" statement.

o  If the "when" statement is a child of any other data definition
statement, the accessible tree is tentatively altered during the
processing of the XPath expression by replacing all instances of
the data node for which the "when" statement is defined with a
single dummy node with the same name, but with no value and no
children.  If no such instance exists, the dummy node is
tentatively created.  The context node is this dummy node.

RFC7950, Section 7.21.5

must statement:

The XPath expression is conceptually evaluated in the following
context, in addition to the definition in Section 6.4.1:

o  If the "must" statement is a substatement of a "notification"
statement, the context node is the node representing the
notification in the accessible tree.

o  If the "must" statement is a substatement of an "input" statement,
the context node is the node representing the operation in the
accessible tree.

o  If the "must" statement is a substatement of an "output"
statement, the context node is the node representing the operation
in the accessible tree.

o  Otherwise, the context node is the node in the accessible tree for
which the "must" statement is defined.

RFC7950, Section 7.5.3

path statement:

The "path" XPath expression is conceptually evaluated in the
following context, in addition to the definition in Section 6.4.1:

o  If the "path" statement is defined within a typedef, the context
node is the leaf or leaf-list node in the data tree that
references the typedef.

o  Otherwise, the context node is the node in the data tree for which
the "path" statement is defined.

RFC7950, Section 9.9.2

All of these rules need to be implemented in order to support standard YANG XPath, current() function included.

Title: XPath current() for Yang

Body:
This is my follow up question for Xpath current() in Yang After the earlier discussion, I implemented a customized function current() for libxml2 with implementation shown below. The function works fine as expected when it evaluates Xpath expressions like:

leaf test-string {
  type string;
  must "current() > 0";
}

But when more complex expressions are involved like Xpath expresion "interface[name=current()/supporting-interface]/type = 'optical'", it does not seem to be working fine. Anything I am missing in the current() implementation.
Given below is my implementation. Also is there a way to print the ultimate Xpath expression that gets constructed by xmlXPathEvalExpression() API?

/*
 * ext_current () -- Defines the Xpath extension current(),
 * defined by Yang RFC.
 *
 * From Yang RFC 7950:
 *
 * The current() function takes no input parameters and returns a node
 * set with the initial context node as its only member.
 */
static void
ext_current (xmlXPathParserContextPtr ctxt, int nargs)
{
    /*
     * This function takes 0 args.
     */
    if (nargs != 0) {
        return;
    }

    /* Push the current context node onto Xpath Stack */
    valuePush(ctxt, xmlXPathNewNodeSet(ctxt->context->node));
}

/*
 * register_yang_xpath_extensions () -- Registers extensions defined by Yang
 * RFC.
 */
static void
register_yang_xpath_extensions (xmlXPathContextPtr ctxt)
{
    int rc = 0;

    rc = xmlXPathRegisterFunc(ctxt, (const xmlChar *)"current",
                              ext_current);
    if (rc != 0)
        fprintf(stderr, "Error in registering current() func\n");
}


问:
Unable to delete file with complete path in c++
I am using visual studio 2017 and working in c++. I have code where I take some input from the user and based on that I am trying to delete a file.

```<code>auto ver = FLAGS_ver;  // taking input from the user

string file = "C:\\Program Files(x86)\\data_" + ver + "\\output\\output.json";

std::ofstream output_file(outputFile);
</code>```

Basically ver is a number based on which that particular directory is accessed. So final string file becomes:

```<code>C:\\Program Files(x86)\\data_209\\output\\output.json
</code>```

So I need to delete above file for which I am using below command:

```<code>int res = remove(file);
</code>```

But it shows below error:

```<code>Error (active)  E0304   no instance of overloaded function "std::remove" matches the argument list

Error   C2664   'int remove(const char *)': cannot convert argument 1 from 'std::string' to 'const char *'
</code>```

I am able to write to this json file so there is no issues with permission. How can I resolve this. Thanks

答:
Your problem is std::remove expects a C-string (const char *). You can use the c_str() method from std::string.

```<code>int res = remove(file.c_str());
</code>```

However, you could use the more appropriate C++ std::filesystem::remove (from C++17s filesystem library) to do the same. Now, Since you use Visual Studio 2017, std::filesystem was not yet fully implemented, and you have to use the experimental version. To accomplish the same:

```<code>#include <filesystem>
// ...
std::experimental::filesystem::remove(file);
</code>```

Body:
I am using visual studio 2017 and working in c++. I have code where I take some input from the user and based on that I am trying to delete a file.

auto ver = FLAGS_ver;  // taking input from the user

string file = "C:\\Program Files(x86)\\data_" + ver + "\\output\\output.json";

std::ofstream output_file(outputFile);

Basically ver is a number based on which that particular directory is accessed. So final string file becomes:

C:\\Program Files(x86)\\data_209\\output\\output.json

So I need to delete above file for which I am using below command:

int res = remove(file);

But it shows below error:

Error (active)  E0304   no instance of overloaded function "std::remove" matches the argument list

Error   C2664   'int remove(const char *)': cannot convert argument 1 from 'std::string' to 'const char *'

I am able to write to this json file so there is no issues with permission. How can I resolve this. Thanks

Body:
Your problem is std::remove expects a C-string (const char *). You can use the c_str() method from std::string.

int res = remove(file.c_str());

However, you could use the more appropriate C++ std::filesystem::remove (from C++17s filesystem library) to do the same. Now, Since you use Visual Studio 2017, std::filesystem was not yet fully implemented, and you have to use the experimental version. To accomplish the same:

#include <filesystem>
// ...
std::experimental::filesystem::remove(file);


问:
How to wait until a sound file ends in vlc in Python 3.6
I have a question in vlc in python</p>

```<code>import vlc

sound = vlc.MediaPlayer('sound.mp3')

sound.play()

# i wanna wait until the sound ends then do some code without
time.sleep()
</code>```

答:
for wait util end of vlc play sound, except your:

    player.play()
    time.sleep(1.5)
    duration = player.get_length() / 1000
    time.sleep(duration)
```

<p>other possible (maybe <strong>more precise</strong>, but <strong>CPU costing</strong>) method is:</p>

<pre class="lang-py prettyprint-override"><code>
# your code ...

Ended = 6
current_state = player.get_state()
while current_state != Ended:
  current_state = player.get_state()
  # do sth you want
print("vlc play ended")
</code>```

refer :

vlc.State definition

vlc.Instance

vlc.MediaPlayer - get_state

Body:
I have a question in vlc in python

import vlc

sound = vlc.MediaPlayer('sound.mp3')

sound.play()

# i wanna wait until the sound ends then do some code without
time.sleep()

Body:
for wait util end of vlc play sound, except your:

    player.play()
    time.sleep(1.5)
    duration = player.get_length() / 1000
    time.sleep(duration)

other possible (maybe more precise, but CPU costing) method is:

# your code ...

Ended = 6
current_state = player.get_state()
while current_state != Ended:
  current_state = player.get_state()
  # do sth you want
print("vlc play ended")

refer :

vlc.State definition

vlc.Instance

vlc.MediaPlayer - get_state


问:
Unable to get wanted output using for and range functions
For my homework assignment, I am using the for loop and the range function. I have to create a loop that prints

```<code>Hello 0
Hello 1
Hello 3
Hello 6
Hello 10
</code>```

The question says that the number corresponds to the accumulated summation over the successive indexes, but I am not really sure how to implement it into my code. I was thinking it was setting the range from 0 to 10 and trying to make a formula, but nothing has come yet. Any help would be appreciated. It has to be in a for i in range function and loop for this assignment.

```<code>for i in range(0,10,2):
    print("Hello",i)
</code>```

答:
may be this will be suitable :</p>

```<code>i=0
step=1
while i<=10:
    print("Hello", i)
    i=i+step
    step=step+1
</code>```

Body:
For my homework assignment, I am using the for loop and the range function. I have to create a loop that prints

Hello 0
Hello 1
Hello 3
Hello 6
Hello 10

The question says that the number corresponds to the accumulated summation over the successive indexes, but I am not really sure how to implement it into my code. I was thinking it was setting the range from 0 to 10 and trying to make a formula, but nothing has come yet. Any help would be appreciated. It has to be in a for i in range function and loop for this assignment.

for i in range(0,10,2):
    print("Hello",i)

Body:
may be this will be suitable :

i=0
step=1
while i<=10:
    print("Hello", i)
    i=i+step
    step=step+1


问:
How to call function from specific referenced DLL
I need to call a specific function from Castle.Core.dll but it seems as though AutoMapper and Moq have Castle.Core merged into their assemblies.

This is what I need to call

```<code>Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof(System.Security.Permissions.UIPermissionAttribute));
</code>```

But I get an Ambiguous reference because Castle.Core is technically available in 3 locations (AutoMapper, Moq, and the standalone DLL)

I can't simply un-ref any of the dlls because they are all managed by NuGet and Castle.Core standalone is needed for NHib and the other dlls are what were pulled in by the AutoMapper and Moq nuget packages.

Any suggestions? other then not depending on NuGet for managing my library refs?

答: You could allays call it by reflection by enumerating the types of the correct assembly. </p>

Body:
I need to call a specific function from Castle.Core.dll but it seems as though AutoMapper and Moq have Castle.Core merged into their assemblies.

This is what I need to call

Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.Add(typeof(System.Security.Permissions.UIPermissionAttribute));

But I get an Ambiguous reference because Castle.Core is technically available in 3 locations (AutoMapper, Moq, and the standalone DLL)

I can't simply un-ref any of the dlls because they are all managed by NuGet and Castle.Core standalone is needed for NHib and the other dlls are what were pulled in by the AutoMapper and Moq nuget packages.

Any suggestions? other then not depending on NuGet for managing my library refs?


问:
Setting up a PyCharm remote conda interpreter
I am trying to setup a remote conda interpreter on MacOS Mojave PyCharm for Anaconda 2019.1.2 Pro, and can't get it to work. My existing remote conda environment (v4.5.12) is running on an Ubuntu 16 EC2 machine, instantiated from Amazon's Deep Learning AMI

I tried setting up an ssh-interpreter, and directed it to: /home/ubuntu/anaconda3/envs/tensorflow_p36/bin/python which is my conda environment. I then tried running a simple Tensorflow GPU test on this interpreter and got the following message, which strongly suggest the environment was not activated: (the server's IP address and company name were purposely obfuscated)

ssh://ubuntu@xx.xx.xx.xx:22/home/ubuntu/anaconda3/envs/tensorflow_p36/bin/python -u /home/ubuntu/company/DeepLearning_copy/apps/test_gpu.py
Traceback (most recent call last):
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.10.0: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/company/DeepLearning_copy/apps/test_gpu.py", line 1, in <module>
    import tensorflow as tf
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.10.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Process finished with exit code 1
```

The code runs perfectly when SSHing into the server, running conda activate tensorflow_p36 and then python gpu_test.py.

I would appreciate any workarounds to allow remote debugging using an existing remote conda environment.
In the meantime I've opened an issue with JetBrains, and with Anaconda community group.

Edit: please see a potential workaround in the JetBrains issue page

答:
OP, it could be something that someone did to your environment that messed up the CUDA installation, like several others have mentioned.

I just provisioned a new Deep Learning AMI Instance on AWS - is this a viable option for you?

Anyway, I performed following steps after sshing to the (newly provisioned) server:

Initial activation

```<code>$ conda activate tensorflow_p36
WARNING: First activation might take some time (1+ min).
Installing TensorFlow optimized for your Amazon EC2 instance......
Env where framework will be re-installed: tensorflow_p36
Instance p2.xlarge is identified as a GPU instance, removing tensorflow-serving-cpu
Installation complete.
</code>```

Scenario 1: Running GPU test from within tensorflow_p36 conda environment:

Do this to make sure that Tensorflow is working fine as per OP's scenario.

```<code>$ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> # Creates a graph.
... a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
>>> b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
>>> c = tf.matmul(a, b)
>>> # Creates a session with log_device_placement set to True.
... sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
>>> # Runs the op.
... print(sess.run(c))
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:GPU:0
a: (Const): /job:localhost/replica:0/task:0/device:GPU:0
b: (Const): /job:localhost/replica:0/task:0/device:GPU:0
[[22. 28.]
 [49. 64.]]
</code>```

Scenario 2: Deactivating the environment, and calling the same python executable as if within the environment.

This should be the same as configuring the remote interpreter to use a particular python interpreter. Notice that there's a lot more output after sess = tf.Session(...) compared to the case above, but everything still runs ok.

```<code>$ conda deactivate
$ /home/ubuntu/anaconda3/envs/tensorflow_p36/bin/python

Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> # Creates a graph.
... a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
>>> b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
>>> c = tf.matmul(a, b)
>>> # Creates a session with log_device_placement set to True.
... sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
2019-05-31 07:14:23.840474: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:998] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-05-31 07:14:23.841300: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55ec160ca020 executing computations on platform CUDA. Devices:
2019-05-31 07:14:23.841334: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): Tesla K80, Compute Capability 3.7
2019-05-31 07:14:23.843647: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2300060000 Hz
2019-05-31 07:14:23.843845: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55ec16131af0 executing computations on platform Host. Devices:
2019-05-31 07:14:23.843870: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>
2019-05-31 07:14:23.844965: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 11.11GiB
2019-05-31 07:14:23.844992: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-31 07:14:23.845991: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-31 07:14:23.846013: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0
2019-05-31 07:14:23.846020: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N
2019-05-31 07:14:23.846577: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
2019-05-31 07:14:23.847176: I tensorflow/core/common_runtime/direct_session.cc:317] Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7

>>> # Runs the op.
... print(sess.run(c))
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:14:25.478310: I tensorflow/core/common_runtime/placer.cc:1059] MatMul: (MatMul)/job:localhost/replica:0/task:0/device:GPU:0
a: (Const): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:14:25.478383: I tensorflow/core/common_runtime/placer.cc:1059] a: (Const)/job:localhost/replica:0/task:0/device:GPU:0
b: (Const): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:14:25.478413: I tensorflow/core/common_runtime/placer.cc:1059] b: (Const)/job:localhost/replica:0/task:0/device:GPU:0
[[22. 28.]
[49. 64.]]
</code>```

Scenario 3: Now trying to use the particular conda environment interpreter as a remote interpreter using Jetbrains PyCharm, within the PyCharm Python Console

Note that the output is basically the same as in Scenario 2 above, but the Tensorflow GPU test works fine and doesn't throw any errors.

```<code>ssh://ubuntu@XX.XX.XX.XX:22/home/ubuntu/anaconda3/envs/tensorflow_p36/bin/python -u /home/ubuntu/.pycharm_helpers/pydev/pydevconsole.py --mode=server

Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
PyDev console: using IPython 6.4.0
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux

import tensorflow as tf
# Creates a graph.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(c))
2019-05-31 07:17:03.883169: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:998] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-05-31 07:17:03.883577: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55be28eef280 executing computations on platform CUDA. Devices:
2019-05-31 07:17:03.883609: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): Tesla K80, Compute Capability 3.7
2019-05-31 07:17:03.886035: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2300060000 Hz
2019-05-31 07:17:03.886752: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55be28f56d50 executing computations on platform Host. Devices:
2019-05-31 07:17:03.886777: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>
2019-05-31 07:17:03.886983: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 508.38MiB
2019-05-31 07:17:03.887009: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-31 07:17:03.887658: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-31 07:17:03.887681: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0
2019-05-31 07:17:03.887697: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N
2019-05-31 07:17:03.887881: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 283 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
2019-05-31 07:17:03.889133: I tensorflow/core/common_runtime/direct_session.cc:317] Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:17:03.890673: I tensorflow/core/common_runtime/placer.cc:1059] MatMul: (MatMul)/job:localhost/replica:0/task:0/device:GPU:0
a: (Const): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:17:03.890718: I tensorflow/core/common_runtime/placer.cc:1059] a: (Const)/job:localhost/replica:0/task:0/device:GPU:0
b: (Const): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:17:03.890750: I tensorflow/core/common_runtime/placer.cc:1059] b: (Const)/job:localhost/replica:0/task:0/device:GPU:0
[[22. 28.]
[49. 64.]]
</code>```

Body:
I am trying to setup a remote conda interpreter on MacOS Mojave PyCharm for Anaconda 2019.1.2 Pro, and can't get it to work. My existing remote conda environment (v4.5.12) is running on an Ubuntu 16 EC2 machine, instantiated from Amazon's Deep Learning AMI

I tried setting up an ssh-interpreter, and directed it to: /home/ubuntu/anaconda3/envs/tensorflow_p36/bin/python which is my conda environment. I then tried running a simple Tensorflow GPU test on this interpreter and got the following message, which strongly suggest the environment was not activated: (the server's IP address and company name were purposely obfuscated)

ssh://ubuntu@xx.xx.xx.xx:22/home/ubuntu/anaconda3/envs/tensorflow_p36/bin/python -u /home/ubuntu/company/DeepLearning_copy/apps/test_gpu.py
Traceback (most recent call last):
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.10.0: cannot open shared object file: No such file or directory

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubuntu/company/DeepLearning_copy/apps/test_gpu.py", line 1, in <module>
    import tensorflow as tf
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: libcublas.so.10.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

Process finished with exit code 1

The code runs perfectly when SSHing into the server, running conda activate tensorflow_p36 and then python gpu_test.py.

I would appreciate any workarounds to allow remote debugging using an existing remote conda environment.
In the meantime I've opened an issue with JetBrains, and with Anaconda community group.

Edit: please see a potential workaround in the JetBrains issue page

Body:
OP, it could be something that someone did to your environment that messed up the CUDA installation, like several others have mentioned.

I just provisioned a new Deep Learning AMI Instance on AWS - is this a viable option for you?

Anyway, I performed following steps after sshing to the (newly provisioned) server:

Initial activation

$ conda activate tensorflow_p36
WARNING: First activation might take some time (1+ min).
Installing TensorFlow optimized for your Amazon EC2 instance......
Env where framework will be re-installed: tensorflow_p36
Instance p2.xlarge is identified as a GPU instance, removing tensorflow-serving-cpu
Installation complete.

Scenario 1: Running GPU test from within tensorflow_p36 conda environment:

Do this to make sure that Tensorflow is working fine as per OP's scenario.

$ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> # Creates a graph.
... a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
>>> b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
>>> c = tf.matmul(a, b)
>>> # Creates a session with log_device_placement set to True.
... sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
>>> # Runs the op.
... print(sess.run(c))
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:GPU:0
a: (Const): /job:localhost/replica:0/task:0/device:GPU:0
b: (Const): /job:localhost/replica:0/task:0/device:GPU:0
[[22. 28.]
 [49. 64.]]

Scenario 2: Deactivating the environment, and calling the same python executable as if within the environment.

This should be the same as configuring the remote interpreter to use a particular python interpreter. Notice that there's a lot more output after sess = tf.Session(...) compared to the case above, but everything still runs ok.

$ conda deactivate
$ /home/ubuntu/anaconda3/envs/tensorflow_p36/bin/python

Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> # Creates a graph.
... a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
>>> b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
>>> c = tf.matmul(a, b)
>>> # Creates a session with log_device_placement set to True.
... sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
2019-05-31 07:14:23.840474: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:998] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-05-31 07:14:23.841300: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55ec160ca020 executing computations on platform CUDA. Devices:
2019-05-31 07:14:23.841334: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): Tesla K80, Compute Capability 3.7
2019-05-31 07:14:23.843647: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2300060000 Hz
2019-05-31 07:14:23.843845: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55ec16131af0 executing computations on platform Host. Devices:
2019-05-31 07:14:23.843870: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>
2019-05-31 07:14:23.844965: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 11.11GiB
2019-05-31 07:14:23.844992: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-31 07:14:23.845991: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-31 07:14:23.846013: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0
2019-05-31 07:14:23.846020: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N
2019-05-31 07:14:23.846577: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 10805 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
2019-05-31 07:14:23.847176: I tensorflow/core/common_runtime/direct_session.cc:317] Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7

>>> # Runs the op.
... print(sess.run(c))
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:14:25.478310: I tensorflow/core/common_runtime/placer.cc:1059] MatMul: (MatMul)/job:localhost/replica:0/task:0/device:GPU:0
a: (Const): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:14:25.478383: I tensorflow/core/common_runtime/placer.cc:1059] a: (Const)/job:localhost/replica:0/task:0/device:GPU:0
b: (Const): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:14:25.478413: I tensorflow/core/common_runtime/placer.cc:1059] b: (Const)/job:localhost/replica:0/task:0/device:GPU:0
[[22. 28.]
[49. 64.]]

Scenario 3: Now trying to use the particular conda environment interpreter as a remote interpreter using Jetbrains PyCharm, within the PyCharm Python Console

Note that the output is basically the same as in Scenario 2 above, but the Tensorflow GPU test works fine and doesn't throw any errors.

ssh://ubuntu@XX.XX.XX.XX:22/home/ubuntu/anaconda3/envs/tensorflow_p36/bin/python -u /home/ubuntu/.pycharm_helpers/pydev/pydevconsole.py --mode=server

Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
PyDev console: using IPython 6.4.0
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux

import tensorflow as tf
# Creates a graph.
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
print(sess.run(c))
2019-05-31 07:17:03.883169: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:998] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2019-05-31 07:17:03.883577: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55be28eef280 executing computations on platform CUDA. Devices:
2019-05-31 07:17:03.883609: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): Tesla K80, Compute Capability 3.7
2019-05-31 07:17:03.886035: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2300060000 Hz
2019-05-31 07:17:03.886752: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55be28f56d50 executing computations on platform Host. Devices:
2019-05-31 07:17:03.886777: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>
2019-05-31 07:17:03.886983: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 508.38MiB
2019-05-31 07:17:03.887009: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-05-31 07:17:03.887658: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-05-31 07:17:03.887681: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990]      0
2019-05-31 07:17:03.887697: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0:   N
2019-05-31 07:17:03.887881: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 283 MB memory) -> physical GPU (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
2019-05-31 07:17:03.889133: I tensorflow/core/common_runtime/direct_session.cc:317] Device mapping:
/job:localhost/replica:0/task:0/device:XLA_GPU:0 -> device: XLA_GPU device
/job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
/job:localhost/replica:0/task:0/device:GPU:0 -> device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:17:03.890673: I tensorflow/core/common_runtime/placer.cc:1059] MatMul: (MatMul)/job:localhost/replica:0/task:0/device:GPU:0
a: (Const): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:17:03.890718: I tensorflow/core/common_runtime/placer.cc:1059] a: (Const)/job:localhost/replica:0/task:0/device:GPU:0
b: (Const): /job:localhost/replica:0/task:0/device:GPU:0
2019-05-31 07:17:03.890750: I tensorflow/core/common_runtime/placer.cc:1059] b: (Const)/job:localhost/replica:0/task:0/device:GPU:0
[[22. 28.]
[49. 64.]]


问:
How to convert Angular locale date to proper date format for API to consume?
I am using two-way binding in my template driven form:

ts:

```<code>searchLeaveApplication: any = {};
</code>```

html:

```<code><mat-form-field class="searchInputs">
  <input
    matInput
    [matDatepicker]="searchStartDate"
    [(ngModel)]="this.searchLeaveApplication.startDate"
    name="startDate"
  />
  <mat-datepicker-toggle
    matSuffix
    [for]="searchStartDate"
  ></mat-datepicker-toggle>
  <mat-datepicker #searchStartDate></mat-datepicker>
</mat-form-field>
</code>```

However I am getting this as the date:

Which is not acceptable as a date format for the API (.Net core). How can I change to format to the proper date format? I suppose I am not able to use date pipes in two-way bindings.

答:
You can always import Angular's DatePipe, or FormatDate into your component.ts, and convert searchLeaveApplication.startDate to the required datetime format that is accepted by .Net core. The full list of pre-defined options and custom formats can be found here.

1) If you are intending to use DatePipe, you may do the following below.

```<code>import { DatePipe } from '@angular/common';

export class SampleComponent implements OnInit {

constructor(private datePipe: DatePipe) {}

  saveData() {
    const searchStartDateString = this.datePipe.transform(this.searchLeaveApplication.startDate, 'yyyy-MM-dd');
    // handle the rest
  }
}
</code>```

Do not forget to add DatePipe to your providers in your module.

```<code>providers: [DatePipe]
</code>```

2) Alternatively, you may want to use formatDate:

```<code>import { formatDate } from '@angular/common';

export class SampleComponent implements OnInit {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  saveData() {
    const searchStartDateString = formatDate(this.searchLeaveApplication.startDate, 'MM-yyyy', this.locale);
    // handle the rest
  }
}
</code>```

Body:
I am using two-way binding in my template driven form:

ts:

searchLeaveApplication: any = {};

html:

<mat-form-field class="searchInputs">
  <input
    matInput
    [matDatepicker]="searchStartDate"
    [(ngModel)]="this.searchLeaveApplication.startDate"
    name="startDate"
  />
  <mat-datepicker-toggle
    matSuffix
    [for]="searchStartDate"
  ></mat-datepicker-toggle>
  <mat-datepicker #searchStartDate></mat-datepicker>
</mat-form-field>

However I am getting this as the date:

Which is not acceptable as a date format for the API (.Net core). How can I change to format to the proper date format? I suppose I am not able to use date pipes in two-way bindings.

Body:
You can always import Angular's DatePipe, or FormatDate into your component.ts, and convert searchLeaveApplication.startDate to the required datetime format that is accepted by .Net core. The full list of pre-defined options and custom formats can be found here.

1) If you are intending to use DatePipe, you may do the following below.

import { DatePipe } from '@angular/common';

export class SampleComponent implements OnInit {

constructor(private datePipe: DatePipe) {}

  saveData() {
    const searchStartDateString = this.datePipe.transform(this.searchLeaveApplication.startDate, 'yyyy-MM-dd');
    // handle the rest
  }
}

Do not forget to add DatePipe to your providers in your module.

providers: [DatePipe]

2) Alternatively, you may want to use formatDate:

import { formatDate } from '@angular/common';

export class SampleComponent implements OnInit {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  saveData() {
    const searchStartDateString = formatDate(this.searchLeaveApplication.startDate, 'MM-yyyy', this.locale);
    // handle the rest
  }
}