问:
Accessing Returned Values From JavaScript Function Causes HTML Page to Reload
When the form is submitted the function buttonClicked() is run. This function runs callGeoCode() which gets the latitude and longitude information for whatever the user typed in the form. Whenever I click the button to submit the form the page reloads. However when I comment out the console.log(location.lat+','+location.lng); line the page doesn't reload. Why would this be? I can't seem to figure it out.

```<code>$('#find-location').submit(function () {
     buttonClicked();
     return false;
});
function buttonClicked() {
    userInput = document.getElementById("locationInput").value;
    var location = callGeoCode(userInput);
    console.log(location.lat+','+location.lng);
}
function callGeoCode(userInput) {
    $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + userInput + '&key=APIKEY-GOES-HERE',
        function(data) {
            if (data.status === 'OK') {
                var lat = data.results[0].geometry.location.lat;
                var lng = data.results[0].geometry.location.lng;
                return {lat: lat, lng: lng};
            } else {
                return 'FAILED';
            }
        }
    );
}
</code>```

答:
Try this:-

```<code>$('#find-location').submit(function (event) {
     event.preventDefault();
     buttonClicked();
     return false;
});
</code>```

For geocode api you can try something like

```<code>function buttonClicked() {
    userInput = document.getElementById("locationInput").value;
    var locationPromise = callGeoCode(userInput);
    locationPromise.done(function( data ) {
        console.log(data);
        if (data.status === 'OK') {
            var lat = data.results[0].geometry.location.lat;
            var lng = data.results[0].geometry.location.lng;
            console.log("lat:" + lat + "long:" + long);
        }
    }
}

function callGeoCode(userInput) {
    return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + userInput + '&key=APIKEY-GOES-HERE');
}
</code>```

Body:
When the form is submitted the function buttonClicked() is run. This function runs callGeoCode() which gets the latitude and longitude information for whatever the user typed in the form. Whenever I click the button to submit the form the page reloads. However when I comment out the console.log(location.lat+','+location.lng); line the page doesn't reload. Why would this be? I can't seem to figure it out.

$('#find-location').submit(function () {
     buttonClicked();
     return false;
});
function buttonClicked() {
    userInput = document.getElementById("locationInput").value;
    var location = callGeoCode(userInput);
    console.log(location.lat+','+location.lng);
}
function callGeoCode(userInput) {
    $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + userInput + '&key=APIKEY-GOES-HERE',
        function(data) {
            if (data.status === 'OK') {
                var lat = data.results[0].geometry.location.lat;
                var lng = data.results[0].geometry.location.lng;
                return {lat: lat, lng: lng};
            } else {
                return 'FAILED';
            }
        }
    );
}

Body:
Try this:-

$('#find-location').submit(function (event) {
     event.preventDefault();
     buttonClicked();
     return false;
});

For geocode api you can try something like

function buttonClicked() {
    userInput = document.getElementById("locationInput").value;
    var locationPromise = callGeoCode(userInput);
    locationPromise.done(function( data ) {
        console.log(data);
        if (data.status === 'OK') {
            var lat = data.results[0].geometry.location.lat;
            var lng = data.results[0].geometry.location.lng;
            console.log("lat:" + lat + "long:" + long);
        }
    }
}

function callGeoCode(userInput) {
    return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + userInput + '&key=APIKEY-GOES-HERE');
}


来源: stackexchange

问:
Android ConstraintLayout - Put one view on top of another view
I'm trying to add a ProgressBar on top of a Button (both are inside a ConstraintLayout).

```<code><Button
    android:id="@+id/sign_in_button"
    android:layout_width="280dp"
    android:layout_height="75dp"
    android:layout_marginBottom="75dp"
    android:layout_marginTop="50dp"
    android:text="@string/sign_in"
    android:textColor="@color/white"
    android:textSize="22sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/passwordEditText"
    app:layout_constraintVertical_bias="0.0"/>

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="@+id/sign_in_button"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="@+id/sign_in_button"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.5"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="@+id/sign_in_button"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="@+id/sign_in_button"/>
</code>```

But even after calling bringToFront on the ProgressBar in onCreate, it always stays behind the Button.

```<code>ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar);
progressBar.bringToFront();
</code>```

答:
Set an elevation on the ProgressBar; 2dp seems to work.

```<code>android:elevation="2dp"
</code>```

You could also try setting translationZ as suggested in the accepted answer to a similar question.

I also came across this answer as an alternative.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to add a ProgressBar on top of a Button (both are inside a ConstraintLayout).

<Button
    android:id="@+id/sign_in_button"
    android:layout_width="280dp"
    android:layout_height="75dp"
    android:layout_marginBottom="75dp"
    android:layout_marginTop="50dp"
    android:text="@string/sign_in"
    android:textColor="@color/white"
    android:textSize="22sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/passwordEditText"
    app:layout_constraintVertical_bias="0.0"/>

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="@+id/sign_in_button"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="@+id/sign_in_button"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.5"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="@+id/sign_in_button"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="@+id/sign_in_button"/>

But even after calling bringToFront on the ProgressBar in onCreate, it always stays behind the Button.

ProgressBar progressBar = (ProgressBar)findViewById(R.id.progressBar);
progressBar.bringToFront();

Body:
Set an elevation on the ProgressBar; 2dp seems to work.

android:elevation="2dp"

You could also try setting translationZ as suggested in the accepted answer to a similar question.

I also came across this answer as an alternative.


问:
Make simply HTTP request and receive the content
I have found a working code for makeing simply HTTP requests here, from How can I make a simple HTTP request in MainActivity.java? (Android Studio) and I am going to post it below (with some changes, if I am not wrong it is now necessery to use try{} catch{}). But I would like to ask how I can receive the content? I work with the code in the following way:

```<code>GetUrlContentTask req = new GetUrlContentTask();
req.execute("http://192.168.1.10/?pin=OFF1");
textView3.setText(req.doInBackground("http://192.168.1.10/?pin=OFF1"));
</code>```

GetUrlContentTask

```<code>private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
    protected String doInBackground(String... urls) {
        // String content1 = "";
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();

            BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String content = "", line;
            while ((line = rd.readLine()) != null) {
                content += line + "\n";
            }
            // content1 = content;
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        // return content1; - returns "", wrong
        return "aaa";
        //does not work    return content;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(String result) {
        // this is executed on the main thread after the process is over
        // update your UI here
    }
}
</code>```

答:
Where exactly are you stuck?  Your code mostly correct although you may need to rearrange it slightly.  Your scope is a bit off and your commented code almost gets there.  See below

```<code>protected String doInBackground(String... urls) {
    String content = "", line = "";
    HttpURLConnection httpURLConnection;
    BufferedReader bufferedReader;
    URL url;

    try {
        for(String uri : urls) {
            url = new URL(uri);
            url = new URI(url.toURI().getScheme(), url.getAuthority(), url.getPath(), "pin=" + URLEncoder.encode("&OFF1", "UTF-8"), null).toURL();

            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();

            bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            while ((line = bufferedReader.readLine()) != null) {
                content += line + System.lineSeparator();
            }
        }
     } catch (Exception e) {
         e.printStackTrace();
     } finally {
         try {
            bufferedReader.close();
         } catch(Exception e) {
             e.printStackTrace();
         }
     }

     return content;

}
</code>```

That will return a String representation of your page.  If the page contains HTML it will return text/html, if it contains text it will return just text.

Then as a previous user stated you can set the response on your GUI

```<code>protected void onPostExecute(String result) {
    textView3.setText(result);
}
</code>```

The above example will technically work.  However, I would highly recommend using http://loopj.com/android-async-http/ over HttpURLConnection.  Your code will be much nicer which will matter down the line.

The code I sent you assumes that the parameter is always pin=OFF1 because it's more a proof of concept

Body:
I have found a working code for makeing simply HTTP requests here, from How can I make a simple HTTP request in MainActivity.java? (Android Studio) and I am going to post it below (with some changes, if I am not wrong it is now necessery to use try{} catch{}). But I would like to ask how I can receive the content? I work with the code in the following way:

GetUrlContentTask req = new GetUrlContentTask();
req.execute("http://192.168.1.10/?pin=OFF1");
textView3.setText(req.doInBackground("http://192.168.1.10/?pin=OFF1"));

GetUrlContentTask

private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
    protected String doInBackground(String... urls) {
        // String content1 = "";
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();

            BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String content = "", line;
            while ((line = rd.readLine()) != null) {
                content += line + "\n";
            }
            // content1 = content;
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        // return content1; - returns "", wrong
        return "aaa";
        //does not work    return content;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(String result) {
        // this is executed on the main thread after the process is over
        // update your UI here
    }
}

Body:
Where exactly are you stuck?  Your code mostly correct although you may need to rearrange it slightly.  Your scope is a bit off and your commented code almost gets there.  See below

protected String doInBackground(String... urls) {
    String content = "", line = "";
    HttpURLConnection httpURLConnection;
    BufferedReader bufferedReader;
    URL url;

    try {
        for(String uri : urls) {
            url = new URL(uri);
            url = new URI(url.toURI().getScheme(), url.getAuthority(), url.getPath(), "pin=" + URLEncoder.encode("&OFF1", "UTF-8"), null).toURL();

            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();

            bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            while ((line = bufferedReader.readLine()) != null) {
                content += line + System.lineSeparator();
            }
        }
     } catch (Exception e) {
         e.printStackTrace();
     } finally {
         try {
            bufferedReader.close();
         } catch(Exception e) {
             e.printStackTrace();
         }
     }

     return content;

}

That will return a String representation of your page.  If the page contains HTML it will return text/html, if it contains text it will return just text.

Then as a previous user stated you can set the response on your GUI

protected void onPostExecute(String result) {
    textView3.setText(result);
}

The above example will technically work.  However, I would highly recommend using http://loopj.com/android-async-http/ over HttpURLConnection.  Your code will be much nicer which will matter down the line.

The code I sent you assumes that the parameter is always pin=OFF1 because it's more a proof of concept


