问:
Entity Framework Core can't create database file on android samsung devices
we have an app written with xamarin for android who uses Entity Framework Core. It works on our test devices from Wiko (Android 6.0), HTC (Android 7.1) and Sony(6.0). But on Samsung devices (6.0) we get the following exception on startup:

```<code>Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1294: 'unable to open database file'.
</code>```

Complete exception:

```<code>    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    ... 1 more
Caused by: android.runtime.JavaProxyThrowable: Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1294: 'unable to open database file'.
  at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists () [0x00000] in <f97b8874924247a39fca91e98b024cf6>:0
  at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate (System.String targetMigration) [0x00030] in <f97b8874924247a39fca91e98b024cf6>:0
  at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate (Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade databaseFacade) [0x00010] in <f97b8874924247a39fca91e98b024cf6>:0
  at FriendsAppDate.Business.AppStart.Start (System.Object hint) [0x0001b] in <c1a86397b9cc451297593cc8cc1289f7>:0
  at MvvmCross.Droid.Views.MvxSplashScreenActivity.TriggerFirstNavigate () [0x00005] in <f6aebf863dc84be7b380cfec8d459508>:0
  at MvvmCross.Droid.Views.MvxSplashScreenActivity.InitializationComplete () [0x00009] in <f6aebf863dc84be7b380cfec8d459508>:0
  at MvvmCross.Droid.Platform.MvxAndroidSetupSingleton.InitializeFromSplashScreen (MvvmCross.Droid.Views.IMvxAndroidSplashScreenActivity splashScreen) [0x00029] in <f6aebf863dc84be7b380cfec8d459508>:0
  at MvvmCross.Droid.Views.MvxSplashScreenActivity.OnResume () [0x00018] in <f6aebf863dc84be7b380cfec8d459508>:0
  at Android.App.Activity.n_OnResume (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <fca2c02347db4086aed81b5475a315fd>:0
  at (wrapper dynamic-method) System.Object:b336e942-d75d-4699-a108-3115233929aa (intptr,intptr)
    at mvvmcross.droid.views.MvxSplashScreenActivity.n_onResume(Native Method)
    at mvvmcross.droid.views.MvxSplashScreenActivity.onResume(MvxSplashScreenActivity.java:39)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
    at android.app.Activity.performResume(Activity.java:6987)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4144)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4245)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1838)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7224)
    ... 3 more
</code>```

I get the databse path via:

```<code>Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), Constants.DB_NAME);
</code>```

and this is the same on all devices.

```<code>/data/user/0/[AppID]/files/[DbName]
</code>```

We use the current version of Entity Framework Core 1.1.1
What could be wrong here?

答:
This is an issue with the implementation of SQLite on Samsung devices and should be fixed with 2.0.
The EF team had a work around in the issue. See here:  https://github.com/aspnet/EntityFramework/issues/7870

Also, what worked for us, was to create the db over raw SQL statements. SQlite DB Browser generates them so you can just copy and paste them.

Body:
we have an app written with xamarin for android who uses Entity Framework Core. It works on our test devices from Wiko (Android 6.0), HTC (Android 7.1) and Sony(6.0). But on Samsung devices (6.0) we get the following exception on startup:

Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1294: 'unable to open database file'.

Complete exception:

    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    ... 1 more
Caused by: android.runtime.JavaProxyThrowable: Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1294: 'unable to open database file'.
  at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists () [0x00000] in <f97b8874924247a39fca91e98b024cf6>:0
  at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate (System.String targetMigration) [0x00030] in <f97b8874924247a39fca91e98b024cf6>:0
  at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate (Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade databaseFacade) [0x00010] in <f97b8874924247a39fca91e98b024cf6>:0
  at FriendsAppDate.Business.AppStart.Start (System.Object hint) [0x0001b] in <c1a86397b9cc451297593cc8cc1289f7>:0
  at MvvmCross.Droid.Views.MvxSplashScreenActivity.TriggerFirstNavigate () [0x00005] in <f6aebf863dc84be7b380cfec8d459508>:0
  at MvvmCross.Droid.Views.MvxSplashScreenActivity.InitializationComplete () [0x00009] in <f6aebf863dc84be7b380cfec8d459508>:0
  at MvvmCross.Droid.Platform.MvxAndroidSetupSingleton.InitializeFromSplashScreen (MvvmCross.Droid.Views.IMvxAndroidSplashScreenActivity splashScreen) [0x00029] in <f6aebf863dc84be7b380cfec8d459508>:0
  at MvvmCross.Droid.Views.MvxSplashScreenActivity.OnResume () [0x00018] in <f6aebf863dc84be7b380cfec8d459508>:0
  at Android.App.Activity.n_OnResume (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <fca2c02347db4086aed81b5475a315fd>:0
  at (wrapper dynamic-method) System.Object:b336e942-d75d-4699-a108-3115233929aa (intptr,intptr)
    at mvvmcross.droid.views.MvxSplashScreenActivity.n_onResume(Native Method)
    at mvvmcross.droid.views.MvxSplashScreenActivity.onResume(MvxSplashScreenActivity.java:39)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)
    at android.app.Activity.performResume(Activity.java:6987)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4144)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4245)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1838)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:7224)
    ... 3 more

I get the databse path via:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), Constants.DB_NAME);

and this is the same on all devices.

/data/user/0/[AppID]/files/[DbName]

We use the current version of Entity Framework Core 1.1.1
What could be wrong here?


来源: stackexchange

问:
How to enable OpenEdge debugger?
I have enabled the debugger with prodebugenable -enable-all as mentioned here: https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pdsoe%2Fenabling-debugging.html%23wwID0EBCZX

I have got the success message

Debugging is enabled for the Progress 4GL installed in ...

But I still get the error

The Progress 4GL is not enabled for debugging. Run proDebugEnable from
  within a proenv session on Windows or from a UNIX shell to enable
  debugging and set the debuggerEnabled property to 1 for any services
  that you want to debug. (11724)

prodebugenable.bat runs the exe file _debugEnable.exe. What does this file do?

Why the debugger isn't enabled although I get a success message ?

My Version: OpenEdge 10.2B

答: The DLC path was wrong in the ini-file. After I corrected it as in the registry the debugging worked.</p>

ContentLicense: CC BY-SA 3.0

Title: How to enable OpenEdge debugger?


问:
Xamarin Forms Unit Testing
What is the approach to write unit tests for Xamarin Forms application (as opposed to Xamarin Traditional which is Xamarin.Android, Xamarin.IOS, or Xamarin.UWP)?

Can anyone provide a good explanation for Unit Tests in Xamarin.Forms vs Unit Tests in Xamarin Traditional?

A good explanation article how to implement Xamarin.Forms tests and are they even needed or should we write Unit Tests for each platform instead?

I have read a number of articles out there but I haven't found one that starts from creating the unit test project type in Visual Studio to writing and running the tests.

