问:
Fatal error: Call to undefined function add_shortcode_param()
I updated the WP Bakery Visual Composer and my site is down. This is the error I get

Fatal error: Call to undefined function add_shortcode_param() in
  /usr/www/users/capecoz/wp-content/themes/jkreativ-themes/admin/vc/extend.php
  on line 27

答:
Add_shortcode_param().

This function was called, but it's not defined, so you will need to define this function in your theme's function.php file.


来源: stackexchange

问:
How to simulate C++ friend in C# and VB.NET?
Because sometimes, I really need a friend.

I can think of the following tricks:

Read only wrapper - like ReadOnlyCollection. The friend keeps the pointer to the modifiable object, while everyone else can access only the wrapper.

Write delegate - the friend gives the constructor of the object a reference to a delegate as one of the parameters, the constructor fills it with an address to a private method that can be used to modify the object.

Reflection - obviously a bad idea. Included for completeness.

Multiple assemblies - put your friends together in a separate assembly and set your modifier methods internal.

Expose the modifiable object, but add comments to modifier methods "This is an infrastructure method - don't call it!"

Nested classes.

Add System.ComponentModel.EditorBrowsable(System.ComponentModel.
EditorBrowsableState.Never) attribute to the member you want only the friend to access to hide it from IntelliSense.

Implicit interface implementation - see comments.

Is this list exhaustive? Can anyone sort these in order of decreasing performance? Order of decreasing neatness? Any suggestions when to use which?

答:
You can also use the InternalsVisibleTo attribute.

For a given assembly, A, you can specify which other assemblies can have access to A's internal types.

ContentLicense: CC BY-SA 2.5


问:
GZIP compression to a byte array
I am trying to write a class that can compress data. The below code fails (no exception is thrown, but the target .gz file is empty.)

Besides: I don't want to generate the .gz file directly like it is done in all examples. I only want to get the compressed
data, so that I can e.g. encrypt it before writting the data to a file.

If I write directly to a file everything works fine:

```<code>import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;

public class Zipper
{
  public static void main(String[] args)
  {
    byte[] dataToCompress = "This is the test data."
      .getBytes(StandardCharsets.ISO_8859_1);

    GZIPOutputStream zipStream = null;
    FileOutputStream fileStream = null;
    try
    {
      fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
      zipStream = new GZIPOutputStream(fileStream);
      zipStream.write(dataToCompress);

      fileStream.write(compressedData);
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      try{ zipStream.close(); }
        catch(Exception e){ }
      try{ fileStream.close(); }
        catch(Exception e){ }
    }
  }
}
</code>```

But, if I want to 'bypass' it to the byte array stream it does not produce a single byte - compressedData is always empty.

```<code>import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;

public class Zipper
{
  public static void main(String[] args)
  {
    byte[] dataToCompress = "This is the test data."
      .getBytes(StandardCharsets.ISO_8859_1);
    byte[] compressedData = null;

    GZIPOutputStream zipStream = null;
    ByteArrayOutputStream byteStream = null;
    FileOutputStream fileStream = null;
    try
    {
      byteStream = new ByteArrayOutputStream(dataToCompress.length);
      zipStream = new GZIPOutputStream(byteStream);
      zipStream.write(dataToCompress);

      compressedData = byteStream.toByteArray();

      fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
      fileStream.write(compressedData);
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      try{ zipStream.close(); }
        catch(Exception e){ }
      try{ byteStream.close(); }
        catch(Exception e){ }
      try{ fileStream.close(); }
        catch(Exception e){ }
    }
  }
}
</code>```

答:
I've improved JITHINRAJ's code - used try-with-resources:</p>

```<code>private static byte[] gzipCompress(byte[] uncompressedData) {
        byte[] result = new byte[]{};
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);
             GZIPOutputStream gzipOS = new GZIPOutputStream(bos)) {
            gzipOS.write(uncompressedData);
            // You need to close it before using bos
            gzipOS.close();
            result = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

private static byte[] gzipUncompress(byte[] compressedData) {
        byte[] result = new byte[]{};
        try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPInputStream gzipIS = new GZIPInputStream(bis)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzipIS.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            result = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: GZIP compression to a byte array

Body:
I am trying to write a class that can compress data. The below code fails (no exception is thrown, but the target .gz file is empty.)

Besides: I don't want to generate the .gz file directly like it is done in all examples. I only want to get the compressed
data, so that I can e.g. encrypt it before writting the data to a file.

If I write directly to a file everything works fine:

import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;

public class Zipper
{
  public static void main(String[] args)
  {
    byte[] dataToCompress = "This is the test data."
      .getBytes(StandardCharsets.ISO_8859_1);

    GZIPOutputStream zipStream = null;
    FileOutputStream fileStream = null;
    try
    {
      fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
      zipStream = new GZIPOutputStream(fileStream);
      zipStream.write(dataToCompress);

      fileStream.write(compressedData);
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      try{ zipStream.close(); }
        catch(Exception e){ }
      try{ fileStream.close(); }
        catch(Exception e){ }
    }
  }
}

But, if I want to 'bypass' it to the byte array stream it does not produce a single byte - compressedData is always empty.

import java.io.*;
import java.util.zip.*;
import java.nio.charset.*;

public class Zipper
{
  public static void main(String[] args)
  {
    byte[] dataToCompress = "This is the test data."
      .getBytes(StandardCharsets.ISO_8859_1);
    byte[] compressedData = null;

    GZIPOutputStream zipStream = null;
    ByteArrayOutputStream byteStream = null;
    FileOutputStream fileStream = null;
    try
    {
      byteStream = new ByteArrayOutputStream(dataToCompress.length);
      zipStream = new GZIPOutputStream(byteStream);
      zipStream.write(dataToCompress);

      compressedData = byteStream.toByteArray();

      fileStream = new FileOutputStream("C:/Users/UserName/Desktop/zip_file.gz");
      fileStream.write(compressedData);
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      try{ zipStream.close(); }
        catch(Exception e){ }
      try{ byteStream.close(); }
        catch(Exception e){ }
      try{ fileStream.close(); }
        catch(Exception e){ }
    }
  }
}

Body:
I've improved JITHINRAJ's code - used try-with-resources:

private static byte[] gzipCompress(byte[] uncompressedData) {
        byte[] result = new byte[]{};
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressedData.length);
             GZIPOutputStream gzipOS = new GZIPOutputStream(bos)) {
            gzipOS.write(uncompressedData);
            // You need to close it before using bos
            gzipOS.close();
            result = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

private static byte[] gzipUncompress(byte[] compressedData) {
        byte[] result = new byte[]{};
        try (ByteArrayInputStream bis = new ByteArrayInputStream(compressedData);
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPInputStream gzipIS = new GZIPInputStream(bis)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzipIS.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            result = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

ContentLicense: CC BY-SA 4.0


问:
How to complete a request in another actor when using akka-http
I am using akka-http 1.0 and I would like to use a route defined as

```<code>def route: Route = path("") {
  // start actor with requestContext
  // call requestContext.complete(...) in actor with the result
}
</code>```

How do I accomplish this?

答:
you may try even better like:</p>

```<code>package controllers

import akka.actor.{Actor, ActorSystem, Props}
import akka.stream.ActorMaterializer

import scala.concurrent.{Await, Future}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import akka.pattern.ask
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn
import akka.actor._

import akka.util.Timeout

case object Message

class TestActor(name:String) extends Actor {
  def receive = {
    case Message =>
      sender ! "Testing Ask pattern Approach"
      println(s"hello from $name")

    case _ =>

      println("that was unexpected")
  }
}

object AskTest extends App {

  implicit val system= ActorSystem("myactor")
  implicit val material=ActorMaterializer()

//  implicit val props=Props.empty
implicit val timeout = Timeout(5 seconds)
  implicit val result =system.actorOf(Props(new TestActor("TestingName")),name = "Scala")

   val future3:Future[String]= ask(result ,Message).mapTo[String]
  val results = Await.result(future3, 2 seconds)
  println(results)
}
</code>```

Body:
I am using akka-http 1.0 and I would like to use a route defined as

def route: Route = path("") {
  // start actor with requestContext
  // call requestContext.complete(...) in actor with the result
}

How do I accomplish this?

Body:
you may try even better like:

package controllers

import akka.actor.{Actor, ActorSystem, Props}
import akka.stream.ActorMaterializer

import scala.concurrent.{Await, Future}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import akka.pattern.ask
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.io.StdIn
import akka.actor._

import akka.util.Timeout

case object Message

class TestActor(name:String) extends Actor {
  def receive = {
    case Message =>
      sender ! "Testing Ask pattern Approach"
      println(s"hello from $name")

    case _ =>

      println("that was unexpected")
  }
}

object AskTest extends App {

  implicit val system= ActorSystem("myactor")
  implicit val material=ActorMaterializer()

//  implicit val props=Props.empty
implicit val timeout = Timeout(5 seconds)
  implicit val result =system.actorOf(Props(new TestActor("TestingName")),name = "Scala")

   val future3:Future[String]= ask(result ,Message).mapTo[String]
  val results = Await.result(future3, 2 seconds)
  println(results)
}


问:
Unable to view value in textbox after binding in angularjs
Hi I am developing Angularjs application. I am trying to bind value to textbox as below.

```<code><ul>
    <li ng-repeat="screen in screenMap">
        <input type="text" ng-model="screenname" value="{{screen.scrn_name}}" />
    </li>