问:
Text and image height do not match
Text and image height do not match, after refresh - all is well.
Thank you for your help!

CodePen

$(document).ready(function() {
  $(window).resize(function() {
    processPost();
  });

  function processPost() {
    $('.post').each(function(i, e) {
      $image = $(e).children('.post-image'),
        $data = $(e).children('.post-data');
      $image.css({
        'background-image': isExist($image.attr('image-url')),
        'height': $data.height(),
      });
    });
  }
  processPost();

  function isExist(data) {
    return `url(${ (data !== undefined && data !== '') ? data : '/data/no-photo.jpg' })`;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.post {
  display: table;
  margin: 4% 2%;
  padding: .6em 1em;
  background-color: #fefefe;
  border-radius: 2px;
}
.post-cell, .post-image, .post-data {
  display: inline-table;
}
.post-cell {
  width: 100%;
}
.post-cell h4, .post-cell p {
  margin: 0;
  padding: .2em 0;
}
.post-cell h4 {
  font-size: 1.5em;
}
.post-cell p {
  color: #d7d7d7;
}
.post-image {
  float: left;
  width: 39%;
  background-size: cover;
  background-position: center;
  border-radius: 2px;
  min-height: 100px;
  max-height: 300px;
}
.post-data {
  padding-left: 2%;
  width: 59%;
}
.post-data p {
  margin: 0;
}
.text-right {
  text-align: right !important;
}</code>```

Heading

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

meta, tag, metatag, meta-tag

```

Screenshot:
[Image Height: 175px, Post Height: 200px]

答: for the record, in your CSS you have 'min-height: 100px;' which is overriding your javascript!</p>

Title: Text and image height do not match

Body:
Text and image height do not match, after refresh - all is well.
Thank you for your help!

CodePen

$(document).ready(function() {
  $(window).resize(function() {
    processPost();
  });

  function processPost() {
    $('.post').each(function(i, e) {
      $image = $(e).children('.post-image'),
        $data = $(e).children('.post-data');
      $image.css({
        'background-image': isExist($image.attr('image-url')),
        'height': $data.height(),
      });
    });
  }
  processPost();

  function isExist(data) {
    return `url(${ (data !== undefined && data !== '') ? data : '/data/no-photo.jpg' })`;
  }
});

.post {
  display: table;
  margin: 4% 2%;
  padding: .6em 1em;
  background-color: #fefefe;
  border-radius: 2px;
}
.post-cell, .post-image, .post-data {
  display: inline-table;
}
.post-cell {
  width: 100%;
}
.post-cell h4, .post-cell p {
  margin: 0;
  padding: .2em 0;
}
.post-cell h4 {
  font-size: 1.5em;
}
.post-cell p {
  color: #d7d7d7;
}
.post-image {
  float: left;
  width: 39%;
  background-size: cover;
  background-position: center;
  border-radius: 2px;
  min-height: 100px;
  max-height: 300px;
}
.post-data {
  padding-left: 2%;
  width: 59%;
}
.post-data p {
  margin: 0;
}
.text-right {
  text-align: right !important;
}

Heading

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

meta, tag, metatag, meta-tag

Screenshot:
[Image Height: 175px, Post Height: 200px]


问:
Read a file out of an android application
I need to place a file on a specific folder, so that my application can read it. First i want to try to create a new file with a specific path, but anyway i try, on the android dev tool on eclipse, I have an IOException.
Do you know a way to create "helloworld.txt"  - For example - on the virtual device?

Thanks.

PS: I tried "new File(Environment.get..., "helloworld.txt").mkdirs();", and stuffs like that

答:
You can not access system folder by using android app.You need to transfer the file from your system to Android Emulator's Virtual SD Card by using file explorer availble with ADT plugin for android in eclipse.
Open file explorer in eclipse and import the file to device.</p>

ContentLicense: CC BY-SA 2.5


问:
Web service task throwing an error on 2015 data tools
I am trying to run a simple web service task and successfully downloaded wsdl file and configured for run. Although it is the only task in the package.

Error :

[Web Service Task] Error: An error occurred with the following error
  message:
  Microsoft.SqlServer.Dts.Tasks.WebServiceTask.WebserviceTaskException:
  Could not execute the Web method.

  The error is: Could not load file or assembly

   Microsoft.SqlServer.WebServiceTask, Version=14.100.0.0,
  Culture=neutral, PublicKeyToken=89845dcd8080cc91 or one of its
  dependencies.

  The system cannot find the file specified..  at
  Microsoft.SqlServer.Dts.Tasks.WebServiceTask.WebServiceTaskUtil.Invoke(DTSWebMethodInfo
  methodInfo, String serviceName, Object connection, VariableDispenser
  taskVariableDispenser) at

  Microsoft.SqlServer.Dts.Tasks.WebServiceTask.WebServiceTask.executeThread().

Please help to resolve it... Thanks in advance!!!

Installation order

SQL Server 2016

Data Tools 2015 shell

Visual Studio 2017 community

Do i need 2015 visual studio to run 2015 data tools ?

答:
Look like the error are thrown because the package are using sql server 2017 assemblies which is not installed. (Microsoft.SqlServer.WebServiceTask, Version=14.100.0.0,)

This maybe caused during upgrade procedure.

Try changing the deployment target to sql server 2016.

Read more in this article:

https://www.mssqltips.com/sqlservertip/4253/backwards-compatibility-in-sql-server-data-tools-for-integration-services/

Also check this link:

Could not load file or assembly error in SSIS Web Service Task


问:
Android In-app Billing and Proguard (Unknown Source)
I am using the In-app Billing service of Google and Proguard. The configuration file that I am using as a Proguard is the one in .../sdk/tools/proguard/proguard-android.txt

As Google says here: http://developer.android.com/google/play/billing/billing_best_practices.html I added the following line in the configuration file:

```<code>-keep class com.android.vending.billing.**
</code>```

I am using the updated files of IAB from Google as well: https://code.google.com/p/marketbilling/source/detail?r=7ec85a9b619fc5f85023bc8125e7e6b1ab4dd69f

The problem is that sometimes, users report random crashes with this stacktrace:

```<code>E/AndroidRuntime: FATAL EXCEPTION: Thread-455
java.lang.NullPointerException
    at com.xx.xxxx.util.IabHelper.startSetup(Unknown Source)
    at com.xx.xxxx.util.IabHelper$2.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:856)
</code>```

It also happened in my device (just opening the app) but only happened once to me today.

And I am not sure if it is problems of Google files (of IAB) or something is missing in the Proguard configuration file.

答:
This worked for me </p>

```<code>-keep class com.android.vending.** { *; }
</code>```

Body:
I am using the In-app Billing service of Google and Proguard. The configuration file that I am using as a Proguard is the one in .../sdk/tools/proguard/proguard-android.txt

As Google says here: http://developer.android.com/google/play/billing/billing_best_practices.html I added the following line in the configuration file:

-keep class com.android.vending.billing.**

I am using the updated files of IAB from Google as well: https://code.google.com/p/marketbilling/source/detail?r=7ec85a9b619fc5f85023bc8125e7e6b1ab4dd69f

The problem is that sometimes, users report random crashes with this stacktrace:

E/AndroidRuntime: FATAL EXCEPTION: Thread-455
java.lang.NullPointerException
    at com.xx.xxxx.util.IabHelper.startSetup(Unknown Source)
    at com.xx.xxxx.util.IabHelper$2.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:856)

It also happened in my device (just opening the app) but only happened once to me today.

And I am not sure if it is problems of Google files (of IAB) or something is missing in the Proguard configuration file.

Body:
This worked for me

-keep class com.android.vending.** { *; }


问:
Lose data in long strings when transfering values using ranges
So, I'm working on a project and at one point I copy data from one workbook to another by setting a range on the one workbook and then setting the range on the destination workbook equal to it. This works great in general, but I have one field that under some circumstances has data that is five digit numbers separated by commas. Zip codes essentially, separated by commas and possibly spaces as well. (Although there aren't supposed to be spaces in that data it is very possible that there are.)

So for example the cell being copied will look like this:
11111,22222,33333,44444,55555,66666,77777,88888,99999

and will transfer as this:
1.11112222233333E+44 or
111,112,222,233,333,000,000,000,000,000,000,000,000,000,000

This is obviously not what I want. How do I fix this?

Here is the relevant code. The column that has the problem data is column F of the Service Areas worksheet.

```<code>Dim MainWB As Workbook
Set MainWB = Workbooks("SATemplate Data Compile.xlsm")
Dim MDSAT As Range

'Setting the range I want to transfer
Set MDSAT = wb.Worksheets("Service Areas").Range("A13:G13", wb.Worksheets("Service Areas").Range("A13:G13").End(xlDown).End(xlDown).End(xlUp))

'Transferring the range values
MainWB.Sheets("SATemplates").Range("A" & Rows.count).End(xlUp).Offset(1).Resize(MDSAT.Rows.count, MDSAT.Columns.count).Cells.Value = MDSAT.Cells.Value
</code>```

Is this a problem with setting the new range equal to the cell values? Would I have to split this up into multiple parts so that a different range will grab the data in column F?

答:
Try this (to force as values (text)):</p>

```<code>With MainWB.Sheets("SATemplates").Range("A" & Rows.count).End(xlUp).Offset(1).Resize(MDSAT.Rows.count, MDSAT.Columns.count)
    .NumberFormat = "@" 'format as text
    .Value = MDSAT.Value
End With
</code>```

Body:
So, I'm working on a project and at one point I copy data from one workbook to another by setting a range on the one workbook and then setting the range on the destination workbook equal to it. This works great in general, but I have one field that under some circumstances has data that is five digit numbers separated by commas. Zip codes essentially, separated by commas and possibly spaces as well. (Although there aren't supposed to be spaces in that data it is very possible that there are.)

So for example the cell being copied will look like this:
11111,22222,33333,44444,55555,66666,77777,88888,99999

and will transfer as this:
1.11112222233333E+44 or
111,112,222,233,333,000,000,000,000,000,000,000,000,000,000