They mostly start somewhere in the middle discussing DI or ServiceLocator (like this one http://arteksoftware.com/unit-testing-with-xamarin-forms-dependencyservice/).

Or, on the other hand, they mix Xamarin.Forms with Xamarin.Android (or IOS) unit testing (like this one: http://www.dsibinski.pl/2017/03/unit-testing-xamarin-application/).

Or, they mix Portable vs Shared like in the case of this one http://www.alteridem.net/2015/12/21/testing-xamarin-projects-using-nunit-3/.

What I understand so far is that I could use regular Unit Test project in VS and use either MSTest or NUnit.  Or, I can write platform specific unit tests for each platform.

All of this is very confusing because authors seem to mix the terms all over the place.

A detailed answer with supporting examples would be highly appreciated as I am entirely a beginner in this area.

答:
Please refer to below links

Unit Testing for Xamarin.Forms (Cross-platorm)

: see also video clip about Creating Unit Tests for Xamarin Forms Apps

Unit Testing for Xamarin.iOS

P.S.

Xamarin.Forms application is usually defined in a cross platform shared project (either a Portable Class Library or a Shared Project) and combined with platform-specific projects.

Xamarin.Forms is best for:

Apps that require little platform-specific functionality Apps where

code sharing is more important than custom UI

Developers comfortable with XAML

Xamarin.iOS & Xamarin.Android are best for:

Apps with interactions that require native behavior

Apps that use many platform-specific APIs

Apps where custom UI is more important than code sharing

This link also explained the differentiation between Xamarin.Forms and Xamarin.Native.

Title: Xamarin Forms Unit Testing

ContentLicense: CC BY-SA 4.0


问:
curl request in ruby RestClient
The fastbill API states in its docu to make this curl request in order to receive information:

```<code>curl -v -X POST \
–u {E-Mail-Adresse}:{API-Key} \
-H 'Content-Type: application/xml' \
-d '{xml body}' \
https://my.fastbill.com/api/1.0/api.php
</code>```

Using RestClientI tried to translate this into a ruby like request:

How I read this:
- make a post request to https://my.fastbill.com/api/1.0/api.php using basic authentification and stating the content type in the header, correct?

Now this would be a resource based request in RestClient like this:

First I authenticate:

```<code>resource = RestClient::Resource.new( 'https://my.fastbill.com/api/1.0/api.php', 'my@email.de', 'API-KEY-XXXXX' )
</code>```

which works and authorises me.
then putting my request in:

```<code>xml = '<?xml version="1.0" encoding="utf-8"?><FBAPI><SERVICE>customer.get</SERVICE><FILTER/></FBAPI>'

resource.post xml, content_type: 'application/xml'
</code>```

It always returns 400 and I don't know what else to do here.

Also how would json work here?

```<code>resource.post param1: 'value', content_type: 'json'
</code>```

would be obvious.

答:
```<code>$url="https://my.fastbill.com/api/1.0/api.php";
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
print_r(json_decode($result));
</code>```

Title: curl request in ruby RestClient

Body:
The fastbill API states in its docu to make this curl request in order to receive information:

curl -v -X POST \
–u {E-Mail-Adresse}:{API-Key} \
-H 'Content-Type: application/xml' \
-d '{xml body}' \
https://my.fastbill.com/api/1.0/api.php

Using RestClientI tried to translate this into a ruby like request:

How I read this:
- make a post request to https://my.fastbill.com/api/1.0/api.php using basic authentification and stating the content type in the header, correct?

Now this would be a resource based request in RestClient like this:

First I authenticate:

resource = RestClient::Resource.new( 'https://my.fastbill.com/api/1.0/api.php', 'my@email.de', 'API-KEY-XXXXX' )

which works and authorises me.
then putting my request in:

xml = '<?xml version="1.0" encoding="utf-8"?><FBAPI><SERVICE>customer.get</SERVICE><FILTER/></FBAPI>'

resource.post xml, content_type: 'application/xml'

It always returns 400 and I don't know what else to do here.

Also how would json work here?

resource.post param1: 'value', content_type: 'json'

would be obvious.


问:
mongodb with scala maven project
I am stuck on an issue. I have created a scala maven project where I am trying to communicate with mongo. My project is getting build successfuly and I do not get any error when I execute my project, but still no data is getting inserted in my mongodb.

If I insert data manually through mongo-cli then my code can read it but it is not even inserting a single record.
Could you please help me in finding where I am making mistakes.
My mongo version is 3.2.10

App.scala

```<code>package com.assignment.scala

import org.mongodb.scala._
import org.mongodb.scala.model.Aggregates._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.model.Projections._
import org.mongodb.scala.model.Sorts._
import org.mongodb.scala.model.Updates._
import org.mongodb.scala.model._

/**
 * @author ${user.name}
 */
object App {

  def main(args: Array[String]) {
    println("Calling insertDoc==")
    insertDoc()
  }

  def insertDoc() = {
    val mongoClient = MongoClient()
    val database = mongoClient.getDatabase("assignment")
    val collection = database.getCollection("links")

   println("collection find : " + collection.find())
   collection.find().subscribe(
  (user: Document) => println("document------------"+user.toJson()),
  (error: Throwable) => println(s"Query failed: ${error.getMessage}"),
  () => println("Done"))

    collection.drop()

    val bufferedSource = io.Source.fromFile("/home/impadmin/ServiceSource/ml-latest-small/links.csv")
    var firstLine = List[String]();
    var docList = List[Document]();
    for ((line,count) <- bufferedSource.getLines.zipWithIndex) {
      val cols = line.split(",").map(_.trim)
      if (firstLine.size <= 0 && cols.length > 0) {
        firstLine = cols.toList;
      } else {
        var doc: Document = Document("_id" -> count)
        for ((a, b) <- firstLine zip cols) {
          doc ++= Document(a -> b)
        }
        docList = docList :+ doc
        collection.insertOne(doc)
      }
    }

    val doc3 = Document("name" -> "MongoDB", "type" -> "database",
      "count" -> 1, "info" -> Document("x" -> 203, "y" -> 102))

   collection.insertOne(doc)
   collection.find().subscribe((doc1: Document) => println(doc1.toJson()),
   (e: Throwable) => println(s"There was an error: $e"))
  }
}
</code>```

答:
It worked using subscribe:</p>

```<code>val insertObservable1: Observable[Completed] =              collection.insertMany(docList);
            val latch1 = new CountDownLatch(1)

            insertObservable1.subscribe(new Observer[Completed] {

              override def onError(e: Throwable): Unit = {
                println("Error1")
                e.printStackTrace()
              }

              override def onSubscribe(subscription: Subscription): Unit = {
                subscription.request(java.lang.Long.MAX_VALUE)
                println("inserting1-------------")
              }

              override def onComplete(): Unit = {
                println("Completed1")
                latch1.countDown()
              }

              override def onNext(result: Completed): Unit = {
                println("Next1-----------")
              }

            })
            latch1.await()
          }
        })
</code>```

Title: mongodb with scala maven project

Body:
I am stuck on an issue. I have created a scala maven project where I am trying to communicate with mongo. My project is getting build successfuly and I do not get any error when I execute my project, but still no data is getting inserted in my mongodb.

If I insert data manually through mongo-cli then my code can read it but it is not even inserting a single record.
Could you please help me in finding where I am making mistakes.
My mongo version is 3.2.10

App.scala

package com.assignment.scala

import org.mongodb.scala._
import org.mongodb.scala.model.Aggregates._
import org.mongodb.scala.model.Filters._
import org.mongodb.scala.model.Projections._
import org.mongodb.scala.model.Sorts._
import org.mongodb.scala.model.Updates._
import org.mongodb.scala.model._

/**
 * @author ${user.name}
 */
object App {

  def main(args: Array[String]) {
    println("Calling insertDoc==")
    insertDoc()
  }

  def insertDoc() = {
    val mongoClient = MongoClient()
    val database = mongoClient.getDatabase("assignment")
    val collection = database.getCollection("links")

   println("collection find : " + collection.find())
   collection.find().subscribe(
  (user: Document) => println("document------------"+user.toJson()),
  (error: Throwable) => println(s"Query failed: ${error.getMessage}"),
  () => println("Done"))

    collection.drop()

    val bufferedSource = io.Source.fromFile("/home/impadmin/ServiceSource/ml-latest-small/links.csv")
    var firstLine = List[String]();
    var docList = List[Document]();
    for ((line,count) <- bufferedSource.getLines.zipWithIndex) {
      val cols = line.split(",").map(_.trim)
      if (firstLine.size <= 0 && cols.length > 0) {
        firstLine = cols.toList;
      } else {
        var doc: Document = Document("_id" -> count)
        for ((a, b) <- firstLine zip cols) {
          doc ++= Document(a -> b)
        }
        docList = docList :+ doc
        collection.insertOne(doc)
      }
    }

    val doc3 = Document("name" -> "MongoDB", "type" -> "database",
      "count" -> 1, "info" -> Document("x" -> 203, "y" -> 102))

   collection.insertOne(doc)
   collection.find().subscribe((doc1: Document) => println(doc1.toJson()),
   (e: Throwable) => println(s"There was an error: $e"))
  }
}

Body:
It worked using subscribe:

val insertObservable1: Observable[Completed] =              collection.insertMany(docList);
            val latch1 = new CountDownLatch(1)

            insertObservable1.subscribe(new Observer[Completed] {

              override def onError(e: Throwable): Unit = {
                println("Error1")
                e.printStackTrace()
              }

              override def onSubscribe(subscription: Subscription): Unit = {
                subscription.request(java.lang.Long.MAX_VALUE)
                println("inserting1-------------")
              }

              override def onComplete(): Unit = {
                println("Completed1")
                latch1.countDown()
              }

              override def onNext(result: Completed): Unit = {
                println("Next1-----------")
              }

            })
            latch1.await()
          }
        })


问:
Find & Replace - Google Sheets Script after GetData
I'm having some trouble with my script. Basically, that works getting data from one course and inputting the values to one Sheet. That's working perfectly. But when one of my students input 'enter' command at that course, I have trouble to read it in Excel.
SO, I have to find (it's a regular Expression: \r\n|\n|\r) and replace the enter at Google Spreadsheet and change it for "; ". Works perfectly doing it manually, but I can't do it by script. Here the piece:

```<code>     //  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "DATA";

//  2. Run > setup
//
//  3. Publish > Deploy as web app
//    - enter Project Version name and click 'Save New Version'
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and post this in your form/script action
//
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)

var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
  return handleResponse(e);
}
 function doPost(e){
  return handleResponse(e);
}

function handleResponse(e) {
  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

  try {
    // next set where we write the data - you could write to multiple/alternate destinations
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("CHANGED BY SECURITY REASON"));
    var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    var headRow = e.parameter.header_row || 1;
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = [];
    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(new Date());
      } else { // else use header name to get data
        row.push(e.parameter[headers[i]]);
      }
    }
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results
    return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(e){

    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  } finally { //release lock
    lock.releaseLock();
  }
}

function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("1Un5A61M8CJDBGDAB-Tx-lYgKYaVB2RSfn9QAQ5Q-sZs", doc.getId());
}
</code>```

I tried this and worked well, but needs a trigger that's play only minute per minute. Not ok.. And change just the first value from the cell. Sometimes there's more than one at same cell:

```<code>function Replace() {
    var redeletar = new RegExp("\r\n|\n|\r");
    var range = SpreadsheetApp.getActiveSheet()
        .getRange('A1:CH');
      range.setValues(range.getValues()
        .map(function (r) {
            return r.map(function (c) {
            //Replace string
              return c.toString().replace(redeletar, ";");
             });
     }));
}
</code>```

Any idea to play this script at same time after the Sheet receive de data from my course AND play it recursively?

Thanks so mucho

答:
I think all you need is the global flag as shown below:

```<code>function Replace()
 {
   var re = /(\r\n|\n|\r")/g;
   var range = SpreadsheetApp.getActiveSheet().getActiveRange();
   range.setValues(range.getValues().map(function (r){return r.map(function (c){return c.toString().replace(re, ";");});}));
 }
</code>```

I think this will make all of the replacements rather than just the first ones;

Body:
I'm having some trouble with my script. Basically, that works getting data from one course and inputting the values to one Sheet. That's working perfectly. But when one of my students input 'enter' command at that course, I have trouble to read it in Excel.
SO, I have to find (it's a regular Expression: \r\n|\n|\r) and replace the enter at Google Spreadsheet and change it for "; ". Works perfectly doing it manually, but I can't do it by script. Here the piece:

     //  1. Enter sheet name where data is to be written below
        var SHEET_NAME = "DATA";

//  2. Run > setup
//
//  3. Publish > Deploy as web app
//    - enter Project Version name and click 'Save New Version'
//    - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
//  4. Copy the 'Current web app URL' and post this in your form/script action
//
//  5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)

var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service

// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
  return handleResponse(e);
}
 function doPost(e){
  return handleResponse(e);
}

function handleResponse(e) {
  // shortly after my original solution Google announced the LockService[1]
  // this prevents concurrent access overwritting data
  // [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
  // we want a public lock, one that locks for all invocations
  var lock = LockService.getPublicLock();
  lock.waitLock(30000);  // wait 30 seconds before conceding defeat.

  try {
    // next set where we write the data - you could write to multiple/alternate destinations
    var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("CHANGED BY SECURITY REASON"));
    var sheet = doc.getSheetByName(SHEET_NAME);

    // we'll assume header is in row 1 but you can override with header_row in GET/POST data
    var headRow = e.parameter.header_row || 1;
    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
    var nextRow = sheet.getLastRow()+1; // get next row
    var row = [];
    // loop through the header columns
    for (i in headers){
      if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
        row.push(new Date());
      } else { // else use header name to get data
        row.push(e.parameter[headers[i]]);
      }
    }
    // more efficient to set values as [][] array than individually
    sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
    // return json success results
    return ContentService
          .createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
          .setMimeType(ContentService.MimeType.JSON);
  } catch(e){

    // if error return this
    return ContentService
          .createTextOutput(JSON.stringify({"result":"error", "error": e}))
          .setMimeType(ContentService.MimeType.JSON);
  } finally { //release lock
    lock.releaseLock();
  }
}