</ul>
</code>```

After binding value to textbox, Textbox does not show any value. But when i see in browser i can see below value is binded

```<code> <input type="text" ng-model="screenname" value="USerProfile" class="ng-pristine ng-untouched ng-valid">
</code>```

May i know why i am not able to see value in textbox? Any help would be appreciated. Thank you.

答:
USE ng-value,

<input type="text" ng-model="screenname" ng-value="screen.scrn_name" />

DEMO

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
   $scope.screenMap = [{
  "id": 1,
  "scrn_name": "Redhold"
}, {
  "id": 2,
  "scrn_name": "Solarbreeze"
}];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

  <div ng-app="myApp" ng-controller="myCtrl">
   <ul>
  <li ng-repeat="screen in screenMap">
  <input type="text" ng-model="screenname" ng-value="screen.scrn_name" />
  </li>
  </ul>

  </div>

</body>

</html></code>```

Body:
Hi I am developing Angularjs application. I am trying to bind value to textbox as below.

        <input type="text" ng-model="screenname" value="{{screen.scrn_name}}" />

After binding value to textbox, Textbox does not show any value. But when i see in browser i can see below value is binded

 <input type="text" ng-model="screenname" value="USerProfile" class="ng-pristine ng-untouched ng-valid">

May i know why i am not able to see value in textbox? Any help would be appreciated. Thank you.

Body:
USE ng-value,

<input type="text" ng-model="screenname" ng-value="screen.scrn_name" />

DEMO

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
   $scope.screenMap = [{
  "id": 1,
  "scrn_name": "Redhold"
}, {
  "id": 2,
  "scrn_name": "Solarbreeze"
}];
});

<!DOCTYPE html>
<html>

<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

  <div ng-app="myApp" ng-controller="myCtrl">
   <ul>
  <li ng-repeat="screen in screenMap">
  <input type="text" ng-model="screenname" ng-value="screen.scrn_name" />
  </li>
  </ul>

  </div>

</body>

</html>


问:
Difference in function performance between calling manually ('=') or through macros
I wrote a lookup function. Its performance differs dramatically depending whether or not I call it by hand on worksheet itself (through '=') or through macros.

My macro does the following:

```<code>Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
    For Each cell In aCol
        If LCase(cell.Value) = LCase(searchCell.Value) Then
            betterSearch = bCol.Cells(cell.row, 1)
            Exit For
        End If
        betterSearch = "Not found"
    Next
End Function
</code>```

The macro opens resultsWorkbook and dataWorkbook and then performs a search of the four values in column A from resultWorkbook in dataWorkbook and returns corresponding data from some other column of dataWorkbook.

```<code>'...opening resultWorkbook and dataWorkbook
For aRow = 6 To 9
    resultWorkbook.Worksheets("B3").Cells(aRow, 125).Value = _
            betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
            , dataWorkbook.Worksheets("page 1").Range("A:A") _
            , dataWorkbook.Worksheets("page 1").Range("Z:Z"))

         resultWorkbook.Worksheets("B3").Cells(aRow, 126).Value = _
            betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
            , dataWorkbook.Worksheets("page 1").Range("A:A") _
            , dataWorkbook.Worksheets("page 1").Range("I:I"))
Next aRow
</code>```

It's really slow - takes minutes for 1 file. But when I open that file manually and type in the formula and hit Enter it calculates instantly (so in that regard my function doesn't need optimizing - it already calculates fast but just in the worksheet, not inside the macros).

I'm not looking to optimize the function. I want to understand why this difference in performance happens. I have Application.Calculation = xlCalculationManual both for the main application and invisible application that runs along and does all the work:  ExcelApp.Calculation = xlCalculationManual and it seems to be changing the workbooks' states to manual but the slow performance is there as if the workbooks were still automatic.

答:
Probably has something to do with using entire column ranges.
I think when calling the function from a macro you are forcing Excel to transfer a million values to VBA for each full column reference (transferring data from Excel to VBA is very slow).
When calling the function from the worksheet you are only transferring a range object which you then loop on cell by cell so the amount of data transferred to VBA is probably hundreds of thousands times less (depending how far down the range you have to go to find a match).

Try Setting range variables in your macro for the full column references and then passing the range variables instead of Range(I:I) to BetterSearch

Body:
I wrote a lookup function. Its performance differs dramatically depending whether or not I call it by hand on worksheet itself (through '=') or through macros.

My macro does the following:

Function betterSearch(searchCell As Range, aCol As Range, bCol As Range)
    For Each cell In aCol
        If LCase(cell.Value) = LCase(searchCell.Value) Then
            betterSearch = bCol.Cells(cell.row, 1)
            Exit For
        End If
        betterSearch = "Not found"
    Next
End Function

The macro opens resultsWorkbook and dataWorkbook and then performs a search of the four values in column A from resultWorkbook in dataWorkbook and returns corresponding data from some other column of dataWorkbook.

'...opening resultWorkbook and dataWorkbook
For aRow = 6 To 9
    resultWorkbook.Worksheets("B3").Cells(aRow, 125).Value = _
            betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
            , dataWorkbook.Worksheets("page 1").Range("A:A") _
            , dataWorkbook.Worksheets("page 1").Range("Z:Z"))

         resultWorkbook.Worksheets("B3").Cells(aRow, 126).Value = _
            betterSearch(resultWorkbook.Worksheets("B3").Cells(aRow, 1) _
            , dataWorkbook.Worksheets("page 1").Range("A:A") _
            , dataWorkbook.Worksheets("page 1").Range("I:I"))
Next aRow

It's really slow - takes minutes for 1 file. But when I open that file manually and type in the formula and hit Enter it calculates instantly (so in that regard my function doesn't need optimizing - it already calculates fast but just in the worksheet, not inside the macros).

I'm not looking to optimize the function. I want to understand why this difference in performance happens. I have Application.Calculation = xlCalculationManual both for the main application and invisible application that runs along and does all the work:  ExcelApp.Calculation = xlCalculationManual and it seems to be changing the workbooks' states to manual but the slow performance is there as if the workbooks were still automatic.


问:
tensorflow-gpu via pip time out
I was getting time outs from pypi.python.org when running pip install --upgrade tensorflow_gpu, so I added the --verbose and --timeout 10000 params to it. It starts out fast then begins to crawl:

```<code>1% |▌                               | 747kB 244bytes/s eta 2 days, 9:31:36
</code>```

Is there a better way to install tensorflow-gpu when inside a virtualenv in Windows? Following the instructions from this model: https://github.com/tensorflow/models/tree/master/attention_ocr

答:
The easiest way to install tensorflow within an environment is as follows.

Activate/Enter your python environment (e.g. for Anaconda,
activate envName).

Ensure that you are actually in your virtual/conda environment!

Use pip to install tensorflow. For CPU use pip install tensorflow and for GPU use pip install tensorflow-gpu. Don't have both installed in the same directory.

Pip should take care of the rest. Tensorflow will be downloaded along with it's dependencies from Pypi.

If you're having problems installing from pip you can try updating pip or checking your internet connection. There is also a chance that Pypi are having some minor issues on their end.

Don't forget to activate your environment before trying to import Tensorflow!

Good luck!

Title: tensorflow-gpu via pip time out

Body:
I was getting time outs from pypi.python.org when running pip install --upgrade tensorflow_gpu, so I added the --verbose and --timeout 10000 params to it. It starts out fast then begins to crawl:

1% |▌                               | 747kB 244bytes/s eta 2 days, 9:31:36

Is there a better way to install tensorflow-gpu when inside a virtualenv in Windows? Following the instructions from this model: https://github.com/tensorflow/models/tree/master/attention_ocr


问:
How can I output javascript with "onclick" into a textfield?
I wrote a javascript program to generate random passwords. How can I output the result into a textfield (input tag)?