This is obviously not what I want. How do I fix this?

Here is the relevant code. The column that has the problem data is column F of the Service Areas worksheet.

Dim MainWB As Workbook
Set MainWB = Workbooks("SATemplate Data Compile.xlsm")
Dim MDSAT As Range

'Setting the range I want to transfer
Set MDSAT = wb.Worksheets("Service Areas").Range("A13:G13", wb.Worksheets("Service Areas").Range("A13:G13").End(xlDown).End(xlDown).End(xlUp))

'Transferring the range values
MainWB.Sheets("SATemplates").Range("A" & Rows.count).End(xlUp).Offset(1).Resize(MDSAT.Rows.count, MDSAT.Columns.count).Cells.Value = MDSAT.Cells.Value

Is this a problem with setting the new range equal to the cell values? Would I have to split this up into multiple parts so that a different range will grab the data in column F?

Body:
Try this (to force as values (text)):

With MainWB.Sheets("SATemplates").Range("A" & Rows.count).End(xlUp).Offset(1).Resize(MDSAT.Rows.count, MDSAT.Columns.count)
    .NumberFormat = "@" 'format as text
    .Value = MDSAT.Value
End With


问:
What's the best strategy for get/setting metadata on Ruby methods at runtime?
I have a class with some methods. It's supersekret but I've reproduced what I can here.

```<code>Class RayGun
  # flashes red light
  # requires confirmation
  # makes "zowowowowowow" sound
  def stun!
    # ...
  end

  # flashes blue light
  # does not require confirmation
  # makes "trrrtrtrtrrtrtrtrtrtrtr" sound
  def freeze!
    # ...
  end

  # doesn't flash any lights
  # does not require confirmation
  # makes Windows startup sound
  def killoblast!
    # ...
  end
end
</code>```

I want to be able to, at runtime, interrogate the class about one of the methods and receive a hash or struct like so:

```<code>  {:lights => 'red', :confirmation => false, :sound => 'windows'}
</code>```

What's the best way of doing this? Obviously you could have separate YAML file alongside and set up a convention to relate the two, but ideally I want code and metadata in one place.

The most promising idea I can come up with is something like this:

```<code>class RayGun
  cattr_accessor :metadata
  def self.register_method(hsh)
    define_method(hsh.name, hsh.block)
    metadata[hsh[:name]] = hsh
  end

  register_method({
    :name => 'stun!',
    :lights => 'red',
    :confirmation => 'true',
    :sound => 'zowowo',
    :block => Proc.new do
      # code goes here
   })

   # etc.
end
</code>```

Anyone got some better ideas? Am I barking up a very wrong tree?

答:
Just a little beautyfication:

```<code>class RayGun
  cattr_accessor :metadata
  def self.register_method(name, hsh, &block)
    define_method(name, block)
    metadata[name] = hsh
  end

  register_method( 'stun!',
    :lights => 'red',
    :confirmation => 'true',
    :sound => 'zowowo',
    ) do
      # code goes here
  end

   # etc.
end
</code>```

You do lose easy access to the original closure, but probably don't need it.

To answer the question, it doesn't look bad, you could do something a little more convetional but probably good enough:

```<code>class RayGun
  cattr_accessor :metadata

  @metadata[:stun!] = {:lights => 'red',
                        :confirmation => 'true',
                        :sound => 'zowowo'}
  def stun!
    # ...
  end

   # etc.
end
</code>```

In the original example register_method is public, if you planned to use it that way then the second option becomes less usefull because it doesn't ensure consistency.

OwnerDisplayName: EmbiggensTheMind

Body:
I have a class with some methods. It's supersekret but I've reproduced what I can here.

Class RayGun
  # flashes red light
  # requires confirmation
  # makes "zowowowowowow" sound
  def stun!
    # ...
  end

  # flashes blue light
  # does not require confirmation
  # makes "trrrtrtrtrrtrtrtrtrtrtr" sound
  def freeze!
    # ...
  end

  # doesn't flash any lights
  # does not require confirmation
  # makes Windows startup sound
  def killoblast!
    # ...
  end
end

I want to be able to, at runtime, interrogate the class about one of the methods and receive a hash or struct like so:

  {:lights => 'red', :confirmation => false, :sound => 'windows'}

What's the best way of doing this? Obviously you could have separate YAML file alongside and set up a convention to relate the two, but ideally I want code and metadata in one place.

The most promising idea I can come up with is something like this:

class RayGun
  cattr_accessor :metadata
  def self.register_method(hsh)
    define_method(hsh.name, hsh.block)
    metadata[hsh[:name]] = hsh
  end

  register_method({
    :name => 'stun!',
    :lights => 'red',
    :confirmation => 'true',
    :sound => 'zowowo',
    :block => Proc.new do
      # code goes here
   })

   # etc.
end

Anyone got some better ideas? Am I barking up a very wrong tree?

Body:
Just a little beautyfication:

class RayGun
  cattr_accessor :metadata
  def self.register_method(name, hsh, &block)
    define_method(name, block)
    metadata[name] = hsh
  end

  register_method( 'stun!',
    :lights => 'red',
    :confirmation => 'true',
    :sound => 'zowowo',
    ) do
      # code goes here
  end

   # etc.
end

You do lose easy access to the original closure, but probably don't need it.

To answer the question, it doesn't look bad, you could do something a little more convetional but probably good enough:

class RayGun
  cattr_accessor :metadata

  @metadata[:stun!] = {:lights => 'red',
                        :confirmation => 'true',
                        :sound => 'zowowo'}
  def stun!
    # ...
  end

   # etc.
end

In the original example register_method is public, if you planned to use it that way then the second option becomes less usefull because it doesn't ensure consistency.


问:
What is the difference between using class and struct with Dictionary.ContainsKey()?
Below is a sample of my dictionary definition.  When I define DicKeys as a class, ContainsKey() doesn't work.  If I change DicKeys to a struct, it works properly.

Why does ContainsKey() work differently for a class than it does for a struct?

```<code>Dictionary<DicKeys, DicVals> aDic = new Dictionary<DicKeys, DicVals>();

// original version as below
public Class DicKeys
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

// revised version as below
public struct DicKeys
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

// common parts of code below
public enum EnKey1
{
   A1,
   A2,
}

public enum EnKey2
{
   B11,
   B12,
}

DicKeys aDicKey = new DicKeys();
// assigned value to aDicKey obj here;

if (aDic.ContainsKey(aDicKey ) == true)
{
 // do some thing here
 // If I defined as 'class', it doesn't hit here.
 // Updated to 'struct', it hit here.
}
</code>```

答:
Well, you haven't shown where you're populating the dictionary or what sfTKey is... but I strongly suspect it's because you haven't overridden Equals or GetHashCode in DicKeys.