function setup() {
    var doc = SpreadsheetApp.getActiveSpreadsheet();
    SCRIPT_PROP.setProperty("1Un5A61M8CJDBGDAB-Tx-lYgKYaVB2RSfn9QAQ5Q-sZs", doc.getId());
}

I tried this and worked well, but needs a trigger that's play only minute per minute. Not ok.. And change just the first value from the cell. Sometimes there's more than one at same cell:

function Replace() {
    var redeletar = new RegExp("\r\n|\n|\r");
    var range = SpreadsheetApp.getActiveSheet()
        .getRange('A1:CH');
      range.setValues(range.getValues()
        .map(function (r) {
            return r.map(function (c) {
            //Replace string
              return c.toString().replace(redeletar, ";");
             });
     }));
}

Any idea to play this script at same time after the Sheet receive de data from my course AND play it recursively?

Thanks so mucho

Body:
I think all you need is the global flag as shown below:

function Replace()
 {
   var re = /(\r\n|\n|\r")/g;
   var range = SpreadsheetApp.getActiveSheet().getActiveRange();
   range.setValues(range.getValues().map(function (r){return r.map(function (c){return c.toString().replace(re, ";");});}));
 }

I think this will make all of the replacements rather than just the first ones;


问:
EditText AfterTextChanged Issue
I am trying to create a simple time calculator app using two EditText fields. The code below is just a normal calculator that adds up two numbers that I whipped up to test the text changed listener. For some reason, every time I run this application and input a number into either EditText fields, it just crashes and asks if I want to restart the app. I just want it to update the total every time the user finishes entering a number instead of having to press a button. Can somebody help me find the error? I have initialized the first few variables outside of the onCreate method.

Log Error:

```<code>  07-03 21:06:45.499 2397-2397/com.example.thesoulreaper.swimmingcalculator E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.thesoulreaper.swimmingcalculator, PID: 2397
    java.lang.NumberFormatException: empty String
        at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1071)
        at java.lang.Float.parseFloat(Float.java:459)
        at com.example.thesoulreaper.swimmingcalculator.OneHundredCalculatorActivity$3.afterTextChanged(OneHundredCalculatorActivity.java:103)
        at android.widget.TextView.sendAfterTextChanged(TextView.java:8202)
        at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:10381)
        at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:1218)
        at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:579)
        at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:230)
        at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:229)
        at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:251)
        at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:451)
        at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:91)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
</code>```

My code:

```<code>    fiftyEditText = (EditText) findViewById(R.id.FiftyEditText);
    hundredEditText = (EditText) findViewById(R.id.HundredEditText);
    totalTextView = (TextView) findViewById(R.id.totalTextView);

    fiftyEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(Integer.parseInt(hundredEditText.getText().toString()) > 0 && Integer.parseInt(fiftyEditText.getText().toString()) > 0) {
                int total = Integer.parseInt(hundredEditText.getText().toString()) + Integer.parseInt(fiftyEditText.getText().toString());
                totalTextView.setText(total);
            } else if(Integer.parseInt(hundredEditText.getText().toString()) <= 0 && Integer.parseInt(fiftyEditText.getText().toString()) > 0) {
                totalTextView.setText(Integer.parseInt(fiftyEditText.getText().toString()));
            } else if(Integer.parseInt(hundredEditText.getText().toString()) > 0 && Integer.parseInt(fiftyEditText.getText().toString()) <= 0) {
                totalTextView.setText(Integer.parseInt(hundredEditText.getText().toString()));
            } else if (Integer.parseInt(hundredEditText.getText().toString()) <= 0 && Integer.parseInt(fiftyEditText.getText().toString()) <= 0) {
                totalTextView.setText(0);
            }
        }
    });

    hundredEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(Integer.parseInt(hundredEditText.getText().toString()) > 0 && Integer.parseInt(fiftyEditText.getText().toString()) > 0) {
                int total = Integer.parseInt(hundredEditText.getText().toString()) + Integer.parseInt(fiftyEditText.getText().toString());
                totalTextView.setText(total);
            } else if(Integer.parseInt(hundredEditText.getText().toString()) <= 0 && Integer.parseInt(fiftyEditText.getText().toString()) > 0) {
                totalTextView.setText(Integer.parseInt(fiftyEditText.getText().toString()));
            } else if(Integer.parseInt(hundredEditText.getText().toString()) > 0 && Integer.parseInt(fiftyEditText.getText().toString()) <= 0) {
                totalTextView.setText(Integer.parseInt(hundredEditText.getText().toString()));
            } else if (Integer.parseInt(hundredEditText.getText().toString()) <= 0 && Integer.parseInt(fiftyEditText.getText().toString()) <= 0) {
                totalTextView.setText(0);
            }
        }
    });
</code>```

答:
Your app is crashing because you are trying to convert empty string to integer so add a check if the string is not empty

```<code>@Override
public void afterTextChanged(Editable editable) {

    int hundredEditTextValue =  hundredEditText.getText().toString().isEmpty() ? 0 : Integer.parseInt(hundredEditText.getText().toString());
    int fiftyEditTextValue =  fiftyEditText.getText().toString().isEmpty() ? 0 : Integer.parseInt(fiftyEditText.getText().toString());

    if(hundredEditTextValue > 0 && fiftyEditTextValue > 0) {
        int total = hundredEditTextValue + fiftyEditTextValue;
        totalTextView.setText(String.valueOf(total));
    } else if(hundredEditTextValue <= 0 && fiftyEditTextValue > 0) {
        totalTextView.setText(String.valueOf(fiftyEditTextValue));
    } else if(hundredEditTextValue > 0 && fiftyEditTextValue <= 0) {
        totalTextView.setText(String.valueOf(hundredEditTextValue));
    } else if (hundredEditTextValue <= 0 && fiftyEditTextValue <= 0) {
        totalTextView.setText(String.valueOf(0));
    }
}
</code>```

and just to make your edittext accepts only numbers add this in your xml

android:inputType="number"

```<code><EditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   .
   .
   android:inputType="number" />
</code>```

Title: EditText AfterTextChanged Issue

Body:
I am trying to create a simple time calculator app using two EditText fields. The code below is just a normal calculator that adds up two numbers that I whipped up to test the text changed listener. For some reason, every time I run this application and input a number into either EditText fields, it just crashes and asks if I want to restart the app. I just want it to update the total every time the user finishes entering a number instead of having to press a button. Can somebody help me find the error? I have initialized the first few variables outside of the onCreate method.

Log Error:

  07-03 21:06:45.499 2397-2397/com.example.thesoulreaper.swimmingcalculator E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.thesoulreaper.swimmingcalculator, PID: 2397
    java.lang.NumberFormatException: empty String
        at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1071)
        at java.lang.Float.parseFloat(Float.java:459)
        at com.example.thesoulreaper.swimmingcalculator.OneHundredCalculatorActivity$3.afterTextChanged(OneHundredCalculatorActivity.java:103)
        at android.widget.TextView.sendAfterTextChanged(TextView.java:8202)
        at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:10381)
        at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:1218)
        at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:579)
        at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:230)
        at android.text.SpannableStringBuilder.delete(SpannableStringBuilder.java:229)
        at android.view.inputmethod.BaseInputConnection.deleteSurroundingText(BaseInputConnection.java:251)
        at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:451)
        at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:91)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