var randomString = function(length) {
  var text = "";
  var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

var rs = randomString(16);
console.log(rs);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="passgen">
  <button type="button" id="pass-button" onclick="**???**">Generate Password</button>
  <br><br>
  <input type="text" name="output">
</section></code>```

答:
you can do something like this:</p>

```<code>var randomString = function(length) {
        var text = "";
        var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
        for(var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }

    var rs = randomString(16);

    console.log(rs);

    document.getElementsByName('output')[0].value = rs;
</code>```

Body:
I wrote a javascript program to generate random passwords. How can I output the result into a textfield (input tag)?

var randomString = function(length) {
  var text = "";
  var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

var rs = randomString(16);
console.log(rs);

  <button type="button" id="pass-button" onclick="**???**">Generate Password</button>

  <input type="text" name="output">

Body:
you can do something like this:

var randomString = function(length) {
        var text = "";
        var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
        for(var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }

    var rs = randomString(16);

    console.log(rs);

    document.getElementsByName('output')[0].value = rs;


问:
How to include a View the best way and call it?
I'm developing an Android App. On the Main Activity Screen there is a view, which calls the onDraw Method of the View class. But what is the right way to include the view?

include the view with  Tags in the xml. The View is drawn.

include the view with invalidate() and in the XML-File: onDraw is called two times

include the view with invalidate() and without tags in the XML-File: nothing is drawn

include the view with setContentView(): the view is drawn, but there is no ActionBar anymore

Can you give me a tip how to solve it?
Because we want something, the view is able to:
1. If we go to another Activity by click on the Action Bar Menu and the go back with the Up Button, the old view should be shown again and not draw again. How is that possible.

with an Intent to the MainActivity by click on a button from another Activity, the onDraw Method should be called.

I hope somebody can help me :)

The XML of the Main Activity:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>
</code>```

The Content XML of the Main Activity:

```<code>        <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="MainActivity"
    tools:showIn="@layout/activity_main">

   <view
       android:id="@+id/view"
       class="MyView"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintHorizontal_bias="0.437"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

The Main Actitivity

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //XML-Layout über die Ressourcen Variable holen
        setContentView(R.layout.activity_main);

        //Toolbar als ActionBar hinzufügen
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Logo in Action Bar integrieren
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.drawable.hsd_logo_weiss);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
}
}
</code>```

答:
If there aren't reason to not do so...

Do as you say in point #1. It's the easiest method, once you wrote it in the xml and you verify that the view is regulary drawn, you could refer to it through the R object with

findviewbyid(R.id.<viewID>)

Just pay attention to the parent, make sure your view elements are where they are supposed to be, under the right parent

As for switching between intent, I don't know why it behave like you describe... some time ago i used actionbar like you do, but i didn't have those problems. Try to not use the onDraw() method if you can.

At least, you can remove it from problem's cause :)

Body:
I'm developing an Android App. On the Main Activity Screen there is a view, which calls the onDraw Method of the View class. But what is the right way to include the view?

include the view with  Tags in the xml. The View is drawn.

include the view with invalidate() and in the XML-File: onDraw is called two times

include the view with invalidate() and without tags in the XML-File: nothing is drawn

include the view with setContentView(): the view is drawn, but there is no ActionBar anymore

Can you give me a tip how to solve it?
Because we want something, the view is able to:
1. If we go to another Activity by click on the Action Bar Menu and the go back with the Up Button, the old view should be shown again and not draw again. How is that possible.

with an Intent to the MainActivity by click on a button from another Activity, the onDraw Method should be called.

I hope somebody can help me :)

The XML of the Main Activity:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

</android.support.design.widget.CoordinatorLayout>

The Content XML of the Main Activity:

        <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="MainActivity"
    tools:showIn="@layout/activity_main">

   <view
       android:id="@+id/view"
       class="MyView"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintHorizontal_bias="0.437"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

The Main Actitivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //XML-Layout über die Ressourcen Variable holen
        setContentView(R.layout.activity_main);

        //Toolbar als ActionBar hinzufügen
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Logo in Action Bar integrieren
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setLogo(R.drawable.hsd_logo_weiss);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
}
}


问:
EXTJS OnClick Tab Event
Is there a way to attach an OnClick event to a tab switch in EXTJS?

I make the grid like this:

```<code>var simple = new Ext.FormPanel({
    labelWidth: '100%',
    border:false,
    width: '100%',
            style:
            {
                height: '291px'
            },
    items: {
        xtype: 'tabpanel',
        activeTab: 0,
        //labelWidth: 75, // label settings here cascade unless overridden
        items:[{
        url:'save-form.php',
        title: 'Tab 1',
  ...
</code>```

Thanks!

答:
I added in a listener after the tabs were defined like this:

```<code>//define all tabs, and after the ] from the tab panel JSON:
listeners: {
    'tabchange': function(tabPanel, tab) {
        alert("tab changed");
    }
}
</code>```

This just alerts when the tab changed, which is sufficient for my purposes. I'm not sure though how to find out which tab is the current tab.

Hope this helps someone in the future.

Title: EXTJS OnClick Tab Event

Body:
Is there a way to attach an OnClick event to a tab switch in EXTJS?

I make the grid like this:

var simple = new Ext.FormPanel({
    labelWidth: '100%',
    border:false,
    width: '100%',
            style:
            {
                height: '291px'
            },
    items: {
        xtype: 'tabpanel',
        activeTab: 0,
        //labelWidth: 75, // label settings here cascade unless overridden
        items:[{
        url:'save-form.php',
        title: 'Tab 1',
  ...

Thanks!

Body:
I added in a listener after the tabs were defined like this:

//define all tabs, and after the ] from the tab panel JSON:
listeners: {
    'tabchange': function(tabPanel, tab) {
        alert("tab changed");
    }
}

This just alerts when the tab changed, which is sufficient for my purposes. I'm not sure though how to find out which tab is the current tab.

Hope this helps someone in the future.


问:
Xcode Interface Builder Pin Tool makes UITableView disappear
I have a UITableView and I want it to hit the upper bar, the sides of the view and the Seek Bar below. When I add constraints with the Pin Tool, the UITableView simply disappears and I get no log output.

I use the Pin Tool like shown here:

After this, the table disappears. Why? Here is another picture of my setup, it's literally just up/down/left/right constraints, nothing else, what am I doing wrong?

答: Solved it by giving the top bar some constraints and giving the UITableView a "width" constraint - I have no idea why that works but now it scales nicely for every display size


问:
Pull large amounts of data from a remote server, into a DataFrame
To give as much context as I can / is needed, I'm trying to pull some data stored on a remote postgres server (heroku) into a pandas DataFrame, using psycopg2 to connect.

I'm interested in two specific tables, users and events, and the connection works fine, because when pulling down the user data

```<code>import pandas.io.sql as sql
# [...]
users = sql.read_sql("SELECT * FROM users", conn)
</code>```

after waiting a few seconds, the DataFrame is returned as expected.

```<code><class 'pandas.core.frame.DataFrame'>
Int64Index: 67458 entries, 0 to 67457
Data columns (total 35 columns): [...]
</code>```

Yet when trying to pull the bigger, heavier events data straight from ipython, after a long time, it just crashes:

```<code>In [11]: events = sql.read_sql("SELECT * FROM events", conn)
vagrant@data-science-toolbox:~$
</code>```

and when trying from an iPython notebook I get the Dead kernel error

The kernel has died, would you like to restart it? If you do not restart the kernel, you will be able to save the notebook, but running code will not work until the notebook is reopened.

Update #1:

To get a better idea of the size of the events table I'm trying to pull in, here are the number of records and the number of attributes for each:

```<code>In [11]: sql.read_sql("SELECT count(*) FROM events", conn)
Out[11]:
     count
0  2711453

In [12]: len(sql.read_sql("SELECT * FROM events LIMIT 1", conn).columns)
Out[12]: 18
</code>```

Update #2:

Memory is definitely a bottleneck for the current implementation of read_sql: when pulling down the events and trying to run another instance of iPython the result is

```<code>vagrant@data-science-toolbox:~$ sudo ipython
-bash: fork: Cannot allocate memory
</code>```

Update #3:

I first tried with a read_sql_chunked implementation that would just return the array of partial DataFrames:

```<code>def read_sql_chunked(query, conn, nrows, chunksize=1000):
    start = 0
    dfs = []
    while start < nrows:
        df = pd.read_sql("%s LIMIT %s OFFSET %s" % (query, chunksize, start), conn)
        start += chunksize
        dfs.append(df)
        print "Events added: %s to %s of %s" % (start-chunksize, start, nrows)
    # print "concatenating dfs"
    return dfs

event_dfs = read_sql_chunked("SELECT * FROM events", conn, events_count, 100000)
</code>```

and that works well, but when trying to concatenate the DataFrames, the kernel dies again.

And this is after giving the VM 2GB of RAM.

Based on Andy's explanation of read_sql vs. read_csv difference in implementation and performance, the next thing I tried was to append the records into a CSV and then read them all into a DataFrame:

```<code>event_dfs[0].to_csv(path+'new_events.csv', encoding='utf-8')

for df in event_dfs[1:]:
    df.to_csv(path+'new_events.csv', mode='a', header=False, encoding='utf-8')
</code>```

Again, the writing to CSV completes successfully – a 657MB file – but reading from the CSV never completes.

How can one approximate how much RAM would be sufficient to read say a 657MB CSV file, since 2GB seem not to be enough?

Feels like I'm missing some fundamental understanding of either DataFrames or psycopg2, but I'm stuck, I can't even pinpoint the bottleneck or where to optimize.

What's the proper strategy to pull larger amounts of data from a remote (postgres) server?

答:
try to use pandas:

```<code>mysql_cn = mysql.connector.connect(host='localhost', port=123, user='xyz',  passwd='****', db='xy_db')**

data= pd.read_sql('SELECT * FROM table;', con=mysql_cn)

mysql_cn.close()
</code>```

It worked for me.

Body:
To give as much context as I can / is needed, I'm trying to pull some data stored on a remote postgres server (heroku) into a pandas DataFrame, using psycopg2 to connect.

I'm interested in two specific tables, users and events, and the connection works fine, because when pulling down the user data

import pandas.io.sql as sql
# [...]
users = sql.read_sql("SELECT * FROM users", conn)

after waiting a few seconds, the DataFrame is returned as expected.

<class 'pandas.core.frame.DataFrame'>
Int64Index: 67458 entries, 0 to 67457
Data columns (total 35 columns): [...]

Yet when trying to pull the bigger, heavier events data straight from ipython, after a long time, it just crashes:

In [11]: events = sql.read_sql("SELECT * FROM events", conn)
vagrant@data-science-toolbox:~$

and when trying from an iPython notebook I get the Dead kernel error

The kernel has died, would you like to restart it? If you do not restart the kernel, you will be able to save the notebook, but running code will not work until the notebook is reopened.

Update #1:

To get a better idea of the size of the events table I'm trying to pull in, here are the number of records and the number of attributes for each:

In [11]: sql.read_sql("SELECT count(*) FROM events", conn)
Out[11]:
     count
0  2711453

In [12]: len(sql.read_sql("SELECT * FROM events LIMIT 1", conn).columns)
Out[12]: 18

Update #2:

Memory is definitely a bottleneck for the current implementation of read_sql: when pulling down the events and trying to run another instance of iPython the result is

vagrant@data-science-toolbox:~$ sudo ipython
-bash: fork: Cannot allocate memory

Update #3:

I first tried with a read_sql_chunked implementation that would just return the array of partial DataFrames:

def read_sql_chunked(query, conn, nrows, chunksize=1000):
    start = 0
    dfs = []
    while start < nrows:
        df = pd.read_sql("%s LIMIT %s OFFSET %s" % (query, chunksize, start), conn)
        start += chunksize
        dfs.append(df)
        print "Events added: %s to %s of %s" % (start-chunksize, start, nrows)
    # print "concatenating dfs"
    return dfs

event_dfs = read_sql_chunked("SELECT * FROM events", conn, events_count, 100000)

and that works well, but when trying to concatenate the DataFrames, the kernel dies again.

And this is after giving the VM 2GB of RAM.

Based on Andy's explanation of read_sql vs. read_csv difference in implementation and performance, the next thing I tried was to append the records into a CSV and then read them all into a DataFrame:

event_dfs[0].to_csv(path+'new_events.csv', encoding='utf-8')

for df in event_dfs[1:]:
    df.to_csv(path+'new_events.csv', mode='a', header=False, encoding='utf-8')

Again, the writing to CSV completes successfully – a 657MB file – but reading from the CSV never completes.

How can one approximate how much RAM would be sufficient to read say a 657MB CSV file, since 2GB seem not to be enough?

Feels like I'm missing some fundamental understanding of either DataFrames or psycopg2, but I'm stuck, I can't even pinpoint the bottleneck or where to optimize.

What's the proper strategy to pull larger amounts of data from a remote (postgres) server?

Body:
try to use pandas:

mysql_cn = mysql.connector.connect(host='localhost', port=123, user='xyz',  passwd='****', db='xy_db')**

data= pd.read_sql('SELECT * FROM table;', con=mysql_cn)

mysql_cn.close()

It worked for me.


问:
How to make a horizontal merge in SSRS Dynamically
I am creating a report that generates a timeline calendar. I managed to make it work but now I'm stuck with the new problem. I don't know how to merge the cell column with the same year value dynamically. I have no idea how to do this. I am no expert when creating reports. But I think it's very simple to others. Please help.

答:
You don't merge the cells in order to do that.

You have to create a (parent of month) column group (in tablix or matrix) and set the Year as the group value.


问:
There is any possibility to hide a error message when the other error message is displayed?
```<code> <form name="form">
     <input type="password" placeholder="Password" ng-model="password" name="password" minlength="6"  maxlength="15" ng-pattern="/^\S*$/" required>
     <span ng-show="form.password.$dirty && form.password.$invalid">
       <span ng-show="form.password.$error.required">Password is required.</span>
       <span ng-show="form.password.$error.minlength">Password should have atleast 6 characters.</span>
       <span ng-show="form.password.$error.pattern">White Space not allowed.</span>
     </span>
 </form>
</code>```

In this code if i type less then 6 characters with space it's showing both "Password should have atleast 6 characters." & "White Space not allowed."

I don't want to show both error message's, only one error message should display.

答:
You'll need to decide which one to show if both conditions are met.

```<code><span ng-show="form.password.$error.minlength">Password should have atleast 6 characters.</span>
<span ng-show="form.password.$error.pattern && !form.password.$error.minlength">White Space not allowed.</span>
</code>```

And if you have a third one

```<code><span ng-show="form.password.$error.patternQ
    && !form.password.$error.pattern
    && !form.password.$error.minlength">Question mark not allowed.</span>
</code>```

Body:
 <form name="form">
     <input type="password" placeholder="Password" ng-model="password" name="password" minlength="6"  maxlength="15" ng-pattern="/^\S*$/" required>

       Password is required.
       Password should have atleast 6 characters.
       White Space not allowed.

 </form>

In this code if i type less then 6 characters with space it's showing both "Password should have atleast 6 characters." & "White Space not allowed."

I don't want to show both error message's, only one error message should display.

Body:
You'll need to decide which one to show if both conditions are met.

<span ng-show="form.password.$error.minlength">Password should have atleast 6 characters.</span>
<span ng-show="form.password.$error.pattern && !form.password.$error.minlength">White Space not allowed.</span>

And if you have a third one

<span ng-show="form.password.$error.patternQ
    && !form.password.$error.pattern
    && !form.password.$error.minlength">Question mark not allowed.</span>


问:
Format all elements of a list
I want to print a list of numbers, but I want to format each member of the list before it is printed.
For example,

```<code>theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]
</code>```

I want the following output printed given the above list as an input:

```<code>[1.34, 7.42, 6.97, 4.55]
</code>```

For any one member of the list, I know I can format it by using

```<code>print "%.2f" % member
</code>```

Is there a command/function that can do this for the whole list? I can write one, but was wondering if one already exists.

Title: Format all elements of a list

Body:
I want to print a list of numbers, but I want to format each member of the list before it is printed.
For example,

theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]

I want the following output printed given the above list as an input:

[1.34, 7.42, 6.97, 4.55]

For any one member of the list, I know I can format it by using

print "%.2f" % member

Is there a command/function that can do this for the whole list? I can write one, but was wondering if one already exists.

Body:
A very short solution using "".format() and a generator expression:

>>> theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]

>>> print(['{:.2f}'.format(item) for item in theList])

['1.34', '7.42', '6.97', '4.55']


问:
how to get access token for fb page for 2 months or more
Hi I had an access token for an facebook page.
I can get the access token for fb account but fb page it is getting only for one hour
i had 7 fb pages in my account. So is there any process to get access token for 2 months or more </p>

答:
Go to https://developers.facebook.com/tools/explorer

Select your app from the dropdown on the top right hand side

Click "Get Access Token" button just below the application dropdown on the right hand side

In the dropdown select the page you want to get a access token for. If you don't see your pages listed then you'll need to make sure you're set with the admin role for the page. Also you may have to click "Get Page Access Token" in the dropdown, after which then your pages will show in the dropdown next time you click the "Get Access Token" button.

Click the blue exclamation point icon in the "Access token" input field

Click the "Open in Access Token Tool" button on the bottom right of the popup

Click the "Extend Access Token" button to get an token that never expires

"referance link:  https://www.rocketmarketinginc.com/blog/get-never-expiring-facebook-page-access-token/"


问:
How scheme of Replication works in hadoop3.x?
As per my understanding in Hadoop-3.x they introduced the support for Microsoft Azure Data Lake filesystem and the scheme of Replication is changed. Are these only the major features, are any other new features they are introducing as part of hadoop-3.x.?

And how scheme of Replication works in Hadoop-3.x

答:
Hadoop 3.0 will incorporate Erasure Coding in place of replication consuming comparatively less storage space whilst providing same level of fault tolerance.

Hadoop 3x replication scheme leading to 200% additional storage space and resource overhead.

For more details, refer “HDFS Erasure Coding”.

To understand the how HDFS Erasure Coding works,
Refer: “Introduction to HDFS Erasure Coding in Apache Hadoop”.


问:
How to programmatically create and shift list
At the moment I have this in my code

```<code>up = [1, 0, 0, 0]
down = [0, 1, 0, 0]
left = [0, 0, 1, 0]
right = [0, 0, 0, 1]
</code>```

I want to add another variable I need to know do

```<code>up = [1, 0, 0, 0, 0]
down = [0, 1, 0, 0, 0]
left = [0, 0, 1, 0, 0]
right = [0, 0, 0, 1, 0]
a = [0, 0, 0, 0, 1]
</code>```

And I'm not sure how many variables I need or I might end up needing a lot.

Is it possible to create a list of the variables I need, and then have a loop going through each one and doing this?

I'm not really sure how to go about figuring this out.

答:
Adding a value to a list in python is done with append() or extend(). Appending a list of items to a list will place the new list at the end of the existing list while extending a list will place each new item of the extension list to the bottom of the existing list.

For example if you're not sure how many more items you will end up needing in your lists, you can create a function that extends them with any number of elements:

```<code>>>> up = [1, 0, 0, 0]
>>> down = [0, 1, 0, 0]
>>> left = [0, 0, 1, 0]
>>> right = [0, 0, 0, 1]
>>> def extend_list(list, items):
...     return list.extend(items)
...
>>> extend_list(up, [0])
>>> print(up)
[1, 0, 0, 0, 0]
>>> extend_list(down, [0,1])
>>> print(down)
[0, 1, 0, 0, 0, 1]
</code>```

Body:
At the moment I have this in my code

up = [1, 0, 0, 0]
down = [0, 1, 0, 0]
left = [0, 0, 1, 0]
right = [0, 0, 0, 1]

I want to add another variable I need to know do

up = [1, 0, 0, 0, 0]
down = [0, 1, 0, 0, 0]
left = [0, 0, 1, 0, 0]
right = [0, 0, 0, 1, 0]
a = [0, 0, 0, 0, 1]

And I'm not sure how many variables I need or I might end up needing a lot.

Is it possible to create a list of the variables I need, and then have a loop going through each one and doing this?

I'm not really sure how to go about figuring this out.

Body:
Adding a value to a list in python is done with append() or extend(). Appending a list of items to a list will place the new list at the end of the existing list while extending a list will place each new item of the extension list to the bottom of the existing list.

For example if you're not sure how many more items you will end up needing in your lists, you can create a function that extends them with any number of elements:

>>> up = [1, 0, 0, 0]
>>> down = [0, 1, 0, 0]
>>> left = [0, 0, 1, 0]
>>> right = [0, 0, 0, 1]
>>> def extend_list(list, items):
...     return list.extend(items)
...
>>> extend_list(up, [0])
>>> print(up)
[1, 0, 0, 0, 0]
>>> extend_list(down, [0,1])
>>> print(down)
[0, 1, 0, 0, 0, 1]


问:
Compare hashMap values by setting tolerable margine with Javascript
I did a function that display difference between two hashmaps

For example : this is my 2 hashmaps

1st =>

```<code>1234 : "1.03 , 2.17 , 3"
1235 : "1 , 4 , 5"
1236 : "2 , 3 , 3"
1237 : "0.33 , 1.51 , 5"
</code>```

2nd =>

```<code>1234 : "1.03 , 2.17 , 3"
1235 : "1.17 , 2 , 3.9"
1236 : "2 , 3 , 3"
1237 : "2 , 1 , 5"
</code>```

Result =>

```<code>1235 : "1 , 4 , 5"
1237 : "0.33 , 1.51 , 5"
</code>```

(the goal was to compare the first with the second and display what keys and values of the first hashmap that aren't coherent).

But now, I want to set a tolerable margin of "0.1" to each "hpos , vpos , dpos" of the object's value. So even if the values of the hashmaps are different by only "0.1" it won't display in the object Difference . What should I modify in my function? Btw: the value's structure of the hashmap is this :

```<code>positionList = iSceneGraph.merch.vpos+","+iSceneGraph.merch.hpos+","+iSceneGraph.merch.dpos.;
facingPositions[iSceneGraph.merch.ean] = positionList;
</code>```

And here is my function of comparison :

```<code>compareHashMap: function(iAdaptation, iActual){
                var difference = {};
                Object.keys(iActual).forEach(function(k){
                    if(iAdaptation[k] !== iActual[k]){
                        difference[k] = iActual[k];
                    }
                });
                return difference;
            }
</code>```

答:
As per your comment let's suppose inside your function you have 2 arrays instead of strings, one for actual numbers one for adaptation. Then in your for each function you can add:

```<code>compareHashMap: function(iAdaptation, iActual){
  var difference = {};
  Object.keys(iActual).forEach(function(k){

    for(key in iActual[k]){
      if(Math.abs(iActual[k][key] - iAdaptation[k][key]) > 0.1){ //Math.abs will return absolute value of the number (positive value in case difference is minus)
        difference[k] = iActual[k];
      }
    }
  });
  return difference;
}
</code>```

This is just an example, yI didn't try to run this code.

Body:
I did a function that display difference between two hashmaps

For example : this is my 2 hashmaps

1st =>

1234 : "1.03 , 2.17 , 3"
1235 : "1 , 4 , 5"
1236 : "2 , 3 , 3"
1237 : "0.33 , 1.51 , 5"

2nd =>

1234 : "1.03 , 2.17 , 3"
1235 : "1.17 , 2 , 3.9"
1236 : "2 , 3 , 3"
1237 : "2 , 1 , 5"

Result =>

1235 : "1 , 4 , 5"
1237 : "0.33 , 1.51 , 5"

(the goal was to compare the first with the second and display what keys and values of the first hashmap that aren't coherent).

But now, I want to set a tolerable margin of "0.1" to each "hpos , vpos , dpos" of the object's value. So even if the values of the hashmaps are different by only "0.1" it won't display in the object Difference . What should I modify in my function? Btw: the value's structure of the hashmap is this :

positionList = iSceneGraph.merch.vpos+","+iSceneGraph.merch.hpos+","+iSceneGraph.merch.dpos.;
facingPositions[iSceneGraph.merch.ean] = positionList;

And here is my function of comparison :

compareHashMap: function(iAdaptation, iActual){
                var difference = {};
                Object.keys(iActual).forEach(function(k){
                    if(iAdaptation[k] !== iActual[k]){
                        difference[k] = iActual[k];
                    }
                });
                return difference;
            }

Body:
As per your comment let's suppose inside your function you have 2 arrays instead of strings, one for actual numbers one for adaptation. Then in your for each function you can add:

compareHashMap: function(iAdaptation, iActual){
  var difference = {};
  Object.keys(iActual).forEach(function(k){

    for(key in iActual[k]){
      if(Math.abs(iActual[k][key] - iAdaptation[k][key]) > 0.1){ //Math.abs will return absolute value of the number (positive value in case difference is minus)
        difference[k] = iActual[k];
      }
    }
  });
  return difference;
}

This is just an example, yI didn't try to run this code.


问:
Wordpress not loading Woocommerce attributes section in product
While I tried to add a new product to My Wordpress Woocommerce site. The Product data -> attributes section shows a loading icon and not allowing to add new Attributes to the page.

Because of this issue I updated the Wordpress and Woocommerce to new version. Also I tried to deactivate some plugin. Nothing works. I installed the following plugins in My Wordpress site.

Booster for WooCommerce

Contact Form 7

Envato WordPress Toolkit

Google Analytics Counter Tracker

Header and Footer Scripts

Jetpack by WordPress.com

Nancy Shortcodes

WPBakery Visual Composer

My Google chrome console showing the following error.

答:
Problem:

The problem happening because of the Visual Composer Plugin.

Solution for The Problem:
The problem can be solved by UN-installing the Visual Composer Plugin and install the latest version of the plugin.

The direct plugin update will not work sometimes, So try to install by removing the folder of the plugin from the WordPress and upload the latest version manually and do the update.

Try to update the plugin with the Ultimate Visual Composer Version 3.16.12. This will solve your problem.


问:
Opening a specific Excel instance in VBA
Hope somebody knows how to do this, i'm none too good with VBA.

I have Excel 2016 (64bit) and Excel 2010 (32bit) installed on my machine. This is because i have some older excel based tools that only function in 2010.
One of these tools contains the following code:

```<code>Start:

            ThisWorkbook.Activate
            strOutputsFilePath = gStrOutputsPath
            strDMfilename = [DMFilePath]

   '2. Refresh the PowerPivot model with the new data

            'Create a new instance of excel
            Application.StatusBar = "Opening a new instance of MS Excel"

            Set appExcelApp = New Excel.Application

            'Disconnect and Re-connect to the PowerPivot Add-in (in case it has been disconnected)

            For Each comAddin In appExcelApp.COMAddIns

                If comAddin.Description = "PowerPivot for Excel" Then
                        Set comAddinPPVT = comAddin
                End If

            Next

            If Not comAddinPPVT Is Nothing Then

                comAddinPPVT.Connect = False
                comAddinPPVT.Connect = True

            End If

            'Apply the settings for the Excel application

            With appExcelApp
                    .Visible = False
                    .ScreenUpdating = False
                    .DisplayAlerts = False
                    .EnableEvents = False
            End With
</code>```

What the app is supposed to do is run a new instance of Excel 2010 and open certain files in it.
However, after installing 2016, the New Excel.Application command defaults to opening Excel 2016 instead of 2010. This produces an error with the PowerPivot addin because of incompatibility between data models.

Question is: Is there a way to specify in the VBA code that i want an instance of Excel 2010?

Tried to make Excel 2010 default on my system however the code still opens 2016 and errors out :\

Any help is greatly appreciated!

Thanks

答:
How about using the Shell function?

```<code>Private Sub OpenExcelInstance(version as string)
Dim path As String
Dim appInstance As Variant
Select Case version
    Case "Excel 2010"
         path = "C:\Program Files (x86)\blablabla\Excel.exe" 'path to 32bit 2010 executable
    Case "Excel 2016"
         path = "C:\Program Files\blablabla\Excel.exe" 'path to 64 bit 2016 executable.
    Case default
         Exit sub
End Select

appInstance = Shell(path, 1)

'GetObject function here.
End Sub
</code>```

However, you can't code against this appInstance - It's an integer returned by the shell command.

It's possible to grab the Application instance from it using GetObject afterwards, however I didn't delve into this, since I ran into the problem documented here and that has a SO-question here (not truely unanswered).

Body:
Hope somebody knows how to do this, i'm none too good with VBA.

I have Excel 2016 (64bit) and Excel 2010 (32bit) installed on my machine. This is because i have some older excel based tools that only function in 2010.
One of these tools contains the following code:

Start:

            ThisWorkbook.Activate
            strOutputsFilePath = gStrOutputsPath
            strDMfilename = [DMFilePath]

   '2. Refresh the PowerPivot model with the new data

            'Create a new instance of excel
            Application.StatusBar = "Opening a new instance of MS Excel"

            Set appExcelApp = New Excel.Application

            'Disconnect and Re-connect to the PowerPivot Add-in (in case it has been disconnected)

            For Each comAddin In appExcelApp.COMAddIns

                If comAddin.Description = "PowerPivot for Excel" Then
                        Set comAddinPPVT = comAddin
                End If

            Next

            If Not comAddinPPVT Is Nothing Then

                comAddinPPVT.Connect = False
                comAddinPPVT.Connect = True

            End If

            'Apply the settings for the Excel application

            With appExcelApp
                    .Visible = False
                    .ScreenUpdating = False
                    .DisplayAlerts = False
                    .EnableEvents = False
            End With

What the app is supposed to do is run a new instance of Excel 2010 and open certain files in it.
However, after installing 2016, the New Excel.Application command defaults to opening Excel 2016 instead of 2010. This produces an error with the PowerPivot addin because of incompatibility between data models.

Question is: Is there a way to specify in the VBA code that i want an instance of Excel 2010?

Tried to make Excel 2010 default on my system however the code still opens 2016 and errors out :\

Any help is greatly appreciated!

Thanks

Body:
How about using the Shell function?

Private Sub OpenExcelInstance(version as string)
Dim path As String
Dim appInstance As Variant
Select Case version
    Case "Excel 2010"
         path = "C:\Program Files (x86)\blablabla\Excel.exe" 'path to 32bit 2010 executable
    Case "Excel 2016"
         path = "C:\Program Files\blablabla\Excel.exe" 'path to 64 bit 2016 executable.
    Case default
         Exit sub
End Select

appInstance = Shell(path, 1)

'GetObject function here.
End Sub

However, you can't code against this appInstance - It's an integer returned by the shell command.

It's possible to grab the Application instance from it using GetObject afterwards, however I didn't delve into this, since I ran into the problem documented here and that has a SO-question here (not truely unanswered).


问:
How to initialize HashSet values by construction?
I need to create a Set with initial values.

```<code>Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
</code>```

Is there a way to do this in one line of code? For instance, it's useful for a final static field.

答:
With Java 9 you can do the following:

```<code>Set.of("a", "b");
</code>```

and you'll get an immutable Set containing the elements. For details see the Oracle documentation of interface Set.

Body:
I need to create a Set with initial values.

Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");

Is there a way to do this in one line of code? For instance, it's useful for a final static field.

Body:
With Java 9 you can do the following:

Set.of("a", "b");

and you'll get an immutable Set containing the elements. For details see the Oracle documentation of interface Set.


问:
Protractor- How can I start the test on multiple browsers and then continue only one of the browsers
I start my automation test on three browsers but after that i want to continue on only one browser. Is it possible?

```<code>// spec.js
multiCapabilities:[{
'browserName': 'MicrosoftEdge',
},
{
'browserName' : 'chrome',
},
{
'browserName' : 'firefox',
}],
describe('Protractor Demo App', function() {
    it('should have a title', function() {
    browser.driver.get('http://preg.fxgm.com/aserving/4/1/blg/1/s/LOC-5675/index.html');
    browser.ignoreSynchronization = true;

    browser.sleep(5000);
    browser.driver.findElement(protractor.By.id('submit_button')).click();
    browser.sleep(2500);
</code>```

I would like to continue only with Chrome browser.

答:
You want to create a config file and split out multiCapabilities into that, out of spec.js which should just contain your specs.

For example, create conf.js and add:

```<code>exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    multiCapabilities: [{
        browserName : 'MicrosoftEdge',
    },{
        browserName : 'chrome',
        specs: 'spec.js',
    },
    {
        browserName : 'firefox',
    }]
};
</code>```

Then specify conf.js when you run protractor:

```<code>> protractor conf
</code>```

Unless you give firefox and edge something to do, (i.e. add specs parameters to the relevant sections), they will complain that no specs were found but they will still run.

Body:
I start my automation test on three browsers but after that i want to continue on only one browser. Is it possible?

// spec.js
multiCapabilities:[{
'browserName': 'MicrosoftEdge',
},
{
'browserName' : 'chrome',
},
{
'browserName' : 'firefox',
}],
describe('Protractor Demo App', function() {
    it('should have a title', function() {
    browser.driver.get('http://preg.fxgm.com/aserving/4/1/blg/1/s/LOC-5675/index.html');
    browser.ignoreSynchronization = true;

    browser.sleep(5000);
    browser.driver.findElement(protractor.By.id('submit_button')).click();
    browser.sleep(2500);

I would like to continue only with Chrome browser.

Body:
You want to create a config file and split out multiCapabilities into that, out of spec.js which should just contain your specs.

For example, create conf.js and add:

exports.config = {
    seleniumAddress: 'http://localhost:4444/wd/hub',
    multiCapabilities: [{
        browserName : 'MicrosoftEdge',
    },{
        browserName : 'chrome',
        specs: 'spec.js',
    },
    {
        browserName : 'firefox',
    }]
};

Then specify conf.js when you run protractor:

> protractor conf

Unless you give firefox and edge something to do, (i.e. add specs parameters to the relevant sections), they will complain that no specs were found but they will still run.


问:
How to calculate means and std at once in pandas?
For example, we have data like :

```<code>>>> df
   name  score  times
0   tom    100      1
1   tom     99      2
2   tom    100      3
3  jack     99      1
4  jack     99      2
5  tony    100      1
6  tony    100      2
7  tony    100      3
</code>```

I want to get a result like

```<code>   name       score std
0  jack   99.000000  0
1   tom   99.666667  0.57
2  tony  100.000000  0
</code>```

Is it possible to get the result at once?
Now I have to calculate them seperately and combine the result

Body:
For example, we have data like :

>>> df
   name  score  times
0   tom    100      1
1   tom     99      2
2   tom    100      3
3  jack     99      1
4  jack     99      2
5  tony    100      1
6  tony    100      2
7  tony    100      3

I want to get a result like

   name       score std
0  jack   99.000000  0
1   tom   99.666667  0.57
2  tony  100.000000  0

Is it possible to get the result at once?
Now I have to calculate them seperately and combine the result

Body:
using agg

In [274]: df.groupby('name').agg({'score': ['mean', 'std']})
Out[274]:
           score
            mean      std
name
jack   99.000000  0.00000
tom    99.666667  0.57735
tony  100.000000  0.00000


问:
Wordpress installation stuck at Choose a Theme
I just recently installed the wordpress app via the Installatron on my godaddy hosted website. It led me to this configuration step with 4 steps. On the final step it requires me to select a theme. Although whenever I am doing so it seems to get hanged/stuck, also there is no continue or next button on the page to move further. Any ideas in this regards would be helpful.

Things I tried:

Refresh the page - Brings me back to the same step in finishing the configuration with similar behavior.

Tried to exit this configuration to create a new post, but brings it back to this same page.

Similar behavior in both Chrome and Firefox.

Javascript console shows the following:

JQMIGRATE: Migrate is installed, version 1.4.1
  jquery-migrate.min.js:2:542

答: you just skip this step and install the new theme using Apperence> theme option</p>


问:
Spring : Unable to resolve view name in Spring MVC
I do have gone through some solutions, none has work in my case.
I have been getting "Not Found" error on browser on running this simple spring mvc example. I am new to Spring framework. Any help would be highly appreciated.

Following is the error I get on Console when I run the program :

WARN  [org.springframework.web.servlet.PageNotFound] (default task-4) No mapping found for HTTP request with URI [/Demo1/] in DispatcherServlet with name 'SpringDispatcher'
  WARN  [org.springframework.web.servlet.PageNotFound] (default task-5) No mapping found for HTTP request with URI [/Demo1/HelloPage] in DispatcherServlet with name 'SpringDispatcher'

Here is web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Demo1</display-name>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>SpringDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.kurshit.springmvc.Demo1</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringDispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>
</code>```

spring-dispatcher-servlet.xml

```<code> <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

 <mvc:default-servlet-handler />
 <mvc:annotation-driven/>
<context:component-scan base-package = "com.kurshit.springmvc.Demo1.controller" />

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

</beans>
</code>```

HomeController.java

```<code>package com.kurshit.springmvc.Demo1.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @RequestMapping(value="/welcome.html")
    public ModelAndView test(HttpServletResponse response) throws IOException{
        // TODO Auto-generated method stub
        ModelAndView mav = new ModelAndView("HelloPage","msg","Welcome To Spring");

        return mav;

    }
}
</code>```

HomePage.jsp

```<code><html>
<body>
    <h1>First Spring Example with Deployment Descriptor</h1>

    <h2>${msg}</h2>

</body>
</html>
</code>```

Here is how my directory structure looks like :

Directory Structure Image Link

I am using Maven tool to resolve dependancies :

Thanks!

答: Your jsp is called HomePage.jsp but you are returning HelloPage in your ModelAndView. These names need to match. (Although you don't need the .jsp extension in the ModelAndView)</p>

Body:
I do have gone through some solutions, none has work in my case.
I have been getting "Not Found" error on browser on running this simple spring mvc example. I am new to Spring framework. Any help would be highly appreciated.

Following is the error I get on Console when I run the program :

WARN  [org.springframework.web.servlet.PageNotFound] (default task-4) No mapping found for HTTP request with URI [/Demo1/] in DispatcherServlet with name 'SpringDispatcher'
  WARN  [org.springframework.web.servlet.PageNotFound] (default task-5) No mapping found for HTTP request with URI [/Demo1/HelloPage] in DispatcherServlet with name 'SpringDispatcher'

Here is web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Demo1</display-name>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>SpringDispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.kurshit.springmvc.Demo1</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringDispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

spring-dispatcher-servlet.xml

 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

 <mvc:default-servlet-handler />
 <mvc:annotation-driven/>
<context:component-scan base-package = "com.kurshit.springmvc.Demo1.controller" />

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

</beans>

HomeController.java

package com.kurshit.springmvc.Demo1.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @RequestMapping(value="/welcome.html")
    public ModelAndView test(HttpServletResponse response) throws IOException{
        // TODO Auto-generated method stub
        ModelAndView mav = new ModelAndView("HelloPage","msg","Welcome To Spring");

        return mav;

    }
}

HomePage.jsp

First Spring Example with Deployment Descriptor

${msg}

Here is how my directory structure looks like :

Directory Structure Image Link

I am using Maven tool to resolve dependancies :

Thanks!


问:
dynamic declaration/query in oracle 9i
In Oracle, given a list of table names, I want to perform 'select column1 into var1 from table' statements on a mass number of tables. And I want to do this for all columns of a table. I cannot declare the type of var1 until the query with user_tab_columns returns the column's type. I tried to declare var1 as sys.anytype but got ORA-00932 with error message such as "inconsistent datatypes: expected CHAR got CHAR".

So how can I get past this error or how can I dynamically declare a variable? Many thanks.

答: Most datatypes will implicitly convert into a VARCHAR.  Obviously there are exceptions, but if your tables are just varchars, dates, and numbers then you should be fine.</p>

Title: dynamic declaration/query in oracle 9i


问:
Multiple spaces in command CMD
Ok so i am trying to flash a hex file onto my arduino pro micro following this sorta guide:

https://www.reddit.com/r/MechanicalKeyboards/comments/69woay/hand_built_keypad_gateron_blues_first_hand_wire/

And I am really struggling with step 2. The problem that i am having is that my thing (Not sure what to call it) looks like this:

```<code>""C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" "-CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM5 -b57600 -D -Uflash:wC:"\Users\My Name\Desktop\Layout\layout.hex:i""
</code>```

I am getting a this error:

```<code>'""C:\Program' is not recognized as an internal or external command,
</code>```

operable program or batch file.

Which i tried fixing with the speech marks following these recommendations:

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

How to use spaces in CMD?

So that's the issue i am probably making one minor mistake or many major ones, but you help would be greatly appreciated.

答:
Let's look at a simpler example. You might try to run C:\Program Files (x86)\myapp\myprogram like this:

```<code>C:\Program Files (x86)\myapp\myprogram --parameter:value
</code>```

It doesn't work because the first thing CMD does is split on spaces. This is called *tokenisation` and the result is a list of tokens:

C:\Program

Files

(x86)\myapp\myprogram

--parameter:value

Then it takes the first token, C:\Program and tries to find a file with that name.

```<code>'C:\Program' is not recognized as an internal or external command
</code>```

The tokenisation routine pays attention to quotes. When it encounters a quote, it strips it, then it doesn't treat spaces as token separators, until it encounters the next quote.

So:

```<code>"C:\Program Files (x86)\myapp\myprogram" --parameter:value
</code>```

Tokenises to:

C:\Program Files (x86)\myapp\myprogram

--parameter:value

For some reason in your example you have put more quotes around the whole thing:

```<code>""C:\Program Files (x86)\myapp\myprogram" --parameter:value"
</code>```

Tokenisation treats the double " as a literal "", so now it tokenises to:

""C:\Program Files

(x86)\myapp\myprogram

--parameter:value

So you get an error because there is no executable file ""C:\Program Files.

Understand how quoting and tokenisation works. Make sense of the commands rather than blindly copying them, and you should be able to solve this.

Title: Multiple spaces in command CMD

Body:
Ok so i am trying to flash a hex file onto my arduino pro micro following this sorta guide:

https://www.reddit.com/r/MechanicalKeyboards/comments/69woay/hand_built_keypad_gateron_blues_first_hand_wire/

And I am really struggling with step 2. The problem that i am having is that my thing (Not sure what to call it) looks like this:

""C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" "-CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM5 -b57600 -D -Uflash:wC:"\Users\My Name\Desktop\Layout\layout.hex:i""

I am getting a this error:

'""C:\Program' is not recognized as an internal or external command,

operable program or batch file.

Which i tried fixing with the speech marks following these recommendations:

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

How to use spaces in CMD?

So that's the issue i am probably making one minor mistake or many major ones, but you help would be greatly appreciated.

Body:
Let's look at a simpler example. You might try to run C:\Program Files (x86)\myapp\myprogram like this:

C:\Program Files (x86)\myapp\myprogram --parameter:value

It doesn't work because the first thing CMD does is split on spaces. This is called *tokenisation` and the result is a list of tokens:

C:\Program

Files

(x86)\myapp\myprogram

--parameter:value

Then it takes the first token, C:\Program and tries to find a file with that name.

'C:\Program' is not recognized as an internal or external command

The tokenisation routine pays attention to quotes. When it encounters a quote, it strips it, then it doesn't treat spaces as token separators, until it encounters the next quote.

So:

"C:\Program Files (x86)\myapp\myprogram" --parameter:value

Tokenises to:

C:\Program Files (x86)\myapp\myprogram

--parameter:value

For some reason in your example you have put more quotes around the whole thing:

""C:\Program Files (x86)\myapp\myprogram" --parameter:value"

Tokenisation treats the double " as a literal "", so now it tokenises to:

""C:\Program Files

(x86)\myapp\myprogram

--parameter:value

So you get an error because there is no executable file ""C:\Program Files.

Understand how quoting and tokenisation works. Make sense of the commands rather than blindly copying them, and you should be able to solve this.


问:
linq 3 table joins not materialising third table into a list
I'm joining three tables in linq, there is a one to one relationship between the first 2 tables then a one to many between the second and third, how can I materialise all the rows from the third table into a list ?, here's what I have so far but its only returning the first match from the 3rd table

```<code>var query = await (from contracts in DbContext.CHPContracts
                               join organisation in DbContext.Organisations on contracts.END_USER_ORG equals organisation.End_User_Org into organisation_joined
                               where request.ContractRefRequests.Contains(contracts.CONTRACT_REF)
                               from oj in organisation_joined.DefaultIfEmpty()

                               select new UserDto
                               {
                                   Email = oj.CHPContacts.FirstOrDefault().Email,
                                   FirstName = oj.CHPContacts.FirstOrDefault().FirstName,
                                   LastName = oj.CHPContacts.FirstOrDefault().LastName,
                                   ID = oj.CHPContacts.FirstOrDefault().ID,
                                   SMS = oj.CHPContacts.FirstOrDefault().Mobile,
                                   Status = oj.CHPContacts.FirstOrDefault().Status,
                                   UserID = "",
                                   UserRole = "",
                                   OrgID = oj.CHPContacts.FirstOrDefault().OrgId,
                                   OrganisationName = oj.OrganisationName,
                                   End_User_Org = oj.End_User_Org
                               }).ToListAsync();
</code>```

obviously its the .FirstOrDefault() bit that's causing that behaviour, but I cant figure out how to get the 3rd table records into a list, anyone help me out ?

答:
I managed to figure it out in the end</p>

```<code>var query = await (from contracts in DbContext.CHPContracts
                               join organisation in DbContext.Organisations on contracts.END_USER_ORG equals organisation.End_User_Org into organisation_joined
                               where request.ContractRefRequests.Contains(contracts.CONTRACT_REF)
                               from oj in organisation_joined.DefaultIfEmpty()
                               from contacts in oj.CHPContacts.DefaultIfEmpty()
                               select new UserDto
                               {
                                   Email = contacts.Email,
                                   FirstName = contacts.FirstName,
                                   LastName = contacts.LastName,
                                   ID = contacts.ID,
                                   SMS = contacts.Mobile,
                                   Status = contacts.Status,
                                   UserID = "",
                                   UserRole = "",
                                   OrgID = contacts.OrgId,
                                   OrganisationName = oj.OrganisationName,
                                   End_User_Org = oj.End_User_Org
                               }).ToListAsync();
</code>```

Body:
I'm joining three tables in linq, there is a one to one relationship between the first 2 tables then a one to many between the second and third, how can I materialise all the rows from the third table into a list ?, here's what I have so far but its only returning the first match from the 3rd table

var query = await (from contracts in DbContext.CHPContracts
                               join organisation in DbContext.Organisations on contracts.END_USER_ORG equals organisation.End_User_Org into organisation_joined
                               where request.ContractRefRequests.Contains(contracts.CONTRACT_REF)
                               from oj in organisation_joined.DefaultIfEmpty()

                               select new UserDto
                               {
                                   Email = oj.CHPContacts.FirstOrDefault().Email,
                                   FirstName = oj.CHPContacts.FirstOrDefault().FirstName,
                                   LastName = oj.CHPContacts.FirstOrDefault().LastName,
                                   ID = oj.CHPContacts.FirstOrDefault().ID,
                                   SMS = oj.CHPContacts.FirstOrDefault().Mobile,
                                   Status = oj.CHPContacts.FirstOrDefault().Status,
                                   UserID = "",
                                   UserRole = "",
                                   OrgID = oj.CHPContacts.FirstOrDefault().OrgId,
                                   OrganisationName = oj.OrganisationName,
                                   End_User_Org = oj.End_User_Org
                               }).ToListAsync();

obviously its the .FirstOrDefault() bit that's causing that behaviour, but I cant figure out how to get the 3rd table records into a list, anyone help me out ?

Body:
I managed to figure it out in the end

var query = await (from contracts in DbContext.CHPContracts
                               join organisation in DbContext.Organisations on contracts.END_USER_ORG equals organisation.End_User_Org into organisation_joined
                               where request.ContractRefRequests.Contains(contracts.CONTRACT_REF)
                               from oj in organisation_joined.DefaultIfEmpty()
                               from contacts in oj.CHPContacts.DefaultIfEmpty()
                               select new UserDto
                               {
                                   Email = contacts.Email,
                                   FirstName = contacts.FirstName,
                                   LastName = contacts.LastName,
                                   ID = contacts.ID,
                                   SMS = contacts.Mobile,
                                   Status = contacts.Status,
                                   UserID = "",
                                   UserRole = "",
                                   OrgID = contacts.OrgId,
                                   OrganisationName = oj.OrganisationName,
                                   End_User_Org = oj.End_User_Org
                               }).ToListAsync();


问:
How can I output javascript with "onclick" into a textfield?
I wrote a javascript program to generate random passwords. How can I output the result into a textfield (input tag)?

var randomString = function(length) {
  var text = "";
  var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

var rs = randomString(16);
console.log(rs);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="passgen">
  <button type="button" id="pass-button" onclick="**???**">Generate Password</button>
  <br><br>
  <input type="text" name="output">
</section></code>```

答:
It's not a good idea to add an inline click event, you can use addEventListener instead.

So here, I am first selecting the element using document.getElementById and attaching a click event for the same, and later, using document.getElementsByName() I select the output element and print the randomized string.

Also note the [0] which am using with document.getElementsByName() is because if the code encounters multiple elements with the name of output, we select the first one, as it returns an array of matched elements. It will be great if you can add some id to the input field and then use document.getElementById() to select a specific element.

var randomString = function(length) {
  var text = "";
  var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

document.getElementById('pass-button').addEventListener('click', function() {
  document.getElementsByName('output')[0].value = randomString(16);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="passgen">
  <button type="button" id="pass-button">Generate Password</button>
  <br>
  <br>
  <input type="text" name="output">
</section></code>```

Body:
I wrote a javascript program to generate random passwords. How can I output the result into a textfield (input tag)?

var randomString = function(length) {
  var text = "";
  var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

var rs = randomString(16);
console.log(rs);

  <button type="button" id="pass-button" onclick="**???**">Generate Password</button>

  <input type="text" name="output">

Body:
It's not a good idea to add an inline click event, you can use addEventListener instead.

So here, I am first selecting the element using document.getElementById and attaching a click event for the same, and later, using document.getElementsByName() I select the output element and print the randomized string.

Also note the [0] which am using with document.getElementsByName() is because if the code encounters multiple elements with the name of output, we select the first one, as it returns an array of matched elements. It will be great if you can add some id to the input field and then use document.getElementById() to select a specific element.

var randomString = function(length) {
  var text = "";
  var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
  for (var i = 0; i < length; i++) {
    text += possible.charAt(Math.floor(Math.random() * possible.length));
  }
  return text;
}

document.getElementById('pass-button').addEventListener('click', function() {
  document.getElementsByName('output')[0].value = randomString(16);
});

<section id="passgen">
  <button type="button" id="pass-button">Generate Password</button>
  <br>
  <br>
  <input type="text" name="output">
</section>


答:
Very simple document.getElementById("id_of_input_field").value = rs;
or else you can use name of input box to target document.getElementsByName('output')[0].value = rs;

Title: How can I output javascript with "onclick" into a textfield?


问:
How Generate Access Token from Client Id and Secret Id in android or java
i want to generate access token from secret id and client id in android ,  Please help me ?
Thank you for any response.</p>

答:
for that you have to use any server (backend service),
i am assuming that you are using nodeJs server on back-end.

Send secret id to node js server where it checks in db that if the user
  already exists then generate jwt token in return ,else create a new
  user by its secret id and return a jwt token and save this token on client
  side to authenticate every request in headers.


问:
How to use new babel-plugin-relay with Relay Classic finally?
After two days digging I just have one question. How to use babel-plugin-relay instead of deprecated babel-relay-plugin?

What I've done so far:

I have this .babelrc with json below:

```<code>{
  "presets": [
    "es2015",
    "stage-0",
    "react"
  ],
  "plugins": [
    ["relay", {"compat": true, "schema": "./graphql/schema.graphql"}]
  ]
}
</code>```

updateSchema.js file from relay-starter-kit.

webpack.config.js with lines below:

```<code>...
module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react', 'stage-0'],
          plugins: [path.resolve(__dirname, 'graphql', 'babelRelayPlugin')],
        },
      },
...
</code>```

projectRoot/graphql/babelRelayPlugin.js with code below:

```<code>const getbabelRelayPlugin = require('babel-relay-plugin');
const schema = require('./schema.json');

module.exports = getbabelRelayPlugin(schema.data);
</code>```

When I've tried to get rid of babel-relay-plugin and change it to the babel-plugin-react as documenation encourages - I've had error with transpiling Relay.QL`` queries like that:

ERROR in ./app.jsx Module build failed: Error:
  /Users/Vadim/Dropbox/WebStormProjects/mulibwanji/client/src/app.jsx:
  babel-plugin-relay: Missing schema option. Check your .babelrc file or
  wherever you configure your Babel plugins to ensure the "relay" plugin
  has a "schema" option.

What I've done wrong? I can't get clue of using Relay Classic with this babel-plugin-relay... It's not obvious what to do babelRelayPlugin file at documentation for sure after migrating to babel-plugin-relay.

答:
At this moment i've found only one workaround and not sure that it is a good practice. I was inspired with this commit, which wasn't accepted eventually.

I've add babel-plugin-relay-loader with babel-plugin-relay npm packages and deleted babelRelayPlugin.js file also added to my package.json lines below:

```<code>...
  "metadata": {
    "graphql": {
      "schema": "./graphql/schema.json"
    }
  }
...
</code>```

js loaders section in webpack.config.js looks like below:

```<code>...
{
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react', 'stage-0'],
          plugins: ['babel-relay-plugin-loader'],
        },
      },
...
</code>```

And .babelrc file I left as below:

```<code>{
  "plugins": [
    ["babel-relay-plugin-loader"]
  ],
  "presets": [
    "es2015",
    "stage-0",
    "react"
  ]
}
</code>```

It works, but i'm still searching of better solution

Body:
After two days digging I just have one question. How to use babel-plugin-relay instead of deprecated babel-relay-plugin?

What I've done so far:

I have this .babelrc with json below:

{
  "presets": [
    "es2015",
    "stage-0",
    "react"
  ],
  "plugins": [
    ["relay", {"compat": true, "schema": "./graphql/schema.graphql"}]
  ]
}

updateSchema.js file from relay-starter-kit.

webpack.config.js with lines below:

...
module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react', 'stage-0'],
          plugins: [path.resolve(__dirname, 'graphql', 'babelRelayPlugin')],
        },
      },
...

projectRoot/graphql/babelRelayPlugin.js with code below:

const getbabelRelayPlugin = require('babel-relay-plugin');
const schema = require('./schema.json');

module.exports = getbabelRelayPlugin(schema.data);

When I've tried to get rid of babel-relay-plugin and change it to the babel-plugin-react as documenation encourages - I've had error with transpiling Relay.QL`` queries like that:

ERROR in ./app.jsx Module build failed: Error:
  /Users/Vadim/Dropbox/WebStormProjects/mulibwanji/client/src/app.jsx:
  babel-plugin-relay: Missing schema option. Check your .babelrc file or
  wherever you configure your Babel plugins to ensure the "relay" plugin
  has a "schema" option.

What I've done wrong? I can't get clue of using Relay Classic with this babel-plugin-relay... It's not obvious what to do babelRelayPlugin file at documentation for sure after migrating to babel-plugin-relay.

Body:
At this moment i've found only one workaround and not sure that it is a good practice. I was inspired with this commit, which wasn't accepted eventually.

I've add babel-plugin-relay-loader with babel-plugin-relay npm packages and deleted babelRelayPlugin.js file also added to my package.json lines below:

...
  "metadata": {
    "graphql": {
      "schema": "./graphql/schema.json"
    }
  }
...

js loaders section in webpack.config.js looks like below:

...
{
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react', 'stage-0'],
          plugins: ['babel-relay-plugin-loader'],
        },
      },
...

And .babelrc file I left as below:

{
  "plugins": [
    ["babel-relay-plugin-loader"]
  ],
  "presets": [
    "es2015",
    "stage-0",
    "react"
  ]
}

It works, but i'm still searching of better solution


答:
var randomString = function(length) {
        var text = "";
        var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
        for(var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }

var generatePassword = function(length) {
document.getElementById('password').value = randomString(length);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="passgen">
<button type="button" id="pass-button" onclick="generatePassword(16)">Generate Password</button>
<br><br>
<input id='password' type="text" name="output">
</section></code>```

Body:
var randomString = function(length) {
        var text = "";
        var possible = "!@[|^]µ§$%&?*€#ABCDEFGHIJKLMNOPQRSTVWXYZabcdefghijklmnopqrstvwxyz1234567890";
        for(var i = 0; i < length; i++) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        return text;
    }

var generatePassword = function(length) {
document.getElementById('password').value = randomString(length);
}

<section id="passgen">
<button type="button" id="pass-button" onclick="generatePassword(16)">Generate Password</button>
<br><br>
<input id='password' type="text" name="output">
</section>