By default, classes use reference identity for equality - in other words, two key references will only compare as equal if they refer to the exact same object. You can override Equals and GetHashCode to provide equality based on the contents of the objects though. Value types (structs) automatically use value-based equality, but I certainly wouldn't recommend using a mutable struct as you've got here. (I wouldn't recommend using public fields at all, to be honest.)

See this question for an example of the kind of thing you might do in Equals and GetHashCode - and some other members you may want to provide on types which have value-based equality.

Body:
Below is a sample of my dictionary definition.  When I define DicKeys as a class, ContainsKey() doesn't work.  If I change DicKeys to a struct, it works properly.

Why does ContainsKey() work differently for a class than it does for a struct?

Dictionary<DicKeys, DicVals> aDic = new Dictionary<DicKeys, DicVals>();

// original version as below
public Class DicKeys
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

// revised version as below
public struct DicKeys
{
   public EnKey1 DicKeyItem1,
   public EnKey2 DicKeyItem2,
}

// common parts of code below
public enum EnKey1
{
   A1,
   A2,
}

public enum EnKey2
{
   B11,
   B12,
}

DicKeys aDicKey = new DicKeys();
// assigned value to aDicKey obj here;

if (aDic.ContainsKey(aDicKey ) == true)
{
 // do some thing here
 // If I defined as 'class', it doesn't hit here.
 // Updated to 'struct', it hit here.
}


问:
How to remove the hash # from the angularjs ng-route
I am trying to use the locationProvider to remove the hashtag from the url routes in angular js but it gives me error.

app.js

```<code>var eclassApp = angular.module('eclassApp',
    ['ngRoute', 'eclassControllers', ]
);

eclassApp.config(['$routeProvider','$locationProvider',
    function ($routeProvider, $locationProvider){
        $routeProvider.
            when('/',{
                templateUrl: '/html/student-list.html',
                controller: 'StudentsListCtrl',
            }).
            when('/students/:studentId',{
                templateUrl: '/html/student-details.html',
                controller: 'StudentDetailsCtrl',

            }).otherwise({
                redirectTo: '/students'
            });
            $locationProvider.htmlMode(true);
    }]
);
</code>```

the error:

```<code> Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=eclassApp&p1=TypeE…oogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.13%2Fangular.min.js%3A17%3A1)
</code>```

Am I missing something?

EDIT: calling the html5Mode function with options object like this

```<code>$locationProvider.html5Mode({
    enabled:true
})
</code>```

i get the following error (changed to angular full to get a better explanation of the error istead of the minified version)

```<code>Error: [$location:nobase] $location in HTML5 mode requires a <base> tag to be present!
</code>```

http://errors.angularjs.org/1.3.13/$location/nobase

答:
Tested on Angular 1.6.1 version:

It requires 3 steps to remove the hashtag (#) from URL.

Step 1: enable html5mode on locationProvider through Config. sample code:

```<code>app.config(function($locationProvider, $routeProvider){
            $locationProvider.html5Mode(true);
            $routeProvider.when('/', {templateUrl: 'partials/home.html'}).when('/info', {templateUrl: 'partials/info.html'});
        });
</code>```

Step 2: provide a base href attribute in the head section of index.html. This should be placed on top of all script and CSS tags. the href attributes defines the relative path of your project. sample code: base href="/demo/". My demo application sits on root directory of Apache web server. If your application is a sub-directory, use: base href="/demo/sub-directory/" or base href="http://localhost/demo/sub-directory/"

Step 3: If you're running this AngularJS application on Apache server (Wamp, Mamp etc): from other StackOverflow posts, you should enable url-rewrite module. As of Apache version 2.2+, this can be achieved by using command: FallbackResource. Sample code: create an .htaccess file on root directory of Apache server. Add the below command and restart the server. Provide the relative path index.html which handles the 404 error caused due angular-route functionality. This should solve refresh/accessing deep-url's and all 404 errors.

```<code>FallbackResource /demo/sub-directory/index.html
</code>```

Body:
I am trying to use the locationProvider to remove the hashtag from the url routes in angular js but it gives me error.

app.js

var eclassApp = angular.module('eclassApp',
    ['ngRoute', 'eclassControllers', ]
);

eclassApp.config(['$routeProvider','$locationProvider',
    function ($routeProvider, $locationProvider){
        $routeProvider.
            when('/',{
                templateUrl: '/html/student-list.html',
                controller: 'StudentsListCtrl',
            }).
            when('/students/:studentId',{
                templateUrl: '/html/student-details.html',
                controller: 'StudentDetailsCtrl',

            }).otherwise({
                redirectTo: '/students'
            });
            $locationProvider.htmlMode(true);
    }]
);

the error:

 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=eclassApp&p1=TypeE…oogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.13%2Fangular.min.js%3A17%3A1)

Am I missing something?

EDIT: calling the html5Mode function with options object like this

$locationProvider.html5Mode({
    enabled:true
})

i get the following error (changed to angular full to get a better explanation of the error istead of the minified version)

Error: [$location:nobase] $location in HTML5 mode requires a <base> tag to be present!

http://errors.angularjs.org/1.3.13/$location/nobase

Body:
Tested on Angular 1.6.1 version:

It requires 3 steps to remove the hashtag (#) from URL.

Step 1: enable html5mode on locationProvider through Config. sample code:

app.config(function($locationProvider, $routeProvider){
            $locationProvider.html5Mode(true);
            $routeProvider.when('/', {templateUrl: 'partials/home.html'}).when('/info', {templateUrl: 'partials/info.html'});
        });

Step 2: provide a base href attribute in the head section of index.html. This should be placed on top of all script and CSS tags. the href attributes defines the relative path of your project. sample code: base href="/demo/". My demo application sits on root directory of Apache web server. If your application is a sub-directory, use: base href="/demo/sub-directory/" or base href="http://localhost/demo/sub-directory/"

Step 3: If you're running this AngularJS application on Apache server (Wamp, Mamp etc): from other StackOverflow posts, you should enable url-rewrite module. As of Apache version 2.2+, this can be achieved by using command: FallbackResource. Sample code: create an .htaccess file on root directory of Apache server. Add the below command and restart the server. Provide the relative path index.html which handles the 404 error caused due angular-route functionality. This should solve refresh/accessing deep-url's and all 404 errors.

FallbackResource /demo/sub-directory/index.html


答:
Because your for-each loop is staring inside the <NRG_FCAST_DTL> element, you need to select the sibling element using ... This works for me:

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
    <xsl:template match="/">
        <xsl:text>GAS_DAY,CRT_DT,CRT_TM,TOT_FCAST,CNG_SNCE_LST_NM,NA_RNM_UPDTD
</xsl:text>
        <xsl:for-each select="//DTL/NRG_FCAST_DTL">
            <xsl:value-of select="concat(../../SHPR_TOT_NRG_FCAST_QRY/GAS_DAY,',',CRT_DT, ',' ,CRT_TM,',' ,TOT_FCAST,',' ,CNG_SNCE_LST_NM,',' ,NA_RNM_UPDTD, '
')"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

Title: XML to CSV using XSLT help required

Body:
I am trying to convert xml to csv. Please help me to get correct XSL file

Output I am looking as (csv)==>

GAS_DAY     CRT_DT      CRT_TM     TOT_FCAST    CNG_SNCE_LST_NM  NA_RNM_UPDTD
10/02/2017  09/02/2017  11:01:21    13847690    99                 Y
10/02/2017  09/02/2017  13:01:59    13780670    -0.5               Y
10/02/2017  09/02/2017  16:01:03    13889719    0.8                Y
10/02/2017  10/02/2017  00:01:07    13862376    -0.2               Y
10/02/2017  10/02/2017  10:01:01    13679133    -1.3               Y
11/02/2017  10/02/2017  11:01:21    338473240   99                 Y
11/02/2017  10/02/2017  13:01:59    13780670    10.5               Y
11/02/2017  10/02/2017  16:01:03    23889719    3.8                Y
11/02/2017  11/02/2017  00:01:07    13432376    10.2               Y
11/02/2017  11/02/2017  10:01:01    13432133    -1.3               Y

Sample XML ==>

<root>
    <SHPR_TOT_NRG_FCAST_OUT>
        <METADATA>
            <TMSTMP>2017-02-10T10:15:44</TMSTMP>
        </METADATA>
        <SHPR_TOT_NRG_FCAST_QRY>
            <GAS_DAY>2017-02-10</GAS_DAY>
        </SHPR_TOT_NRG_FCAST_QRY>
        <DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-09</CRT_DT>
                <CRT_TM>11:01:21</CRT_TM>
                <TOT_FCAST>13847690</TOT_FCAST>
                <CNG_SNCE_LST_NM>99.0</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-09</CRT_DT>
                <CRT_TM>13:01:59</CRT_TM>
                <TOT_FCAST>13780670</TOT_FCAST>
                <CNG_SNCE_LST_NM>-0.5</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-09</CRT_DT>
                <CRT_TM>16:01:03</CRT_TM>
                <TOT_FCAST>13889719</TOT_FCAST>
                <CNG_SNCE_LST_NM>0.8</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>00:01:07</CRT_TM>
                <TOT_FCAST>13862376</TOT_FCAST>
                <CNG_SNCE_LST_NM>-0.2</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>10:01:01</CRT_TM>
                <TOT_FCAST>13679133</TOT_FCAST>
                <CNG_SNCE_LST_NM>-1.3</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
        </DTL>
    </SHPR_TOT_NRG_FCAST_OUT>
    <SHPR_TOT_NRG_FCAST_OUT>
        <METADATA>
            <TMSTMP>2017-02-10T10:15:44</TMSTMP>
        </METADATA>
        <SHPR_TOT_NRG_FCAST_QRY>
            <GAS_DAY>2017-02-11</GAS_DAY>
        </SHPR_TOT_NRG_FCAST_QRY>
        <DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>11:01:21</CRT_TM>
                <TOT_FCAST>338473240</TOT_FCAST>
                <CNG_SNCE_LST_NM>99.0</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>13:01:59</CRT_TM>
                <TOT_FCAST>13780670</TOT_FCAST>
                <CNG_SNCE_LST_NM>10.5</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-10</CRT_DT>
                <CRT_TM>16:01:03</CRT_TM>
                <TOT_FCAST>23889719</TOT_FCAST>
                <CNG_SNCE_LST_NM>3.8</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-11</CRT_DT>
                <CRT_TM>00:01:07</CRT_TM>
                <TOT_FCAST>13432376</TOT_FCAST>
                <CNG_SNCE_LST_NM>10.2</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
            <NRG_FCAST_DTL>
                <CRT_DT>2017-02-11</CRT_DT>
                <CRT_TM>10:01:01</CRT_TM>
                <TOT_FCAST>13432133</TOT_FCAST>
                <CNG_SNCE_LST_NM>-1.3</CNG_SNCE_LST_NM>
                <NA_RNM_UPDTD>Y</NA_RNM_UPDTD>
            </NRG_FCAST_DTL>
        </DTL>
    </SHPR_TOT_NRG_FCAST_OUT>
</root>

XSL I could progress is ==

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:fo="http://www.w3.org/1999/XSL/Format" >
<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
<xsl:template match="/">GAS_DAY,CRT_DT,CRT_TM,TOT_FCAST,CNG_SNCE_LST_NM,NA_RNM_UPDTD
<xsl:for-each select="//DTL//NRG_FCAST_DTL">
     <xsl:value-of select="concat(SHPR_TOT_NRG_FCAST_QRY//GAS_DAY,',',CRT_DT, ',' ,CRT_TM,',' ,TOT_FCAST,',' ,CNG_SNCE_LST_NM,',' ,NA_RNM_UPDTD,'
     ')"/>
        <xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Body:
Because your for-each loop is staring inside the <NRG_FCAST_DTL> element, you need to select the sibling element using ... This works for me:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
    <xsl:template match="/">
        <xsl:text>GAS_DAY,CRT_DT,CRT_TM,TOT_FCAST,CNG_SNCE_LST_NM,NA_RNM_UPDTD&#xa;</xsl:text>
        <xsl:for-each select="//DTL/NRG_FCAST_DTL">
            <xsl:value-of select="concat(../../SHPR_TOT_NRG_FCAST_QRY/GAS_DAY,',',CRT_DT, ',' ,CRT_TM,',' ,TOT_FCAST,',' ,CNG_SNCE_LST_NM,',' ,NA_RNM_UPDTD, '&#xa;')"/>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>


问:
Convert hours, mins, secs String to hours
I want to convert a time in the below format into hours.

My input which is a time format could be anything like

```<code>1 hour 30 mins 20 secs
2 hrs 10 mins
45 mins
</code>```

whereas my output will be:

```<code>1.505
2.167
0.75
</code>```

These are the hours.

Currently I am doing it manually by parsing the input string 1 hour 30 mins 20 secs, finding whether the word hour/hours/hrs/hr is present, then taking the preceding digits--the same for mins and secs. I use the formula to convert mins and secs to hours manually.

Is there any built-in provision that I can use in Java?

答:
Currently I'm doing like this : </p>

```<code>private double convertToHours(String inputTime) {
    inputTime = " 1 hour 30 mins 20 secs";
    double hours = 0;
    List<String> timeList = Arrays.asList(inputTime.split(" "));
    ListIterator<String> iterator = timeList.listIterator();
    String time = null;
    String previous = null;
    while (iterator.hasNext()) {
        int prevIndex = iterator.previousIndex();
        time = (String) iterator.next();

        if (!time.isEmpty() && time != null) {

            if (time.contains("hours") || time.contains("hrs") || time.contains("hr") || time.contains("hour")) {
                // time = time.substring(0, time.indexOf('h'));
                    previous = timeList.get(prevIndex);

                hours = hours + Double.parseDouble(previous.trim());
            }

            if (time.contains("mins") || time.contains("min") || time.contains("mns")) {
                //time = time.substring(0, time.indexOf('m'));
                previous = timeList.get(prevIndex);
                hours = hours + Double.parseDouble(previous) / 60;
            }

            if (time.contains("secs") || time.contains("sec") || time.contains("scs")) {
                //time = time.substring(0, time.indexOf('s'));
                previous = timeList.get(prevIndex);
                hours = hours + Double.parseDouble(previous) / 3600;
            }
        }
    }
    return hours;
}
</code>```

Body:
I want to convert a time in the below format into hours.

My input which is a time format could be anything like

1 hour 30 mins 20 secs
2 hrs 10 mins
45 mins

whereas my output will be:

1.505
2.167
0.75

These are the hours.

Currently I am doing it manually by parsing the input string 1 hour 30 mins 20 secs, finding whether the word hour/hours/hrs/hr is present, then taking the preceding digits--the same for mins and secs. I use the formula to convert mins and secs to hours manually.

Is there any built-in provision that I can use in Java?

Body:
Currently I'm doing like this :

private double convertToHours(String inputTime) {
    inputTime = " 1 hour 30 mins 20 secs";
    double hours = 0;
    List<String> timeList = Arrays.asList(inputTime.split(" "));
    ListIterator<String> iterator = timeList.listIterator();
    String time = null;
    String previous = null;
    while (iterator.hasNext()) {
        int prevIndex = iterator.previousIndex();
        time = (String) iterator.next();

        if (!time.isEmpty() && time != null) {

            if (time.contains("hours") || time.contains("hrs") || time.contains("hr") || time.contains("hour")) {
                // time = time.substring(0, time.indexOf('h'));
                    previous = timeList.get(prevIndex);

                hours = hours + Double.parseDouble(previous.trim());
            }

            if (time.contains("mins") || time.contains("min") || time.contains("mns")) {
                //time = time.substring(0, time.indexOf('m'));
                previous = timeList.get(prevIndex);
                hours = hours + Double.parseDouble(previous) / 60;
            }

            if (time.contains("secs") || time.contains("sec") || time.contains("scs")) {
                //time = time.substring(0, time.indexOf('s'));
                previous = timeList.get(prevIndex);
                hours = hours + Double.parseDouble(previous) / 3600;
            }
        }
    }
    return hours;
}


问:
PHP - how to randomly get something from array
how can i get something randomly from a array for example i have this array I want to grab one of those lines randomly how can I do that using PHP?

```<code> $quizes = array(
        '3-1' => '2',
        '4+4' => '8',
        '7-5' => '2',
        '4+2' => '6',
        '9-3' => '6',
        '1+2' => '3',
        '9+9' => '18',
        '3+2' => '5',
        '2*3' => '6',
        '5*3' => '15',
        '6+6' => '12',
        '3+4' => '7',
        '7-4' => '3',
        '6+2' => '8',
        '3*2' => '6',
        '7+6' => '13',
        '1+1' => '2',
        '4*4' => '16',
        '10-3' => '7'
    );
</code>```

What i have tried

```<code>$rand_keys = array_rand($quizes, 2);
echo $quizes[$rand_keys[0]] . "\n";
echo $quizes[$rand_keys[1]] . "\n";
</code>```

but this only returns results such as 2 7, 15 2, 3 2 and more

Please help thank you

答:
Each of the "rows" in your code is actually two parts: a key and its corresponding value. For example, in the first row '3-1' is the key and '2' is its value. The => operator indicates this relationship.

The array_rand function you used will return a random key (or set of keys, if you specify the second parameter) from your array.

```<code>$key = array_rand($quizes);    // returns a random key e.g. '3-1'
</code>```

Then you can use that key to get the corresponding value,

```<code>$value = $quizes[$key];        // returns the value that matches $key
</code>```

There are various ways to output them from that point. If you want it to look kind of like it does in the code, you can use

```<code>echo "$key => $value";
</code>```

Body:
how can i get something randomly from a array for example i have this array I want to grab one of those lines randomly how can I do that using PHP?

 $quizes = array(
        '3-1' => '2',
        '4+4' => '8',
        '7-5' => '2',
        '4+2' => '6',
        '9-3' => '6',
        '1+2' => '3',
        '9+9' => '18',
        '3+2' => '5',
        '2*3' => '6',
        '5*3' => '15',
        '6+6' => '12',
        '3+4' => '7',
        '7-4' => '3',
        '6+2' => '8',
        '3*2' => '6',
        '7+6' => '13',
        '1+1' => '2',
        '4*4' => '16',
        '10-3' => '7'
    );

What i have tried

$rand_keys = array_rand($quizes, 2);
echo $quizes[$rand_keys[0]] . "\n";
echo $quizes[$rand_keys[1]] . "\n";

but this only returns results such as 2 7, 15 2, 3 2 and more

Please help thank you

Body:
Each of the "rows" in your code is actually two parts: a key and its corresponding value. For example, in the first row '3-1' is the key and '2' is its value. The => operator indicates this relationship.

The array_rand function you used will return a random key (or set of keys, if you specify the second parameter) from your array.

$key = array_rand($quizes);    // returns a random key e.g. '3-1'

Then you can use that key to get the corresponding value,

$value = $quizes[$key];        // returns the value that matches $key

There are various ways to output them from that point. If you want it to look kind of like it does in the code, you can use

echo "$key => $value";


问:
Copy files to output directory using csproj dotnetcore
So my issue is pretty simple. I have some files that I want to be copied to the build output directory whether it is a debug build or a release publish. All of the information I can find is about the old json config approach. Anyone have an example using the csproj with dotnetcore?</p>

答:
There's quite a few ways to achieve your goals, depending on what your needs are.

The easiest approach is setting the metadata (CopyToOutputDirectory / CopyToPublishDirectory) items conditionally (assuming .txt being a None item instead of Content, if it doesn't work, try <Content> instead):

<ItemGroup Condition="'$(Configuration)' == 'Debug'">
  <None Update="foo.txt" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
```
<p>If more control is required, the most versatile approach is to add custom targets that hook into the build process in the csproj file:</p>
<pre class="lang-xml prettyprint-override"><code><Target Name="CopyCustomContent" AfterTargets="AfterBuild">
  <Copy SourceFiles="foo.txt" DestinationFolder="$(OutDir)" />
</Target>
<Target Name="CopyCustomContentOnPublish" AfterTargets="Publish">
  <Copy SourceFiles="foo.txt" DestinationFolder="$(PublishDir)" />
</Target>
</code>```

This copies a file to the respective directories. For more options for the <Copy> task, see its documentation. To limit this to certain configurations, you can use a Condition attribute:

<Target … Condition=" '$(Configuration)' == 'Release' ">
```

This Condition attribute can be applied both on the <Target> element or on task elements like <Copy>.

Body:
There's quite a few ways to achieve your goals, depending on what your needs are.

The easiest approach is setting the metadata (CopyToOutputDirectory / CopyToPublishDirectory) items conditionally (assuming .txt being a None item instead of Content, if it doesn't work, try <Content> instead):

<ItemGroup Condition="'$(Configuration)' == 'Debug'">
  <None Update="foo.txt" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

If more control is required, the most versatile approach is to add custom targets that hook into the build process in the csproj file:

<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
  <Copy SourceFiles="foo.txt" DestinationFolder="$(OutDir)" />
</Target>
<Target Name="CopyCustomContentOnPublish" AfterTargets="Publish">
  <Copy SourceFiles="foo.txt" DestinationFolder="$(PublishDir)" />
</Target>

This copies a file to the respective directories. For more options for the <Copy> task, see its documentation. To limit this to certain configurations, you can use a Condition attribute:

<Target … Condition=" '$(Configuration)' == 'Release' ">

This Condition attribute can be applied both on the <Target> element or on task elements like <Copy>.

ContentLicense: CC BY-SA 4.0


问:
Parse string to DateTime in C#
I have date and time in a string formatted like that one:

```<code>"2011-03-21 13:26" //year-month-day hour:minute
</code>```

How can I parse it to System.DateTime?

I want to use functions like DateTime.Parse() or DateTime.ParseExact() if possible, to be able to specify the format of the date manually.

答:
You can also use XmlConvert.ToDateString

```<code>var dateStr = "2011-03-21 13:26";
var parsedDate = XmlConvert.ToDateTime(dateStr, "yyyy-MM-dd hh:mm");
</code>```

It is good to specify the date kind, the code is:

```<code>var anotherParsedDate = DateTime.ParseExact(dateStr, "yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
</code>```

More details on different parsing options http://amir-shenodua.blogspot.ie/2017/06/datetime-parsing-in-net.html

Title: Parse string to DateTime in C#

Body:
I have date and time in a string formatted like that one:

"2011-03-21 13:26" //year-month-day hour:minute

How can I parse it to System.DateTime?

I want to use functions like DateTime.Parse() or DateTime.ParseExact() if possible, to be able to specify the format of the date manually.

Body:
You can also use XmlConvert.ToDateString

var dateStr = "2011-03-21 13:26";
var parsedDate = XmlConvert.ToDateTime(dateStr, "yyyy-MM-dd hh:mm");

It is good to specify the date kind, the code is:

var anotherParsedDate = DateTime.ParseExact(dateStr, "yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

More details on different parsing options http://amir-shenodua.blogspot.ie/2017/06/datetime-parsing-in-net.html


问:
How to Remove white strip on top of wpf window after setting window style to none
Hi I have created WPF window with custom title bar successfully.But the problem is White strip on the top of  the titlebar.I can remove the white strip if i set the ResizeMode = "NoResize".But I want my window to Resizable I just only want to remove the whitestrip at the top of window.

Please help me to solve this problem.

Thanks in advance.

答:
I've seen this happen in Windows 10.

It is the default re-size border. You can remove that and still make the window resizable by setting ResizeMode="CanResizeWithGrip" AllowsTransparency="True"

How to remove white strip on top of WPF window with WindowStyle=None?


问:
How to access updated DAO recordset properties during a transaction?
I am developing an application in Access which uses transaction processing in DAO. I use a class to represent a body of data to be imported from another source. Among other things, this class houses a dictionary of recordsets, each of which has a new record added or an existing record edited depending on whether another record exists with the same primary key or not. I create an instance of this class from another procedure in a normal code module and use the properties and methods of the class to perform analysis and finalize the data extract.

In one procedure I want to subsequently edit the most recently added or edited record for each recordset in order to augument what has already been done to those records via the class' methods. The problem is that after a transaction has begun processing the .Recordcount property doesn't appear to update until the transaction has been committed, and it doesn't look like I can set a bookmark to the newly-added/edited record prior to committing it. The latter issue throws a "No Current Record" error when trying to set a bookmark to a record that has just been added (the Recordcount property is still at 0).

Am I correct in the understanding that DAO bookmarks are not a viable way of recalling a record that may have been added prior to committing a transaction? Is there another better way of doing this, or does anyone have any other suggestions?

答:
It turns out that although the .Bookmark property was not available during the transaction the .LastModified property was, which is a bookmark pointer to the record I wanted to access anyway. I simply went from:

```<code>Private Sub Test()

dim vBookmark as Variant
dim wsp as Workspace
dim rs as DAO.Recordset
dim rs2 as DAO.Recordset

set wsp = DBEngine.Workspaces(0)
set rs = CurrentDB.OpenRecordset("TableName", dbOpenTable)

wsp.BeginTrans

'... Make some record active

vBookmark = rs.Bookmark
'Note: ^ Error is thrown here when recordset has 0 records

'... Later

set rs2.Bookmark = vBookmark

wsp.CommitTrans

End Sub
</code>```

To this:

```<code>Private Sub Test()

dim vBookmark as Variant
dim wsp as Workspace
dim rs as DAO.Recordset
dim rs2 as DAO.Recordset

set wsp = DBEngine.Workspaces(0)
set rs = CurrentDB.OpenRecordset("TableName", dbOpenTable)

wsp.BeginTrans

'... Make some record active

vBookmark = rs.LastModified
'Note: ^ Correctly stores bookmark even during an uncommitted transaction

'... Later

set rs2.Bookmark = vBookmark

wsp.CommitTrans

End Sub
</code>```

Body:
It turns out that although the .Bookmark property was not available during the transaction the .LastModified property was, which is a bookmark pointer to the record I wanted to access anyway. I simply went from:

Private Sub Test()

dim vBookmark as Variant
dim wsp as Workspace
dim rs as DAO.Recordset
dim rs2 as DAO.Recordset

set wsp = DBEngine.Workspaces(0)
set rs = CurrentDB.OpenRecordset("TableName", dbOpenTable)

wsp.BeginTrans

'... Make some record active

vBookmark = rs.Bookmark
'Note: ^ Error is thrown here when recordset has 0 records

'... Later

set rs2.Bookmark = vBookmark

wsp.CommitTrans

End Sub

To this:

Private Sub Test()

dim vBookmark as Variant
dim wsp as Workspace
dim rs as DAO.Recordset
dim rs2 as DAO.Recordset

set wsp = DBEngine.Workspaces(0)
set rs = CurrentDB.OpenRecordset("TableName", dbOpenTable)

wsp.BeginTrans

'... Make some record active

vBookmark = rs.LastModified
'Note: ^ Correctly stores bookmark even during an uncommitted transaction

'... Later

set rs2.Bookmark = vBookmark

wsp.CommitTrans

End Sub


问:
Drag page content view make a blank screen on iOS 8 mobile app
In ionic ios app swipe the page it shows blank screen.Please help me how to fix this.

app.js

```<code> $stateProvider.state('login',
      {
          cache: false,
          url: '/login',
          templateUrl: 'templates/Login.html',
          controller: 'loginCtrl'

      })
</code>```

this is Login.html template page

```<code><ion-view view-title="Login" hide-nav-bar="true" padding="true">

<ion-header-bar align-title="center" class="bar-positive">

    <h1 class="title">Login</h1>
</ion-header-bar>
<ion-content scroll="true" overflow-scroll="true">
       <form name="signInForm" novalidate="" ng-submit="tryLogin(signInForm)">
        <div class="list-header">
            <label class="item item-input" tabs-item-hide="true" ng-class="{ 'has-errors' : signInForm.Email.$invalid, 'no-errors' : signInForm.Email.$valid}">
                <input type="email" placeholder="Email" name="Email" ng-model="loginData.Email" autofocus required>
            </label>
            <span class="form-errors" ng-show="signInForm.Email.$error && signInForm.$submitted" ng-messages="signInForm.Email.$error" ng-messages-include="templates/form-errors.html">

            </span>
            <label class="item item-input">
                <input type="password" placeholder="Password" name="Password" ng-model="loginData.Password" required>
            </label>
            <span class="form-errors" ng-show="signInForm.Password.$error && signInForm.$submitted" ng-messages="signInForm.Password.$error" ng-messages-include="templates/form-errors.html">

            </span>
            <div> </div>
            <p class="text_right">
                <a href="#/forgotPassword">Forgot Password?</a>
            </p>
            <div>
                <button class="button button-block button-positive">Login</button>
            </div>

            <div style="text-align: center">
                <a href="#/SignUp">Create an account</a>

            </div>

        </div>
    </form>
</ion-content>
</code>```

My Main Page HTML:

```<code><ion-side-menus>
    <ion-side-menu-content>
        <ion-nav-bar class="bar-positive">
            <ion-nav-buttons side="left">
                <button class="button button-icon button-clear ion-navicon" ng-click="toggleLeft()"></button>
            </ion-nav-buttons>
         </ion-nav-bar>
        <ion-nav-view></ion-nav-view>
    </ion-side-menu-content>
    <ion-side-menu side="left" >
        <ion-header-bar class="bar-positive">
            <h1 class="title">MY App</h1>
        </ion-header-bar>
        <ion-content>
            <ion-list>
                <ion-item class="item item-icon-left" nav-clear menu-close href="#/Settings">
                    <i class="icon ion-gear-b"></i>Settings
                </ion-item>
            </ion-list>
        </ion-content>
    </ion-side-menu>

</ion-side-menus>
</code>```

Now swipe the child page it from the iphone it show the blank screen, coldn't load it again

答:
an issue was created on github and the cash being disabled was identified as the cause of the problem. moreover a reply from the ionic team came as follow (last reply on github)

This is caused by caching being disabled. There is big benefit of caching you views, and an edge case like this isn't something we want to support.

If you're worried about data not being updated, you can use the view
  lifecycle events to make sure data is up to date.

so if you need the caching disabled and you don't care about this feature you can disable it as @Arul said. if you want this feature you have to enable caching.

Body:
In ionic ios app swipe the page it shows blank screen.Please help me how to fix this.

app.js

 $stateProvider.state('login',
      {
          cache: false,
          url: '/login',
          templateUrl: 'templates/Login.html',
          controller: 'loginCtrl'

      })

this is Login.html template page

<ion-view view-title="Login" hide-nav-bar="true" padding="true">

<ion-header-bar align-title="center" class="bar-positive">

Login

</ion-header-bar>
<ion-content scroll="true" overflow-scroll="true">
       <form name="signInForm" novalidate="" ng-submit="tryLogin(signInForm)">

                <input type="email" placeholder="Email" name="Email" ng-model="loginData.Email" autofocus required>

                <input type="password" placeholder="Password" name="Password" ng-model="loginData.Password" required>

                Forgot Password?

                <button class="button button-block button-positive">Login</button>

                Create an account

    </form>
</ion-content>

My Main Page HTML:

<ion-side-menus>
    <ion-side-menu-content>
        <ion-nav-bar class="bar-positive">
            <ion-nav-buttons side="left">
                <button class="button button-icon button-clear ion-navicon" ng-click="toggleLeft()"></button>
            </ion-nav-buttons>
         </ion-nav-bar>
        <ion-nav-view></ion-nav-view>
    </ion-side-menu-content>
    <ion-side-menu side="left" >
        <ion-header-bar class="bar-positive">

MY App

        </ion-header-bar>
        <ion-content>
            <ion-list>
                <ion-item class="item item-icon-left" nav-clear menu-close href="#/Settings">
                    Settings
                </ion-item>
            </ion-list>
        </ion-content>
    </ion-side-menu>

</ion-side-menus>

Now swipe the child page it from the iphone it show the blank screen, coldn't load it again


问:
Access .laccdb file not clean until last user logs out
I have an Access data base (.accdb) on the local network server that is used by multiple users, via the local network OR by using Remote Desktop via VPN to a terminal services computer connected to the www and the local network.

three issues:

1: The .laccdb file contains the users (local and remote) even after they log out until the file is deleted when the last user logs out.  Access doesn't seem to clean up after itself regardless of the mode of connection.  Are there any options, settings or anything I can add to the db to cleanup the .laccdb file?

The remote users are not listed by login id or computername or username in the .laccdb file, just by terminal-services-computer-name and "Admin".
I'd like to know which remote user(s) are actively logged in.

Rarely, the last user logs out but the .laccdb file is not deleted.  Restarting that user's computer seems to be the easiest fix but it can take some time to get that done.  Meanwhile there are some database operations that can't be done without exclusive access.

答: try to check the "Compact on Close" option in the database settings. Also you may want to check if all the users have rights to delete files on that location - this may be the cause you cannot get rid of that temp *laccdb file</p>


问:
%pylab inline error "matplotlib/fontList.py3k.cache"
I was trying to plot a graphic with matplotlib in Jupyter and then with only the 'pylab inline' the following error shows up. I'm working with python 3.x and anaconda in a macbook. I found similar trends (for example this) with some potential solutions but they didn't work. I have tried everything but nothing works. I would really appreciate any help.

My code:

```<code>%pylab inline
</code>```

which produces the following error:

```<code>    ---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in <module>()
   1429         try:
-> 1430             fontManager = pickle_load(_fmcache)
   1431             if (not hasattr(fontManager, '_version') or

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in pickle_load(filename)
    965     """
--> 966     with open(filename, 'rb') as fh:
    967         data = pickle.load(fh)

FileNotFoundError: [Errno 2] No such file or directory: '/Users/sebasg167/.matplotlib/fontList.py3k.cache'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-2-d4543581fa9d> in <module>()
----> 1 get_ipython().magic('pylab inline')

//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
   2156         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2157         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2158         return self.run_line_magic(magic_name, magic_arg_s)
   2159
   2160     #-------------------------------------------------------------------------

//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
   2077                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2078             with self.builtin_trap:
-> 2079                 result = fn(*args,**kwargs)
   2080             return result
   2081

<decorator-gen-105> in pylab(self, line)

//anaconda/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    186     # but it's overkill for just that one bit of state.
    187     def magic_deco(arg):
--> 188         call = lambda f, *a, **k: f(*a, **k)
    189
    190         if callable(arg):

//anaconda/lib/python3.6/site-packages/IPython/core/magics/pylab.py in pylab(self, line)
    154             import_all = not args.no_import_all
    155
--> 156         gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
    157         self._show_matplotlib_backend(args.gui, backend)
    158         print ("Populating the interactive namespace from numpy and matplotlib")

//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in enable_pylab(self, gui, import_all, welcome_message)
   2984         from IPython.core.pylabtools import import_pylab
   2985
-> 2986         gui, backend = self.enable_matplotlib(gui)
   2987
   2988         # We want to prevent the loading of pylab to pollute the user's

//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui)
   2945                 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
   2946
-> 2947         pt.activate_matplotlib(backend)
   2948         pt.configure_inline_support(self, backend)
   2949

//anaconda/lib/python3.6/site-packages/IPython/core/pylabtools.py in activate_matplotlib(backend)
    292     matplotlib.rcParams['backend'] = backend
    293
--> 294     import matplotlib.pyplot
    295     matplotlib.pyplot.switch_backend(backend)
    296

//anaconda/lib/python3.6/site-packages/matplotlib/pyplot.py in <module>()
     27 from cycler import cycler
     28 import matplotlib
---> 29 import matplotlib.colorbar
     30 from matplotlib import style
     31 from matplotlib import _pylab_helpers, interactive

//anaconda/lib/python3.6/site-packages/matplotlib/colorbar.py in <module>()
     34 import matplotlib.collections as collections
     35 import matplotlib.colors as colors
---> 36 import matplotlib.contour as contour
     37 import matplotlib.cm as cm
     38 import matplotlib.gridspec as gridspec

//anaconda/lib/python3.6/site-packages/matplotlib/contour.py in <module>()
     20 import matplotlib.colors as colors
     21 import matplotlib.collections as mcoll
---> 22 import matplotlib.font_manager as font_manager
     23 import matplotlib.text as text
     24 import matplotlib.cbook as cbook

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in <module>()
   1438             raise
   1439         except:
-> 1440             _rebuild()
   1441     else:
   1442         _rebuild()

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in _rebuild()
   1417         global fontManager
   1418
-> 1419         fontManager = FontManager()
   1420
   1421         if _fmcache:

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in __init__(self, size, weight)
   1071         self.afmfiles = findSystemFonts(paths, fontext='afm') + \
   1072             findSystemFonts(fontext='afm')
-> 1073         self.afmlist = createFontList(self.afmfiles, fontext='afm')
   1074         if len(self.afmfiles):
   1075             self.defaultFont['afm'] = self.afmfiles[0]

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in createFontList(fontfiles, fontext)
    589                 continue
    590             try:
--> 591                 prop = afmFontProperty(fpath, font)
    592             except KeyError:
    593                 continue

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in afmFontProperty(fontpath, font)
    498     """
    499
--> 500     name = font.get_familyname()
    501     fontname = font.get_fontname().lower()
    502

//anaconda/lib/python3.6/site-packages/matplotlib/afm.py in get_familyname(self)
    523         extras = (br'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
    524                   br'light|ultralight|extra|condensed))+$')
--> 525         return re.sub(extras, '', name)
    526
    527     @property

//anaconda/lib/python3.6/re.py in sub(pattern, repl, string, count, flags)
    189     a callable, it's passed the match object and must return
    190     a replacement string to be used."""
--> 191     return _compile(pattern, flags).sub(repl, string, count)
    192
    193 def subn(pattern, repl, string, count=0, flags=0):

TypeError: cannot use a bytes pattern on a string-like object
</code>```

答:
You must find this file  :
font_manager.py
in my case : C:\Users\gustavo\Anaconda3\Lib\site-packages\matplotlib\ font_manager.py

and FIND  def win32InstalledFonts(directory=None, fontext='ttf')
and replace
by :

def win32InstalledFonts(directory=None, fontext='ttf'):
    """
    Search for fonts in the specified font directory, or use the
    system directories if none given.  A list of TrueType font
    filenames are returned by default, or AFM fonts if fontext ==
    'afm'.
    """

```<code>from six.moves import winreg
if directory is None:
    directory = win32FontDirectory()

fontext = get_fontext_synonyms(fontext)

key, items = None, {}
for fontdir in MSFontDirectories:
    try:
        local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
    except OSError:
        continue

    if not local:
        return list_fonts(directory, fontext)
    try:
        for j in range(winreg.QueryInfoKey(local)[1]):
            try:
                key, direc, any = winreg.EnumValue(local, j)
                if not is_string_like(direc):
                    continue
                if not os.path.dirname(direc):
                    direc = os.path.join(directory, direc)
                    direc = direc.split('\0', 1)[0]

                if os.path.splitext(direc)[1][1:] in fontext:
                    items[direc] = 1
            except EnvironmentError:
                continue
            except WindowsError:
                continue
            except MemoryError:
                continue
        return list(six.iterkeys(items))
    finally:
        winreg.CloseKey(local)
return None
</code>```

Body:
I was trying to plot a graphic with matplotlib in Jupyter and then with only the 'pylab inline' the following error shows up. I'm working with python 3.x and anaconda in a macbook. I found similar trends (for example this) with some potential solutions but they didn't work. I have tried everything but nothing works. I would really appreciate any help.

My code:

%pylab inline

which produces the following error:

    ---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in <module>()
   1429         try:
-> 1430             fontManager = pickle_load(_fmcache)
   1431             if (not hasattr(fontManager, '_version') or

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in pickle_load(filename)
    965     """
--> 966     with open(filename, 'rb') as fh:
    967         data = pickle.load(fh)

FileNotFoundError: [Errno 2] No such file or directory: '/Users/sebasg167/.matplotlib/fontList.py3k.cache'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-2-d4543581fa9d> in <module>()
----> 1 get_ipython().magic('pylab inline')

//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
   2156         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2157         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2158         return self.run_line_magic(magic_name, magic_arg_s)
   2159
   2160     #-------------------------------------------------------------------------

//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line)
   2077                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2078             with self.builtin_trap:
-> 2079                 result = fn(*args,**kwargs)
   2080             return result
   2081

<decorator-gen-105> in pylab(self, line)

//anaconda/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    186     # but it's overkill for just that one bit of state.
    187     def magic_deco(arg):
--> 188         call = lambda f, *a, **k: f(*a, **k)
    189
    190         if callable(arg):

//anaconda/lib/python3.6/site-packages/IPython/core/magics/pylab.py in pylab(self, line)
    154             import_all = not args.no_import_all
    155
--> 156         gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
    157         self._show_matplotlib_backend(args.gui, backend)
    158         print ("Populating the interactive namespace from numpy and matplotlib")

//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in enable_pylab(self, gui, import_all, welcome_message)
   2984         from IPython.core.pylabtools import import_pylab
   2985
-> 2986         gui, backend = self.enable_matplotlib(gui)
   2987
   2988         # We want to prevent the loading of pylab to pollute the user's

//anaconda/lib/python3.6/site-packages/IPython/core/interactiveshell.py in enable_matplotlib(self, gui)
   2945                 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
   2946
-> 2947         pt.activate_matplotlib(backend)
   2948         pt.configure_inline_support(self, backend)
   2949

//anaconda/lib/python3.6/site-packages/IPython/core/pylabtools.py in activate_matplotlib(backend)
    292     matplotlib.rcParams['backend'] = backend
    293
--> 294     import matplotlib.pyplot
    295     matplotlib.pyplot.switch_backend(backend)
    296

//anaconda/lib/python3.6/site-packages/matplotlib/pyplot.py in <module>()
     27 from cycler import cycler
     28 import matplotlib
---> 29 import matplotlib.colorbar
     30 from matplotlib import style
     31 from matplotlib import _pylab_helpers, interactive

//anaconda/lib/python3.6/site-packages/matplotlib/colorbar.py in <module>()
     34 import matplotlib.collections as collections
     35 import matplotlib.colors as colors
---> 36 import matplotlib.contour as contour
     37 import matplotlib.cm as cm
     38 import matplotlib.gridspec as gridspec

//anaconda/lib/python3.6/site-packages/matplotlib/contour.py in <module>()
     20 import matplotlib.colors as colors
     21 import matplotlib.collections as mcoll
---> 22 import matplotlib.font_manager as font_manager
     23 import matplotlib.text as text
     24 import matplotlib.cbook as cbook

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in <module>()
   1438             raise
   1439         except:
-> 1440             _rebuild()
   1441     else:
   1442         _rebuild()

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in _rebuild()
   1417         global fontManager
   1418
-> 1419         fontManager = FontManager()
   1420
   1421         if _fmcache:

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in __init__(self, size, weight)
   1071         self.afmfiles = findSystemFonts(paths, fontext='afm') + \
   1072             findSystemFonts(fontext='afm')
-> 1073         self.afmlist = createFontList(self.afmfiles, fontext='afm')
   1074         if len(self.afmfiles):
   1075             self.defaultFont['afm'] = self.afmfiles[0]

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in createFontList(fontfiles, fontext)
    589                 continue
    590             try:
--> 591                 prop = afmFontProperty(fpath, font)
    592             except KeyError:
    593                 continue

//anaconda/lib/python3.6/site-packages/matplotlib/font_manager.py in afmFontProperty(fontpath, font)
    498     """
    499
--> 500     name = font.get_familyname()
    501     fontname = font.get_fontname().lower()
    502

//anaconda/lib/python3.6/site-packages/matplotlib/afm.py in get_familyname(self)
    523         extras = (br'(?i)([ -](regular|plain|italic|oblique|bold|semibold|'
    524                   br'light|ultralight|extra|condensed))+$')
--> 525         return re.sub(extras, '', name)
    526
    527     @property

//anaconda/lib/python3.6/re.py in sub(pattern, repl, string, count, flags)
    189     a callable, it's passed the match object and must return
    190     a replacement string to be used."""
--> 191     return _compile(pattern, flags).sub(repl, string, count)
    192
    193 def subn(pattern, repl, string, count=0, flags=0):

TypeError: cannot use a bytes pattern on a string-like object

Body:
You must find this file  :
font_manager.py
in my case : C:\Users\gustavo\Anaconda3\Lib\site-packages\matplotlib\ font_manager.py

and FIND  def win32InstalledFonts(directory=None, fontext='ttf')
and replace
by :

def win32InstalledFonts(directory=None, fontext='ttf'):
    """
    Search for fonts in the specified font directory, or use the
    system directories if none given.  A list of TrueType font
    filenames are returned by default, or AFM fonts if fontext ==
    'afm'.
    """

from six.moves import winreg
if directory is None:
    directory = win32FontDirectory()

fontext = get_fontext_synonyms(fontext)

key, items = None, {}
for fontdir in MSFontDirectories:
    try:
        local = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, fontdir)
    except OSError:
        continue

    if not local:
        return list_fonts(directory, fontext)
    try:
        for j in range(winreg.QueryInfoKey(local)[1]):
            try:
                key, direc, any = winreg.EnumValue(local, j)
                if not is_string_like(direc):
                    continue
                if not os.path.dirname(direc):
                    direc = os.path.join(directory, direc)
                    direc = direc.split('\0', 1)[0]

                if os.path.splitext(direc)[1][1:] in fontext:
                    items[direc] = 1
            except EnvironmentError:
                continue
            except WindowsError:
                continue
            except MemoryError:
                continue
        return list(six.iterkeys(items))
    finally:
        winreg.CloseKey(local)
return None


问:
What header should be sent by master when there are multiple slaves whose data is getting updated(Event triggered Frames)?
We want to check Rx of data from slaves in case of Lin event triggered frames. According to our understanding, in Lin stack integration for Autosar, we have Tx and Rx of unconditional frames. Here the master sends a header based on PID(protected identifier) configured for TX and Rx frames by using ARTOP tool. When header sent by master matches with slave PID then that slave responds with a data. Where as in event triggered frames, master sends a header and more than one slaves  will respond for that header, only if thier data has got updated. If only a single slave responds then it will send its updated data but if more than one slave responds then there will be a collision and master will handle and resolve the collision.</p>

答:
The event triggered frame header sent by the master consist in a group of unconditional frames headers just packed, each one has the PID of one slave the master wants to poll, something like: [Break:Sync:IDx:Break:Sync:IDy:Break:Sync:IDz:...], they are sent in a row.

After that, the protocol follows as you describe it.


问:
How to Subtracting 7hrs from a String time?
I need to convert time from GMT to PST and for that I am trying to subtract 7 hrs from the time. The issue is that the time is stored in a String and I am not sure how can I subtract 7 hrs from a String time. displayDateString gives me the date and time and it is a String. I am trying the following approach but it is not working the way I need it.

Before Code Change

```<code> public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);
    DateFormat pstFormat = new SimpleDateFormat();
    return displayDateString;
}
</code>```

above code outputs: 06/02/17 07:19 PM

After Code Change

```<code>public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);

    DateFormat pstFormat = new SimpleDateFormat();
    /*TimeZone pstZone = TimeZone.getTimeZone( "PST" );
    pstFormat.setTimeZone( pstZone );
    displayDateString = pstFormat.format(date);*/

    Calendar cal = Calendar.getInstance();
    cal = Calendar.getInstance();
    cal.add( Calendar.HOUR, -7 );
    displayDateString = pstFormat.format( cal.getTime() );
    return displayDateString;
}

public static Date convertStringToDate(String strDate, String inputFormat) {
    SimpleDateFormat dateFormat = null;
    Date date = null;
    boolean formatChagned = false;
    try {
        if(!StringUtils.isSet(strDate)){
            return date;
        }
        if(strDate.indexOf("/")>0 && inputFormat.indexOf("-")>=0){
            inputFormat = inputFormat.replaceAll("-", "/");
            formatChagned=true;
        }else if (strDate.indexOf("-")>0 && inputFormat.indexOf("/")>=0){
            inputFormat = inputFormat.replaceAll("/", "-");
            formatChagned=true;
        }

        dateFormat = new SimpleDateFormat(inputFormat);
        dateFormat.setLenient(false);
        date = dateFormat.parse(strDate);
    } catch (Exception exception) {
        log.error("Given date to parse:"+strDate);
        log.error("Given Input Date Format:"+inputFormat);

        if(formatChagned){
            log.error("Given Input Date Format is incorrcet and it is modified as :"+inputFormat);
        }

        log.error(exception);
        log.error("DateUtil.convertStringToDate :Parse exception while parsing,"+strDate+" using format :"+inputFormat);
        date = null;
    }
    return date;
}
</code>```

I added the calendar part to somehow subtract 7hrs from the existing time. This doesn't work.

答:
You need to set the calendar date before manipulating it:

```<code>cal.setTime(date);
</code>```

before the:

```<code>cal.add( Calendar.HOUR, -7 );
</code>```

And you seem to have some redundant code, like calling the Calendar getInstance twice.

Body:
I need to convert time from GMT to PST and for that I am trying to subtract 7 hrs from the time. The issue is that the time is stored in a String and I am not sure how can I subtract 7 hrs from a String time. displayDateString gives me the date and time and it is a String. I am trying the following approach but it is not working the way I need it.

Before Code Change

 public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);
    DateFormat pstFormat = new SimpleDateFormat();
    return displayDateString;
}

above code outputs: 06/02/17 07:19 PM

After Code Change

public static String formatDate(String strDate, String inputFormat, String outputFormat) {
    Date date = convertStringToDate(strDate,inputFormat);
    String displayDateString = formatDate(date, outputFormat);

    DateFormat pstFormat = new SimpleDateFormat();
    /*TimeZone pstZone = TimeZone.getTimeZone( "PST" );
    pstFormat.setTimeZone( pstZone );
    displayDateString = pstFormat.format(date);*/

    Calendar cal = Calendar.getInstance();
    cal = Calendar.getInstance();
    cal.add( Calendar.HOUR, -7 );
    displayDateString = pstFormat.format( cal.getTime() );
    return displayDateString;
}

public static Date convertStringToDate(String strDate, String inputFormat) {
    SimpleDateFormat dateFormat = null;
    Date date = null;
    boolean formatChagned = false;
    try {
        if(!StringUtils.isSet(strDate)){
            return date;
        }
        if(strDate.indexOf("/")>0 && inputFormat.indexOf("-")>=0){
            inputFormat = inputFormat.replaceAll("-", "/");
            formatChagned=true;
        }else if (strDate.indexOf("-")>0 && inputFormat.indexOf("/")>=0){
            inputFormat = inputFormat.replaceAll("/", "-");
            formatChagned=true;
        }

        dateFormat = new SimpleDateFormat(inputFormat);
        dateFormat.setLenient(false);
        date = dateFormat.parse(strDate);
    } catch (Exception exception) {
        log.error("Given date to parse:"+strDate);
        log.error("Given Input Date Format:"+inputFormat);

        if(formatChagned){
            log.error("Given Input Date Format is incorrcet and it is modified as :"+inputFormat);
        }

        log.error(exception);
        log.error("DateUtil.convertStringToDate :Parse exception while parsing,"+strDate+" using format :"+inputFormat);
        date = null;
    }
    return date;
}

I added the calendar part to somehow subtract 7hrs from the existing time. This doesn't work.

Body:
You need to set the calendar date before manipulating it:

cal.setTime(date);

before the:

cal.add( Calendar.HOUR, -7 );

And you seem to have some redundant code, like calling the Calendar getInstance twice.


问:
create a subclass of NSView to enable setTag()
I am using xamarin to develop a Mac app, and somewhere in my program I want to set the tag of a NSView. However, the tag property is readonly for NSView, so I'm searching for a way to create a subclass where tag is writable. Is there any suggestion about how I should write the subclass? thanks</p>

答:
```<code>public class MyNSView : NSView
{
    public nint _tag;

    public new nint Tag
    {
        get
        {
            return _tag;
        }
        set
        {
            _tag = value;
        }
    }
</code>```

Be aware that this is not longer the NSView Tag.

Using your custom NSView Tag

```<code>var view = new MyNSView ();

view.Tag = 100;
</code>```

Body:
public class MyNSView : NSView
{
    public nint _tag;

    public new nint Tag
    {
        get
        {
            return _tag;
        }
        set
        {
            _tag = value;
        }
    }

Be aware that this is not longer the NSView Tag.

Using your custom NSView Tag

var view = new MyNSView ();

view.Tag = 100;