My code:

    fiftyEditText = (EditText) findViewById(R.id.FiftyEditText);
    hundredEditText = (EditText) findViewById(R.id.HundredEditText);
    totalTextView = (TextView) findViewById(R.id.totalTextView);

    fiftyEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(Integer.parseInt(hundredEditText.getText().toString()) > 0 && Integer.parseInt(fiftyEditText.getText().toString()) > 0) {
                int total = Integer.parseInt(hundredEditText.getText().toString()) + Integer.parseInt(fiftyEditText.getText().toString());
                totalTextView.setText(total);
            } else if(Integer.parseInt(hundredEditText.getText().toString()) <= 0 && Integer.parseInt(fiftyEditText.getText().toString()) > 0) {
                totalTextView.setText(Integer.parseInt(fiftyEditText.getText().toString()));
            } else if(Integer.parseInt(hundredEditText.getText().toString()) > 0 && Integer.parseInt(fiftyEditText.getText().toString()) <= 0) {
                totalTextView.setText(Integer.parseInt(hundredEditText.getText().toString()));
            } else if (Integer.parseInt(hundredEditText.getText().toString()) <= 0 && Integer.parseInt(fiftyEditText.getText().toString()) <= 0) {
                totalTextView.setText(0);
            }
        }
    });

    hundredEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(Integer.parseInt(hundredEditText.getText().toString()) > 0 && Integer.parseInt(fiftyEditText.getText().toString()) > 0) {
                int total = Integer.parseInt(hundredEditText.getText().toString()) + Integer.parseInt(fiftyEditText.getText().toString());
                totalTextView.setText(total);
            } else if(Integer.parseInt(hundredEditText.getText().toString()) <= 0 && Integer.parseInt(fiftyEditText.getText().toString()) > 0) {
                totalTextView.setText(Integer.parseInt(fiftyEditText.getText().toString()));
            } else if(Integer.parseInt(hundredEditText.getText().toString()) > 0 && Integer.parseInt(fiftyEditText.getText().toString()) <= 0) {
                totalTextView.setText(Integer.parseInt(hundredEditText.getText().toString()));
            } else if (Integer.parseInt(hundredEditText.getText().toString()) <= 0 && Integer.parseInt(fiftyEditText.getText().toString()) <= 0) {
                totalTextView.setText(0);
            }
        }
    });

Body:
Your app is crashing because you are trying to convert empty string to integer so add a check if the string is not empty

@Override
public void afterTextChanged(Editable editable) {

    int hundredEditTextValue =  hundredEditText.getText().toString().isEmpty() ? 0 : Integer.parseInt(hundredEditText.getText().toString());
    int fiftyEditTextValue =  fiftyEditText.getText().toString().isEmpty() ? 0 : Integer.parseInt(fiftyEditText.getText().toString());

    if(hundredEditTextValue > 0 && fiftyEditTextValue > 0) {
        int total = hundredEditTextValue + fiftyEditTextValue;
        totalTextView.setText(String.valueOf(total));
    } else if(hundredEditTextValue <= 0 && fiftyEditTextValue > 0) {
        totalTextView.setText(String.valueOf(fiftyEditTextValue));
    } else if(hundredEditTextValue > 0 && fiftyEditTextValue <= 0) {
        totalTextView.setText(String.valueOf(hundredEditTextValue));
    } else if (hundredEditTextValue <= 0 && fiftyEditTextValue <= 0) {
        totalTextView.setText(String.valueOf(0));
    }
}

and just to make your edittext accepts only numbers add this in your xml

android:inputType="number"

<EditText
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   .
   .
   android:inputType="number" />


问:
How do I schedule a cron job to run every hour and a half?

Possible Duplicate:

  How can I set cron to run certain commands every one and a half hours?

I know that every two hours is:

```<code>* */2 * * * command-to-run
</code>```

but how do I schedule a cron job to run every hour and a half?

答:
You can do this as two cron jobs:

```<code>0   0,3,6,9,12,15,18,21  * * * myprog myargs
30  1,4,7,10,13,16,19,22 * * * myprog myargs
</code>```

This has the advantage of working on even ancient systems that don't support the /2-type syntax.

Body:
Possible Duplicate:

  How can I set cron to run certain commands every one and a half hours?

I know that every two hours is:

* */2 * * * command-to-run

but how do I schedule a cron job to run every hour and a half?

Body:
You can do this as two cron jobs:

0   0,3,6,9,12,15,18,21  * * * myprog myargs
30  1,4,7,10,13,16,19,22 * * * myprog myargs

This has the advantage of working on even ancient systems that don't support the /2-type syntax.

ContentLicense: CC BY-SA 2.5


问:
When designing structure of Deep neural net, why are numbers 256, 512, 32, 16 etc?
Is there a hard-ware reason why, say the number of nodes in a layer, is a power of 2?</p>

答: I am 99% certain most machine learning developers choose those numbers just because they increase it in orders of 2 until it works. No hardware reasons.</p>


问:
Webview not clearing previous page Android
I have a webView which changes its load url on a button click.
Everything is working fine except the loaded url seems to be not cleared properly.

The previous url is loaded in webview and is displayed just before the new url appears. I tried using

webView.clearView(),

webView.clearHistory(),

webView.loadUrl("about:blank"),

webView.clearCache(true)

and also tried clearing the cookies. But nothing helps clearing the webview properly.

I also tried webView.destroy(); but the webView is destroyed fully as I am nt able to load the next url.

Please help.

答:
This order worked for me </p>

```<code>        mWebView.clearCache(true);
        mWebView.clearHistory();
        clearCookies(this); // Activity context

 @SuppressWarnings("deprecation")
    private void clearCookies(Context context)
    {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().removeAllCookies(null);
            CookieManager.getInstance().flush();
        } else
        {
            CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
            cookieSyncMngr.startSync();
            CookieManager cookieManager=CookieManager.getInstance();
            cookieManager.removeAllCookie();
            cookieManager.removeSessionCookie();
            cookieSyncMngr.stopSync();
            cookieSyncMngr.sync();
        }
    }
</code>```

Body:
This order worked for me

        mWebView.clearCache(true);
        mWebView.clearHistory();
        clearCookies(this); // Activity context

 @SuppressWarnings("deprecation")
    private void clearCookies(Context context)
    {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().removeAllCookies(null);
            CookieManager.getInstance().flush();
        } else
        {
            CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context);
            cookieSyncMngr.startSync();
            CookieManager cookieManager=CookieManager.getInstance();
            cookieManager.removeAllCookie();
            cookieManager.removeSessionCookie();
            cookieSyncMngr.stopSync();
            cookieSyncMngr.sync();
        }
    }


问:
Javascript Calculation issue when there is a Space during calculating input value

function divideBy() {
  var w = document.getElementById("first").value;
  var x = document.getElementById("second").value;
  var y = w / x;
  y = y.toFixed(2);
  var z = y;
  document.getElementById("answer").innerHTML = z;
  var a = document.getElementById("first1").value;
  var b = document.getElementById("second1").value;
  var c = a / b;
  var d = c;
  d = d.toFixed(2);
  var e = d
  document.getElementById("answer1").innerHTML = e;
  document.getElementById('modal').style.visibility = 'hidden';
  document.getElementById('modal1').style.visibility = 'hidden';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr>
  <td class="normal">
    <div align="right">SGST @ 9% :</div>
  </td>
  <td nowrap class="normal">
    <div align="right">
      <div id="divCheckbox1" style="display: none;">
        <input type="number" step=0.001 id="first" value=1 000>
        <input type="number" step=0.001 id="second" value=2 .0>
      </div>
      <button type="button" id="modal1" onclick="divideBy()"></button>
      <span id="answer"></span>
      <span style="display:inline-block; width: 5;"></span>
  </td>
  <tr>
    <td class="normal">
      <div align="right">CGST @ 9% :</div>
    </td>
    <td nowrap class="normal">
      <div align="right">
        <div id="divCheckbox" style="display: none;">
          <input type="number" step=0.001 id="first1" value=1 000>
          <input type="number" step=0.001 id="second1" value=2 .0>
        </div>
        <button type="button" id="modal" onclick="divideBy()"></button>
        <span id=answer1></span>
        <span style="display:inline-block; width: 5;"></span>
    </td></code>```

答:
function removeSpace(text){
         return text.replace(/\s/g,'');
    }

        function divideBy() {
          var w = removeSpace(document.getElementById("first").value);
          var x = removeSpace(document.getElementById("second").value);
          var y = w / x;
          y = y.toFixed(2);
          var z = y;
          document.getElementById("answer").innerHTML = z;
          var a = removeSpace(document.getElementById("first1").value);
          var b = removeSpace(document.getElementById("second1").value);
          var c = a / b;
          var d = c;
          d = d.toFixed(2);
          var e = d
          document.getElementById("answer1").innerHTML = e;
          document.getElementById('modal').style.visibility = 'hidden';
          document.getElementById('modal1').style.visibility = 'hidden';
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
    <table>
        <tr>
          <td class="normal">
            <div align="right">SGST @ 9% :</div>
          </td>
          <td nowrap class="normal">
            <div align="right">
              <div id="divCheckbox1" >
                <input type="text" step=0.001 id="first"  value="1 000"/>
                <input type="text"  step=0.001 id="second" value="2 .0"/>
              </div>
              <button type="button" id="modal1" onclick="divideBy()">click here </button>
              <span id="answer"></span>
              <span style="display:inline-block; width: 5;"></span>
              </div>
          </td>
          </tr>
          <tr>
            <td class="normal">
              <div align="right">CGST @ 9% :</div>
            </td>
            <td nowrap class="normal">
              <div align="right">
                <div id="divCheckbox">
                  <input type="text"  step=0.001 id="first1" value="5 000"/>
                  <input type="text"  step=0.001 id="second1" value="3 .0"/>
                </div>
                <button type="button" id="modal" onclick="divideBy()">Click here1</button>
                <span id=answer1></span>
                <span style="display:inline-block; width: 5;"></span>
                </div>
            </td>
            </tr>
            </table>

    </code>```

Body:
function divideBy() {
  var w = document.getElementById("first").value;
  var x = document.getElementById("second").value;
  var y = w / x;
  y = y.toFixed(2);
  var z = y;
  document.getElementById("answer").innerHTML = z;
  var a = document.getElementById("first1").value;
  var b = document.getElementById("second1").value;
  var c = a / b;
  var d = c;
  d = d.toFixed(2);
  var e = d
  document.getElementById("answer1").innerHTML = e;
  document.getElementById('modal').style.visibility = 'hidden';
  document.getElementById('modal1').style.visibility = 'hidden';
}

SGST @ 9% :

        <input type="number" step=0.001 id="first" value=1 000>
        <input type="number" step=0.001 id="second" value=2 .0>

      <button type="button" id="modal1" onclick="divideBy()"></button>

CGST @ 9% :

          <input type="number" step=0.001 id="first1" value=1 000>
          <input type="number" step=0.001 id="second1" value=2 .0>

        <button type="button" id="modal" onclick="divideBy()"></button>

Body:
function removeSpace(text){
         return text.replace(/\s/g,'');
    }

        function divideBy() {
          var w = removeSpace(document.getElementById("first").value);
          var x = removeSpace(document.getElementById("second").value);
          var y = w / x;
          y = y.toFixed(2);
          var z = y;
          document.getElementById("answer").innerHTML = z;
          var a = removeSpace(document.getElementById("first1").value);
          var b = removeSpace(document.getElementById("second1").value);
          var c = a / b;
          var d = c;
          d = d.toFixed(2);
          var e = d
          document.getElementById("answer1").innerHTML = e;
          document.getElementById('modal').style.visibility = 'hidden';
          document.getElementById('modal1').style.visibility = 'hidden';
        }

    <table>
        <tr>
          <td class="normal">
            <div align="right">SGST @ 9% :</div>
          </td>
          <td nowrap class="normal">
            <div align="right">
              <div id="divCheckbox1" >
                <input type="text" step=0.001 id="first"  value="1 000"/>
                <input type="text"  step=0.001 id="second" value="2 .0"/>
              </div>
              <button type="button" id="modal1" onclick="divideBy()">click here </button>
              <span id="answer"></span>
              <span style="display:inline-block; width: 5;"></span>
              </div>
          </td>
          </tr>
          <tr>
            <td class="normal">
              <div align="right">CGST @ 9% :</div>
            </td>
            <td nowrap class="normal">
              <div align="right">
                <div id="divCheckbox">
                  <input type="text"  step=0.001 id="first1" value="5 000"/>
                  <input type="text"  step=0.001 id="second1" value="3 .0"/>
                </div>
                <button type="button" id="modal" onclick="divideBy()">Click here1</button>
                <span id=answer1></span>
                <span style="display:inline-block; width: 5;"></span>
                </div>
            </td>
            </tr>
            </table>


问:
order by clause in Mysql
I am writing a sql to get the medium of a list of numbers (assume the length of the list is odd)

set @r=0;
select S.num
from
(select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from T1
order by num) S
where rowIndex = ceil(@r/2)

This query works, however, I am confused by my subquery. My question is the following: if I simply type

select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from T1

I will have 2 columns with the 1st column being the original list of numbers in its original order, e.g., 10,1,3,11,5,4,19... and the 2nd column is the row index, 1,2,3,4,.... Note that what I want is first sort my original list in ascending order, then give each row its row index.

I initially thought that

select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from T1
order by num

will produce a table such that the 1st column is the sorted version of my original list, but then 2nd column is a rearrangement of the index set [1,2,3,...]. Because I think the order of the query is: first create a table as suggested by select num, case when num is not NULL then (@r:=@r+1) end as rowIndex from T1, then it sorts this table by num column, and hence, when num column is sorted, the rowIndex column should no longer be [1,2,3,...].

But actually, it seems that it first just sort the num column and then it add row index. In another word, I find that whether I add order by num or not, the 2nd column will always be a nice row index [1,2,3,4,...]. Why?

答:
The derived table (subquery) orders your num column and gives each row an index number according to that order. The outer query then re-uses the computed vale of @r to arrive at the half-way point (median) in that ordered series.

```<code>CREATE TABLE mytable(
   num NUMERIC(6,2)
);
</code>```

```<code>INSERT INTO mytable(num) VALUES (12.4);
INSERT INTO mytable(num) VALUES (134.9);
INSERT INTO mytable(num) VALUES (45.12);
INSERT INTO mytable(num) VALUES (876.78);
INSERT INTO mytable(num) VALUES (212.8);
INSERT INTO mytable(num) VALUES (578.9);
</code>```

```<code>set @r=0;
select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from mytable T1
order by num;
</code>```

```
   num | rowIndex
-----: | -------:
 12.40 |        1
 45.12 |        2
134.90 |        3
212.80 |        4
578.90 |        5
876.78 |        6
```

```<code>set @r=0;
select S.num
from (
    select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
    from mytable T1
    order by num
    ) S
where rowIndex = ceil(@r/2);
</code>```

```
|    num |
| -----: |
| 134.90 |
```

dbfiddle here

If we remove the order by however the results are not predictable. e.g.

```<code>set @r=0;
select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from mytable T1
;
</code>```

```
   num | rowIndex
-----: | -------:
 12.40 |        1
134.90 |        2
 45.12 |        3
876.78 |        4
212.80 |        5
578.90 |        6
```

```<code>set @r=0;
select S.num
from (
    select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
    from mytable T1
    ) S
where rowIndex = ceil(@r/2);
</code>```

```
|   num |
| ----: |
| 45.12 |
```

dbfiddle here

Without an explicit ORDER BY clause it is NOT safe to assume the number series will be ordered as you need it. It might occur, but you cannot rely on it.

Title: order by clause in Mysql

Body:
The derived table (subquery) orders your num column and gives each row an index number according to that order. The outer query then re-uses the computed vale of @r to arrive at the half-way point (median) in that ordered series.

CREATE TABLE mytable(
   num NUMERIC(6,2)
);

INSERT INTO mytable(num) VALUES (12.4);
INSERT INTO mytable(num) VALUES (134.9);
INSERT INTO mytable(num) VALUES (45.12);
INSERT INTO mytable(num) VALUES (876.78);
INSERT INTO mytable(num) VALUES (212.8);
INSERT INTO mytable(num) VALUES (578.9);

set @r=0;
select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from mytable T1
order by num;

   num | rowIndex
-----: | -------:
 12.40 |        1
 45.12 |        2
134.90 |        3
212.80 |        4
578.90 |        5
876.78 |        6

set @r=0;
select S.num
from (
    select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
    from mytable T1
    order by num
    ) S
where rowIndex = ceil(@r/2);

|    num |
| -----: |
| 134.90 |

dbfiddle here

If we remove the order by however the results are not predictable. e.g.

set @r=0;
select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
from mytable T1
;

   num | rowIndex
-----: | -------:
 12.40 |        1
134.90 |        2
 45.12 |        3
876.78 |        4
212.80 |        5
578.90 |        6

set @r=0;
select S.num
from (
    select num, case when num is not NULL then (@r:=@r+1) end as rowIndex
    from mytable T1
    ) S
where rowIndex = ceil(@r/2);

|   num |
| ----: |
| 45.12 |

dbfiddle here

Without an explicit ORDER BY clause it is NOT safe to assume the number series will be ordered as you need it. It might occur, but you cannot rely on it.


问:
add conditional style to IE in drupal
I want to add conditional style sheet to IE browser.I have tried to add it in themes html.tpl.php file as

```<code><!--[if IE]><link rel="stylesheet" type="text/css"  href="themes/themeName/css/ie_style.css"></link><![endif]-->
</code>```

this file path is also correct but not included for IE browser.

答:
Try this one, It will target all IE browsers below VERSIONS of IE 7. </p>

```<code><!--[if lt IE 7]><link rel="stylesheet" type="text/css" href="themes/themeName/css/ie_style.css"></link><![endif]-->
</code>```

Title: add conditional style to IE in drupal

Body:
I want to add conditional style sheet to IE browser.I have tried to add it in themes html.tpl.php file as

this file path is also correct but not included for IE browser.

Body:
Try this one, It will target all IE browsers below VERSIONS of IE 7.

<!--[if lt IE 7]><link rel="stylesheet" type="text/css" href="themes/themeName/css/ie_style.css"></link><![endif]-->


问:
Laravel - change specific tr bgcolor in views using controller based on parameter
I'm trying to change the color of my table rows based on my parameter. here's my code:

AdminController.php

```<code>public function table_row(){

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }
    return view('walks', compact('$highlightClass'));
}
</code>```

walks.blade.php

```<code><tr class="{{ $highlightClass }}">
</code>```

It didn't work.. :(

Here's the image of table in my views:

enter image description here

答:
Just remove $ from compact and try

return view('walks', compact('highlightClass'));

and learn how compact work actually in laravel :- [https://www.quora.com/What-does-compact-do-in-Laravel][1]

Body:
I'm trying to change the color of my table rows based on my parameter. here's my code:

AdminController.php

public function table_row(){

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }
    return view('walks', compact('$highlightClass'));
}

walks.blade.php

It didn't work.. :(

Here's the image of table in my views:

enter image description here


问:
Android Webview shouldoverrideurlloading only called when url redirected
I have a WebView inside of an activity and it has a webviewclient with shouldoverrideurlloading.

When I load https://mobile.twitter.com/, shouldoverrideurlloading not called because it doesn't redirected,
but it works when load http://mobile.twitter.com. (http protocol redirects to http)

I have tested almost 20 urls, shouldoverrideurlloading called only when url redirected.

Is there any conditions or settings required to use shouldoverrideurlloading in any cases? (Except POST)

答:
when you use loadUrl on WebView, it won't call shouldoverrideurlloading because you don't need it, and you can decide if you want the WebView to load the URL, or you want to handle it on your own before passing to the WebView.

shouldoverrideurlloading will be called when the WebView changes it's URL not by your will, but for example when user clicks on the link in the WebView, or the redirect happens.


答:
As people have pointed out in comments value = 1 000 wont work, because me and you can see 1 000 as 1000 but the computer cannot. It assumes it as value = 1 (000 is ignored). So you can write it as value = 1000 ans also in the next line value = 2.0. Do not give spaces in between digits (because the language doesn't allows that.

Also you are not closing both divs in each tr.

So, to make the code work, all you need to do is change the value = 1 000 to value = 1000 and value = 2 .0 to value = 2.0, and check all the elements are properly placed according to HTML syntax.

This snippet works according to your javascript code.

function divideBy() {
  var w = document.getElementById("first").value;
  var x = document.getElementById("second").value;
  var y = w / x;
  y = y.toFixed(2);
  var z = y;
  document.getElementById("answer").innerHTML = z;
  var a = document.getElementById("first1").value;
  var b = document.getElementById("second1").value;
  var c = a / b;
  var d = c;
  d = d.toFixed(2);
  var e = d
  document.getElementById("answer1").innerHTML = e;
  document.getElementById('modal').style.visibility = 'hidden';
  document.getElementById('modal1').style.visibility = 'hidden';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tr>
  <td class="normal">
    <div align="right">SGST @ 9% :</div>
  </td>
  <td nowrap class="normal">
    <div align="right">
      <div id="divCheckbox1" style="display: none;">
        <input type="number" step=0.001 id="first" value=1 000>
        <input type="number" step=0.001 id="second" value=2 .0>
      </div>
      <button type="button" id="modal1" onclick="divideBy()"></button>
      <span id="answer"></span>
      <span style="display:inline-block; width: 5;"></span>
      </div>
  </td>
  <tr>
    <td class="normal">
      <div align="right">CGST @ 9% :</div>
    </td>
    <td nowrap class="normal">
      <div align="right">
        <div id="divCheckbox" style="display: none;">
          <input type="number" step=0.001 id="first1" value=1000>
          <input type="number" step=0.001 id="second1" value=2.0>
        </div>
        <button type="button" id="modal" onclick="divideBy()"></button>
        <span id=answer1></span>
        <span style="display:inline-block; width: 5;"></span>
        </div>
    </td>
    </table></code>```

Title: Javascript Calculation issue when there is a Space during calculating input value

Body:
As people have pointed out in comments value = 1 000 wont work, because me and you can see 1 000 as 1000 but the computer cannot. It assumes it as value = 1 (000 is ignored). So you can write it as value = 1000 ans also in the next line value = 2.0. Do not give spaces in between digits (because the language doesn't allows that.

Also you are not closing both divs in each tr.

So, to make the code work, all you need to do is change the value = 1 000 to value = 1000 and value = 2 .0 to value = 2.0, and check all the elements are properly placed according to HTML syntax.

This snippet works according to your javascript code.

function divideBy() {
  var w = document.getElementById("first").value;
  var x = document.getElementById("second").value;
  var y = w / x;
  y = y.toFixed(2);
  var z = y;
  document.getElementById("answer").innerHTML = z;
  var a = document.getElementById("first1").value;
  var b = document.getElementById("second1").value;
  var c = a / b;
  var d = c;
  d = d.toFixed(2);
  var e = d
  document.getElementById("answer1").innerHTML = e;
  document.getElementById('modal').style.visibility = 'hidden';
  document.getElementById('modal1').style.visibility = 'hidden';
}

<table>
<tr>
  <td class="normal">
    <div align="right">SGST @ 9% :</div>
  </td>
  <td nowrap class="normal">
    <div align="right">
      <div id="divCheckbox1" style="display: none;">
        <input type="number" step=0.001 id="first" value=1 000>
        <input type="number" step=0.001 id="second" value=2 .0>
      </div>
      <button type="button" id="modal1" onclick="divideBy()"></button>
      <span id="answer"></span>
      <span style="display:inline-block; width: 5;"></span>
      </div>
  </td>
  <tr>
    <td class="normal">
      <div align="right">CGST @ 9% :</div>
    </td>
    <td nowrap class="normal">
      <div align="right">
        <div id="divCheckbox" style="display: none;">
          <input type="number" step=0.001 id="first1" value=1000>
          <input type="number" step=0.001 id="second1" value=2.0>
        </div>
        <button type="button" id="modal" onclick="divideBy()"></button>
        <span id=answer1></span>
        <span style="display:inline-block; width: 5;"></span>
        </div>
    </td>
    </table>


问:
How to replace Email id text before @ with * in swift 3.0
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

```<code>    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")
</code>```

Any suggestion is accepted.

Thank you.

答:
You can do like,</p>

```<code>    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    let arr = newstr.components(separatedBy: delimiter)

    let resultStr = "xxxxxx" + "@" + arr[1]

    print(resultStr)
</code>```

Body:
Hello I have not get perfect solution for how to replace Email Id text before @ with * like

suppose my email id is XXXXXXX@gmail.com then my output I want like *******@gmail.com

I try like this

    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    var token = newstr.components(separatedBy: delimiter)

    let newQuery = (token[0] as NSString).replacingCharacters(
        in: NSMakeRange(0,token[0].characters.count), with: "*")

Any suggestion is accepted.

Thank you.

Body:
You can do like,

    let delimiter = "@"
    let newstr = "Himmoradiya@gmail.com"
    let arr = newstr.components(separatedBy: delimiter)

    let resultStr = "xxxxxx" + "@" + arr[1]

    print(resultStr)


问:
How to set the selected item color in the spinner?
```<code><Spinner
     android:id="@+id/spinner1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/editText1F"
     android:layout_alignTop="@+id/txtLabel1F"
     android:entries="@array/cat_array"
     android:prompt="@string/cat_promt"
     android:textColor="#ffffff"
   />
</code>```

My Background is black and the item showing is with gray bg and black font color. But when it come to the selected it shows the font as black so it is not being seen. How do I change the color in it?

答:
If you are using MaterialBetterSpinner and Binding your Layouts,

try this, hope it helps you:

```<code>public class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
        rowBinding.tv1.setText(mMy.getValues().get(position));
        if(position == mMy.getCurrentIndex()) {
            rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
            rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
        }
        return rowBinding.getRoot();
    }
}
</code>```

Your XML should be something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<layout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@color/colorBackgroundStart">
        <TextView
            android:id="@+id/tv1"
            android:layout_width="0dp"
            android:layout_weight="0.7"
            android:layout_height="30dp"
            android:textColor="#fff"
            android:textSize="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="8dp"/>
    </LinearLayout>
</layout>
</code>```

create a spinner with this adapter and yourXML :

```<code>final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());

final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);
</code>```

Body:
<Spinner
     android:id="@+id/spinner1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_alignLeft="@+id/editText1F"
     android:layout_alignTop="@+id/txtLabel1F"
     android:entries="@array/cat_array"
     android:prompt="@string/cat_promt"
     android:textColor="#ffffff"
   />

My Background is black and the item showing is with gray bg and black font color. But when it come to the selected it shows the font as black so it is not being seen. How do I change the color in it?

Body:
If you are using MaterialBetterSpinner and Binding your Layouts,

try this, hope it helps you:

public class MyAdapter extends ArrayAdapter<String> {

    public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
        super(context, textViewResourceId, objects);

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
        rowBinding.tv1.setText(mMy.getValues().get(position));
        if(position == mMy.getCurrentIndex()) {
            rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
            rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
        }
        return rowBinding.getRoot();
    }
}

Your XML should be something like this:

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@color/colorBackgroundStart">
        <TextView
            android:id="@+id/tv1"
            android:layout_width="0dp"
            android:layout_weight="0.7"
            android:layout_height="30dp"
            android:textColor="#fff"
            android:textSize="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="8dp"/>
    </LinearLayout>
</layout>

create a spinner with this adapter and yourXML :

final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());

final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);


问:
Menu status CUR not working
Cant get the CUR status working. the menue always have the classes marked with 0 instead of those marked with 2. what i am doing wrong? My typoscript code:</p>

```<code>10.marks {
MENU_OBEN = HMENU
MENU_OBEN {
  special = directory
  special.value = 10
  1 = TMENU
  1 {
    wrap = <ul>|</ul>
    noBlur = 1
    NO = 1
    NO {
      allWrap = <li class="first0"> | </li> |*| <li class="normal0"> | </li> |*| <li class="last0"> | </li>
      stdWrap.wrap = <strong> | </strong> |*| | |*| <b> | </b>
    }
    CUR = 1
    CUR {
      allWrap = <li class="first2"> | </li> |*| <li class="normal2"> | </li> |*| <li class="last2"> | </li>
      stdWrap.wrap = <strong> | </strong> |*| | |*| <b> | </b>
    }
  }
}
</code>```

答:
In my general ts template I have no NO=1. Instead I copy the NO status into CUR. I really dont know why, but it works for me this way.

e.g.

```<code>    NO.wrapItemAndSub = <li> | </li>
    NO.stdWrap.htmlSpecialChars = 1

    CUR < .NO
    CUR = 1
    CUR.ATagParams = class="cur"

    ACT < .NO
    ACT = 1
    ACT.ATagParams = class="act"
</code>```

Title: Menu status CUR not working

Body:
Cant get the CUR status working. the menue always have the classes marked with 0 instead of those marked with 2. what i am doing wrong? My typoscript code:

10.marks {
MENU_OBEN = HMENU
MENU_OBEN {
  special = directory
  special.value = 10
  1 = TMENU
  1 {
    wrap =
|

    noBlur = 1
    NO = 1
    NO {
      allWrap =
 |
 |*|
 |
 |*|
 |

      stdWrap.wrap =  |  |*| | |*|  |
    }
    CUR = 1
    CUR {
      allWrap =
 |
 |*|
 |
 |*|
 |

      stdWrap.wrap =  |  |*| | |*|  |
    }
  }
}

Body:
In my general ts template I have no NO=1. Instead I copy the NO status into CUR. I really dont know why, but it works for me this way.

e.g.

    NO.wrapItemAndSub = <li> | </li>
    NO.stdWrap.htmlSpecialChars = 1

    CUR < .NO
    CUR = 1
    CUR.ATagParams = class="cur"

    ACT < .NO
    ACT = 1
    ACT.ATagParams = class="act"


问:
Can't import self created NPM package in Typescript code
I have a web project written in Typescript (2.1.6) and compiled with Webpack in VScode.
I have a logging client as a third party that I'm currently trying to upload to NPM and use it as a normal dependency.

That logging client was originally written in the "old" Typescript syntax using the old Typescript modules (those that compile into Javascript objects), so I rewrote the code to use the import/export syntax.
I'm compiling the refactored logging code with the module flag set to "umd" and with ES5 as the target script.
I'm creating a single d.ts file for it using the dts-generator npm package.

Currently it looks kinda like this: (I don't really have the code in front of me, but this is the general idea)

The refactored code for the Logger.ts looks something like this:

```<code>import { LoggerSettings } from "./LoggerSetting";
import { AjaxRequest } from "./AjaxRequest";

// ... more of the same
export class Logger {
    // Implementation
}
</code>```

The d.ts that is created looks something like this:

```<code>declare module "logging-client" {
    export class LoggerSettings {
        // ...
    }
}

declare module "logging-client" {
    export class Logger {
        // ...
    }
}
</code>```

The package.json looks like this:

```<code>{
    "name": "logging-client",
    "main": "Logger.js",
    "types": "logging-client.d.ts"
}
</code>```

When trying to import the Logger into my typescript code, I'm getting a "can't find the logging-client module".

How can I even start diagnosing such a problem?
Am I doing something wrong?

Thanks in advance, Avi :)

EDIT: If anyone's interested, here's a git repo with the problem:
https://github.com/avrahams1/LogError

答:
I know it's been a while, just want to close this one.
There isn't a way to re-conciliate old and new Typescript syntax, I had to re-write the old logger to conform to the ES6 module syntax. </p>

Body:
I have a web project written in Typescript (2.1.6) and compiled with Webpack in VScode.
I have a logging client as a third party that I'm currently trying to upload to NPM and use it as a normal dependency.

That logging client was originally written in the "old" Typescript syntax using the old Typescript modules (those that compile into Javascript objects), so I rewrote the code to use the import/export syntax.
I'm compiling the refactored logging code with the module flag set to "umd" and with ES5 as the target script.
I'm creating a single d.ts file for it using the dts-generator npm package.

Currently it looks kinda like this: (I don't really have the code in front of me, but this is the general idea)

The refactored code for the Logger.ts looks something like this:

import { LoggerSettings } from "./LoggerSetting";
import { AjaxRequest } from "./AjaxRequest";

// ... more of the same
export class Logger {
    // Implementation
}

The d.ts that is created looks something like this:

declare module "logging-client" {
    export class LoggerSettings {
        // ...
    }
}

declare module "logging-client" {
    export class Logger {
        // ...
    }
}

The package.json looks like this:

{
    "name": "logging-client",
    "main": "Logger.js",
    "types": "logging-client.d.ts"
}

When trying to import the Logger into my typescript code, I'm getting a "can't find the logging-client module".

How can I even start diagnosing such a problem?
Am I doing something wrong?

Thanks in advance, Avi :)

EDIT: If anyone's interested, here's a git repo with the problem:
https://github.com/avrahams1/LogError


问:
Powershell handling of System.Net.WebException
Having almost mastered using Powershell Invoke-WebRequest I'm now embarking on trying to get control of exception errors

In this first piece of code I've got to handle the exceptions returned from the web service ok. You can see a 400 code is returned along with a Message description and a detailed message.

```<code>Try {
    $what = Invoke-WebRequest -Uri $GOODURL -Method Post -Body $RequestBody -ContentType $ContentType
}

catch [System.Net.WebException] {
    $Request = $_.Exception
    Write-host "Exception caught: $Request"

    $crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
    Write-Output $crap;
    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output $crapMessage;
    $crapdescription = ($_.ErrorDetails.Message).ToString().Trim();
    Write-Output $crapdescription;
 }
</code>```

Output returned. Nice!

```<code>Exception caught: System.Net.WebException: The remote server returned an error: (400) Bad Request.
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
   400
   The remote server returned an error: (400) Bad Request.
   Modus.queueFailed Could not queue message http://schemas.xmlsoap.org/soap/actor/next
</code>```

That's very cool, however as part of my testing I wanted simulate connection errors, so I fed the script an invalid URI and immediately my error handling in the above code crashed.

Specifically, the invalid URI fell over on the "$_.Exception.Response.StatusCode.value__" and "$_.ErrorDetails.Message" presumably because they don't exist in the System.Net.WebException object returned

So, I took them out as a test and sure enough it works with the invalid URL as expected as below

```<code>Try {
    $what = Invoke-WebRequest -Uri $BADURL -Method Post -Body $RequestBody -ContentType $ContentType
}

catch [System.Net.WebException] {
    $Request = $_.Exception
    Write-host "Exception caught: $Request"

    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output $crapMessage;
 }
</code>```

And I get this (also nice)

```<code>Exception caught: System.Net.WebException: The remote name could not be resolved: 'gateway.zzzzsonicmobile.com'
   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.SetRequestContent(WebRequest request, String content)
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
   at System.Management.Automation.CommandProcessor.ProcessRecord()

   The remote name could not be resolved: 'gateway.zzzzsonybile.com'
</code>```

Trouble is, the first example gets everything I want from the exception object but won't work with an invalid URL. The second example handles the invalid URL (connection errors), but I can't figure out how to get hold of the 400 StatusCode and the ErrorDetails.Message

I would really like to do that, if at all possible.

Is there a way of setting this up to handle all exception handling..?

Any help, much appreciated..!

答:
I think you're probably only seeing an issue because you're trying to do the .ToString().Trim() methods on those properties when they don't exist. I'm not sure doing those methods even adds a lot of value, so I'd be tempted to just remove them.

Alternatively, you could put If blocks around them so that they are only output if they have value:

```<code>If ($_.Exception.Response.StatusCode.value__) {
    $crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
    Write-Output $crap;
}
If  ($_.Exception.Message) {
    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output $crapMessage;
}
</code>```

Body:
Having almost mastered using Powershell Invoke-WebRequest I'm now embarking on trying to get control of exception errors

In this first piece of code I've got to handle the exceptions returned from the web service ok. You can see a 400 code is returned along with a Message description and a detailed message.

Try {
    $what = Invoke-WebRequest -Uri $GOODURL -Method Post -Body $RequestBody -ContentType $ContentType
}

catch [System.Net.WebException] {
    $Request = $_.Exception
    Write-host "Exception caught: $Request"

    $crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
    Write-Output $crap;
    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output $crapMessage;
    $crapdescription = ($_.ErrorDetails.Message).ToString().Trim();
    Write-Output $crapdescription;
 }

Output returned. Nice!

Exception caught: System.Net.WebException: The remote server returned an error: (400) Bad Request.
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
   400
   The remote server returned an error: (400) Bad Request.
   Modus.queueFailed Could not queue message http://schemas.xmlsoap.org/soap/actor/next

That's very cool, however as part of my testing I wanted simulate connection errors, so I fed the script an invalid URI and immediately my error handling in the above code crashed.

Specifically, the invalid URI fell over on the "$_.Exception.Response.StatusCode.value__" and "$_.ErrorDetails.Message" presumably because they don't exist in the System.Net.WebException object returned

So, I took them out as a test and sure enough it works with the invalid URL as expected as below

Try {
    $what = Invoke-WebRequest -Uri $BADURL -Method Post -Body $RequestBody -ContentType $ContentType
}

catch [System.Net.WebException] {
    $Request = $_.Exception
    Write-host "Exception caught: $Request"

    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output $crapMessage;
 }

And I get this (also nice)

Exception caught: System.Net.WebException: The remote name could not be resolved: 'gateway.zzzzsonicmobile.com'
   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.SetRequestContent(WebRequest request, String content)
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
   at System.Management.Automation.CommandProcessor.ProcessRecord()

   The remote name could not be resolved: 'gateway.zzzzsonybile.com'

Trouble is, the first example gets everything I want from the exception object but won't work with an invalid URL. The second example handles the invalid URL (connection errors), but I can't figure out how to get hold of the 400 StatusCode and the ErrorDetails.Message

I would really like to do that, if at all possible.

Is there a way of setting this up to handle all exception handling..?

Any help, much appreciated..!

Body:
I think you're probably only seeing an issue because you're trying to do the .ToString().Trim() methods on those properties when they don't exist. I'm not sure doing those methods even adds a lot of value, so I'd be tempted to just remove them.

Alternatively, you could put If blocks around them so that they are only output if they have value:

If ($_.Exception.Response.StatusCode.value__) {
    $crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
    Write-Output $crap;
}
If  ($_.Exception.Message) {
    $crapMessage = ($_.Exception.Message).ToString().Trim();
    Write-Output $crapMessage;
}


问:
how to implement confirm on exit in angular 4?
I want to know how can I implement a confirm-on-exit component so that on page refresh or leaving tab or window or screen I can execute a confirm on exit method, so that if user click OK he will leave the screen and on click on NO he will remain on same screen?

Code I am using here is:

```<code>import { Component, OnInit, Input, Output, HostListener } from '@angular/core';
@Component({
    selector: 'confirmonexit',
    templateUrl: './confirm-on-exit.html'
})
export class ConfirmOnExitComponent {
    @Input() isDirty: boolean;
    public isConfirmed: boolean = false;
    @HostListener('window:beforeunload',['$event']) beforeUnloadHander() {
        if (this.isDirty) {
            let msg: string = 'Are you sure you want to navigate without saving the entered data on the screen ? '
            if (confirm(msg)) {
                this.isDirty = false;
                this.isConfirmed = false;
            } else {
                this.isDirty = true;
                event.preventDefault();
            }
        }
    }
}

appModule added - this component in declarations
html added =  <confirmonexit [isDirty]="CreateEditForm.form.dirty"></confirmonexit>
</code>```

I don't know where the mistake is. I am not able to execute this functionality. Could anyone help me out?

答:
you can use angular deactivate guard on a route .This will execute as soon as you try to navigate away from any route.For example you can refer this
https://scotch.io/courses/routing-angular-2-applications/candeactivate

SO if you are using a form then you can pass the form to the guard and then check for form state.if it is dirty it means it has been changed and then you can show the confirm dialog to the user

Body:
I want to know how can I implement a confirm-on-exit component so that on page refresh or leaving tab or window or screen I can execute a confirm on exit method, so that if user click OK he will leave the screen and on click on NO he will remain on same screen?

Code I am using here is:

import { Component, OnInit, Input, Output, HostListener } from '@angular/core';
@Component({
    selector: 'confirmonexit',
    templateUrl: './confirm-on-exit.html'
})
export class ConfirmOnExitComponent {
    @Input() isDirty: boolean;
    public isConfirmed: boolean = false;
    @HostListener('window:beforeunload',['$event']) beforeUnloadHander() {
        if (this.isDirty) {
            let msg: string = 'Are you sure you want to navigate without saving the entered data on the screen ? '
            if (confirm(msg)) {
                this.isDirty = false;
                this.isConfirmed = false;
            } else {
                this.isDirty = true;
                event.preventDefault();
            }
        }
    }
}

appModule added - this component in declarations
html added =  <confirmonexit [isDirty]="CreateEditForm.form.dirty"></confirmonexit>

I don't know where the mistake is. I am not able to execute this functionality. Could anyone help me out?


问:
How to get the bar names from Google Chart api
I am stuck for a couple of days!

I making an app that show cat breeds and when they are discovered in europe.

This is my code:

Since I can't post my code here because the forum want to reformat it.

Check my Google drive:

My code

https://docs.google.com/document/d/1wiwgFI3tGimvXKzOinLUZMYXAaMVscECeQopiyEHB98/edit?usp=sharing

And It returns a good looking chart that looks like this:

What I trying to do is getting the name that's inside a bar of the timeline.
As an example, if I click on "pers(ion)" , I want to make dynamicaly a div with more information about the pers(ion). But because it doesn't get a class or id I can't get it.

Does anybody now an easy way do do this?

答:
This will help you get the name of the BAR.
If you data is

```<code>var data = new google.visualization.arrayToDataTable([
    ['Object', 'Count'],
    ["ApexClass", apexCount],
    ["Sobjects", objectCount],
    ["ApexPage", vfPageCount],
    ["Role", rolesCount],
    ["Dashboard", dashboardCount],
    ["Profile", profileCount]

    ]);
</code>```

Then in select Handler write this

```<code>google.visualization.events.addListener(barchart, 'select', countsChartSelectListener);
    function countsChartSelectListener(){
        var selectedItem = barchart.getSelection()[0];
        if (selectedItem) {
            var barName = data.getValue(selectedItem.row, 0);
</code>```

Body:
This will help you get the name of the BAR.
If you data is

var data = new google.visualization.arrayToDataTable([
    ['Object', 'Count'],
    ["ApexClass", apexCount],
    ["Sobjects", objectCount],
    ["ApexPage", vfPageCount],
    ["Role", rolesCount],
    ["Dashboard", dashboardCount],
    ["Profile", profileCount]

    ]);

Then in select Handler write this

google.visualization.events.addListener(barchart, 'select', countsChartSelectListener);
    function countsChartSelectListener(){
        var selectedItem = barchart.getSelection()[0];
        if (selectedItem) {
            var barName = data.getValue(selectedItem.row, 0);


问:
Remove first gallery in post content in Wordpress
Despite of looking so simple, I don't know why the below code doesn't removes the first gallery from the post content.

```<code>function remove_slider($content){
    $c=str_replace(get_post_gallery(),"",$content);
    return $c;
}
add_filter("the_content","remove_slider");
</code>```

Thanks in advance.

答:
try this</p>

```<code>function wpse125903_remove_the_first_gallery( $output, $attr )
{
    // Run only once
    remove_filter( current_filter(), __FUNCTION__ );

    // Override the first gallery output
    return '<!-- gallery 1 was here -->';   // Must be non-empty.
}

add_filter( 'post_gallery', 'wpse125903_remove_the_first_gallery', 10, 2 );
</code>```

Body:
Despite of looking so simple, I don't know why the below code doesn't removes the first gallery from the post content.

function remove_slider($content){
    $c=str_replace(get_post_gallery(),"",$content);
    return $c;
}
add_filter("the_content","remove_slider");

Thanks in advance.

Body:
try this

function wpse125903_remove_the_first_gallery( $output, $attr )
{
    // Run only once
    remove_filter( current_filter(), __FUNCTION__ );

    // Override the first gallery output
    return '<!-- gallery 1 was here -->';   // Must be non-empty.
}

add_filter( 'post_gallery', 'wpse125903_remove_the_first_gallery', 10, 2 );


问:
Dynamically create function name and execute them
In nodejs 8, I try to insert 10 records int mongodb

```<code>// create company
await mylib.defaultCompany1SavePromise();
await mylib.defaultCompany2SavePromise();
await mylib.defaultCompany3SavePromise();
await mylib.defaultCompany4SavePromise();
await mylib.defaultCompany5SavePromise();
await mylib.defaultCompany6SavePromise();
await mylib.defaultCompany7SavePromise();
await mylib.defaultCompany8SavePromise();
await mylib.defaultCompany9SavePromise();
await mylib.defaultCompany10SavePromise();
</code>```

Is it a way to dynamically create function name and execute them?

Update 1, can I do something like this:

```<code>for(let index=1; index<=9; index++) {
  mylib.defaultCompany{index}SavePromise();
}
</code>```

答:
Create and execute functions in one loop

```<code>for (let index = 1; index <= 9; index++) {
    const fnName = 'defaultCompany' + index + 'SavePromise';
    // create function
    mylib[fnName] = function () {
        // function body
    };
    // run function
    mylib[fnName]();
}
</code>```

or you can execute those functions in another loop.

But in my opinion it's better to pass index into function and modify it's behavior based on index

Body:
In nodejs 8, I try to insert 10 records int mongodb

// create company
await mylib.defaultCompany1SavePromise();
await mylib.defaultCompany2SavePromise();
await mylib.defaultCompany3SavePromise();
await mylib.defaultCompany4SavePromise();
await mylib.defaultCompany5SavePromise();
await mylib.defaultCompany6SavePromise();
await mylib.defaultCompany7SavePromise();
await mylib.defaultCompany8SavePromise();
await mylib.defaultCompany9SavePromise();
await mylib.defaultCompany10SavePromise();

Is it a way to dynamically create function name and execute them?

Update 1, can I do something like this:

for(let index=1; index<=9; index++) {
  mylib.defaultCompany{index}SavePromise();
}

Body:
Create and execute functions in one loop

for (let index = 1; index <= 9; index++) {
    const fnName = 'defaultCompany' + index + 'SavePromise';
    // create function
    mylib[fnName] = function () {
        // function body
    };
    // run function
    mylib[fnName]();
}

or you can execute those functions in another loop.

But in my opinion it's better to pass index into function and modify it's behavior based on index


问:
How to change the erroring code background color in eclipse CDT
As you can see below,how to change the background color of erroring code?
<img src="https://i.stack.imgur.com/xLshL.png" alt="How to change the background color of erroring code?">  </p>

答:
It seems to me that, in addition to the new background color being a poor choice, those lines shouldn't be changing background color at all.

Please file a bug with details.

In the meantime, you can look in Preferences | General | Appearance | Colors and Fonts or Preferences | General | Editors | Text Editors | Appearance color options to see if you can find the offending background color and change it to something better.