问:
GeoDjango query: all point that are contained into a multi polygon
I have two models:

```<code>Model_A that contains a GeoDjango Point;

Model_B that contains a GeoDjnago MultiPololygon;
</code>```

For every element in Model_A I have to check if the point is contained into some m_polygon of Model_B element;

I'm able to make this simple query.

But I also thought:
I have a lot of elements in Model_A and few elements in Model_B.
So, probably is more efficient to iterate all elements in Model_B and check if exist some element in Model_A that it is contained into the current Model_B element.

So, is there any way to make this GeoDjango query?

Something like this:

```<code>Model_A.objects.filter(*point_is_contained_into*=a_model_b_mpolygon);
</code>```

------------------ EDIT -----------------

I tried to use this:

```<code>result = Model_A.objects.filter(position__intersects=a_model_b_mpolygon)
</code>```

And this works for me.
Are there contraindications to use this type of query in my case?

答:
From Django version 1.11 you have an optimized option to solve this query.

Assumptions:

Model_A has a geometry field called: model_a_point.

Model_B has a geometry field called: model_b_poly.

Methods used:

Subquery(), new method in Django 1.11 which allows the definition of queries with a subquery part.

OuterRef(), new method in Django 1.11 which is used:

when a queryset in a Subquery needs to refer to a field from the outer
  query.

within(), which:

Tests if the geometry field is spatially within the lookup geometry.

annotate(), which will generate for each item in a queryset, a new field (in our case it will contain the points contained by a polygon.)

Query:

```<code>Model_B.objects.annotate(
    contained_points=Subquery(
        Model_A.objects.filter(
            model_a_point__within=OuterRef('model_b_poly')
        )  # Ref: 1, referenced below, keep reading
    )
)
</code>```

Result and something more:

The query above will have a field contained_points for every polygon in Model_B which contains every point from Model_A contained by this polygon.

If you only want to keep geometry field of those points (lon, lan), at the end of the Subquery call (Ref: 1), use the values() method.

Body:
I have two models:

Model_A that contains a GeoDjango Point;

Model_B that contains a GeoDjnago MultiPololygon;

For every element in Model_A I have to check if the point is contained into some m_polygon of Model_B element;

I'm able to make this simple query.

But I also thought:
I have a lot of elements in Model_A and few elements in Model_B.
So, probably is more efficient to iterate all elements in Model_B and check if exist some element in Model_A that it is contained into the current Model_B element.

So, is there any way to make this GeoDjango query?

Something like this:

Model_A.objects.filter(*point_is_contained_into*=a_model_b_mpolygon);

------------------ EDIT -----------------

I tried to use this:

result = Model_A.objects.filter(position__intersects=a_model_b_mpolygon)

And this works for me.
Are there contraindications to use this type of query in my case?

Body:
From Django version 1.11 you have an optimized option to solve this query.

Assumptions:

Model_A has a geometry field called: model_a_point.

Model_B has a geometry field called: model_b_poly.

Methods used:

Subquery(), new method in Django 1.11 which allows the definition of queries with a subquery part.

OuterRef(), new method in Django 1.11 which is used:

when a queryset in a Subquery needs to refer to a field from the outer
  query.

within(), which:

Tests if the geometry field is spatially within the lookup geometry.

annotate(), which will generate for each item in a queryset, a new field (in our case it will contain the points contained by a polygon.)

Query:

Model_B.objects.annotate(
    contained_points=Subquery(
        Model_A.objects.filter(
            model_a_point__within=OuterRef('model_b_poly')
        )  # Ref: 1, referenced below, keep reading
    )
)

Result and something more:

The query above will have a field contained_points for every polygon in Model_B which contains every point from Model_A contained by this polygon.

If you only want to keep geometry field of those points (lon, lan), at the end of the Subquery call (Ref: 1), use the values() method.


来源: stackexchange

问:
date data loading from backend set bootstrap datepicker in correct format
I use bootstrap datepicker plugin for my calendar and I have a little problem with formatting my loading data, I want to get my date format in this type dd/M/yyyy = 15/Nov/2017 when my page loaded

Could you help me, thank you very much!

The Step 1) is my static HTML,
The Step 2) when my page was loaded

Step 1)

```<code><input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate">
</code>```

Step 2)

```<code><input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="06.06.2017 00:00:00">
</code>```

jsfiddle

答:
It would be like this. In some case, it looks like the first one, in the properties it should has Value method

1)

```<code><input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate.Value.ToString("dd/MMM/yyyy", System.Globalization.CultureInfo.InvariantCulture)">
</code>```

In some case not has Value properties.

2)

```<code><input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate.ToString("dd/MMM/yyyy", System.Globalization.CultureInfo.InvariantCulture)">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use bootstrap datepicker plugin for my calendar and I have a little problem with formatting my loading data, I want to get my date format in this type dd/M/yyyy = 15/Nov/2017 when my page loaded

Could you help me, thank you very much!

The Step 1) is my static HTML,
The Step 2) when my page was loaded

Step 1)

<input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate">

Step 2)

<input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="06.06.2017 00:00:00">

jsfiddle

Body:
It would be like this. In some case, it looks like the first one, in the properties it should has Value method

1)

<input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate.Value.ToString("dd/MMM/yyyy", System.Globalization.CultureInfo.InvariantCulture)">

In some case not has Value properties.

2)

<input type="text" class="form-control" data-provide="datepicker" data-date-format="dd/M/yyyy" value="@Model.LiveDate.ToString("dd/MMM/yyyy", System.Globalization.CultureInfo.InvariantCulture)">


问:
PHP/HTML - Same size of column containing columns
I need some help to be able to match the same size between the first column and the group of four other columns. Yet I tried with solution MatchHeight and row-eq-height. i tried also with a table. The main problem is that it brake the responsive tool.

I'm using bootstrap 3.3.6

Here is the sample I'm working with:

```<code><div class="container">
  <div class="row">
    <div class="col-xs-6 bg-success">
      <div class="small-box">
        <div class="row">
          <div class="col-lg-12 col-xs-12">
            <h3>Colonne 1</h3>
            <p>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ultrices massa ligula, a faucibus nisi scelerisque sit amet. Sed cursus, urna eu suscipit egestas, dui dui luctus purus, malesuada pellentesque dolor dolor ac augue. Duis ac rutrum massa,
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="col-xs-6 bg-warning">
      <div class="small-box">
        <div class="row">
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 2</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 3</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 4</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
          <div class="col-lg-6 col-xs-6">
            <h3>Colonne 5</h3>
            <p>
              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

One of the constraint is to have two rows on the right. I can't just make one unique row.

A real thank to who would like to help and to those who are able to.

答:
Replace all
 with

Body:
I need some help to be able to match the same size between the first column and the group of four other columns. Yet I tried with solution MatchHeight and row-eq-height. i tried also with a table. The main problem is that it brake the responsive tool.

I'm using bootstrap 3.3.6

Here is the sample I'm working with:

Colonne 1

              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ultrices massa ligula, a faucibus nisi scelerisque sit amet. Sed cursus, urna eu suscipit egestas, dui dui luctus purus, malesuada pellentesque dolor dolor ac augue. Duis ac rutrum massa,

Colonne 2

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 3

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 4

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

Colonne 5

              Donec in venenatis enim. Fusce mollis dui a est pharetra mollis. Pellentesque rhoncus, sem nec tempus tincidunt, ligula velit condimentum sapien, non ullamcorper ipsum mi vitae ante. Donec justo neque, euismod ut dapibus ac, varius sit amet ante. Nullam

One of the constraint is to have two rows on the right. I can't just make one unique row.

A real thank to who would like to help and to those who are able to.

Body: Replace all <div class="col-lg-6 col-xs-6"> with <div class="col-lg-3 col-xs-3">


问:
Vuex: Preserve parts of the state when refreshing the browser
I’m using Vue with Vuex. I’ve got the following problem: When the user presses the “refresh button” of the browser, the state in the Vuex store is reset to its initial values. However, I want to preserve the state. More precisely, I want to preserve only parts of the state, but not the whole one.

Now I know there is a plugin called “vuex-persistedstate”. It’s this one:

https://www.npmjs.com/package/vuex-persistedstate

There is also an option to preserve only parts of the states, but I don’t know how to do it precisely. For example, if we have a look at the jsfiddle

https://jsfiddle.net/robinvdvleuten/wmf8zvf8/

there is a variable called “count”. Assume we had another variable “newCount” in the state and I want to persist only newCount, but not count. What in detail do I have to write instead of plugins: [createPersistedState()]?

Thank you very much for any help!

答:
You can't preserve any part of the state after a browser refresh.
Why? Because it's only javascript, everything happen will be reseted after a refresh.

If you want to create persistent data, you have to store it somewhere. Several solutions:

Use a remote database

Create server session

Store in browser local storage (vuex-persistedstate default solution)

Store in cookies

Be carefull with browser storage, some users disable it, you'll have to manage privacy and security policies.


问:
Map throw error on duplicate insertion
I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.

```<code>Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");
</code>```

Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality?

答:
Map.put returns  the previous value associated with key, or null if there was
  no mapping for key. (A null return can also indicate that the map
  previously associated null with key, if the implementation supports
  null values.)

So you can do this:

```<code>public void addItem ( Integer key, String value ) throws Exception {
  String old = map.put( key, value );
  if ( old != null) {
     throw new Exception("Already exists!");
  }
}
</code>```

Beware: in this code the new value is instered anyway, even though the key already existed, you cannot add null as it will throw an exception.

Title: Map throw error on duplicate insertion

Body:
I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.

Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");

Here this map should throw an error since a key '1' is already present.
It can throw an error or does not compile.
Is there any map which has said functionality?

Body:
Map.put returns  the previous value associated with key, or null if there was
  no mapping for key. (A null return can also indicate that the map
  previously associated null with key, if the implementation supports
  null values.)

So you can do this:

public void addItem ( Integer key, String value ) throws Exception {
  String old = map.put( key, value );
  if ( old != null) {
     throw new Exception("Already exists!");
  }
}

Beware: in this code the new value is instered anyway, even though the key already existed, you cannot add null as it will throw an exception.


问:
Analog clock from Windows in my application
Is it possible to use analog clock from Windows in my own application? Call it from some DLL for example.</p>

答: It's not a formally documented interface, i.e. it can break in future Windows versions. But for the current windows versions, it's certainly possible. Using the Shell, open the control panel, enumerate all items, find the clock item, and start it.</p>

ContentLicense: CC BY-SA 2.5


问:
Adding columns in table
I have display quantity and price attributes on my table from database but for some reasons I don't save the total into database but I display total by multiplying quantity * total on the table when data is being fetched.

Total for every column on my table is being displayed accurately. Is there a way that I can add all total columns on the table in my html?

PS: with my code, it only displays the total of the current column of the table

Table

```<code><tbody>
    @foreach($items as $items)
        <tr>
            <td>{{$item>id }}</td>
            <td>{{$item->quantity}}</td>
            <td>{{ $item->price}}</td>
            <td>{{ $item->quantity * $item->price}}</td>
        </tr>
    @endforeach
    <p>Sum: {{ $item->quantity * $item->price}}</p>
</tbody>
</code>```

答:
You can use blade's @php directive like this

```<code><tbody>
@php
$total = 0
    @foreach($items as $items)
    <tr>
        <td>{{$item>id }}</td>
        <td>{{$item->quantity}}</td>
        <td>{{$item->price}}</td>
        <td>{{$total = $total + ($item->quantity * $item->price)}}</td>
    </tr>
    @endforeach

    <p>Sum: {{ $total }}</p>
@endphp
</tbody>
</code>```

Title: Adding columns in table

Body:
I have display quantity and price attributes on my table from database but for some reasons I don't save the total into database but I display total by multiplying quantity * total on the table when data is being fetched.

Total for every column on my table is being displayed accurately. Is there a way that I can add all total columns on the table in my html?

PS: with my code, it only displays the total of the current column of the table

Table

    @foreach($items as $items)

            {{$item>id }}
            {{$item->quantity}}
            {{ $item->price}}
            {{ $item->quantity * $item->price}}

    @endforeach

Sum: {{ $item->quantity * $item->price}}

Body:
You can use blade's @php directive like this

<tbody>
@php
$total = 0
    @foreach($items as $items)
    <tr>
        <td>{{$item>id }}</td>
        <td>{{$item->quantity}}</td>
        <td>{{$item->price}}</td>
        <td>{{$total = $total + ($item->quantity * $item->price)}}</td>
    </tr>
    @endforeach

    <p>Sum: {{ $total }}</p>
@endphp
</tbody>


问:
AS3 drawing Sprite on BitmapData memory leak
I have an AIR app that renders images from a Flash editor. You can customize several surfaces - they all have the same width and height. Each surface is then rendered by the AIR app.

I'm struggling with a memory leak I fail to address.

For each surface I need to render, I have a Sprite containing many components (other sprites - some having event listeners, BitmapDatas and other children components, sprites, etc).

I'm already aware of BitmapData issues to be garbage collected, I tested both :

creating a new BitmapData for each rendering then dispose() and point to null

reuse a single BitmapData for each rendering

Memory leak is still happening in equal proportion.

Here is my loop :

```<code>var bm:BitmapData = new BitmapData(destDim.x, destDim.y, true, bgColor);
var mtx:Matrix = new Matrix();
trace('before drawing :'+(System.privateMemory/1024));
bm.draw(myBigSprite, mtx, null, null, null, true);
trace('after drawing :'+(System.privateMemory/1024));
var result:Bitmap = new Bitmap(bm, PixelSnapping.NEVER, true);

//return result and encode Bitmap to png

result.bitmapData.dispose();
result.bitmapData = null;
result = null;
</code>```

Result :

```<code>before drawing :208364
after drawing :302816
Wrote bitmap to file: surface0.png
before drawing :303296
after drawing :446160
Wrote bitmap to file: surface1.png
before drawing :446160
after drawing :565212
Wrote bitmap to file: surface2.png
before drawing :565924
after drawing :703100
Wrote bitmap to file: surface3.png
before drawing :703572
after drawing :834420
Wrote bitmap to file: surface4.png
</code>```

I feel like I'm missing something in draw function behaviour. It seems like I have newly created instances of the components of myBigSprite that persists after draw operation.

I tried to completely destroy myBigSprite at the end of each loop, it does not change anything....

Any hint would be appreciated !

答:
Ok guys, I eventually understood and fixed this issue.

First of all, I installed and ran Adobe Scout. Excellent tool.

As you may not see (plus it's in French language), I generated 3 surfaces corresponding to the edges. The "big" green bar on the right which is mass memory consuming represent "Bitmap display objects". Interesting ! Never heard of those before.

A Google search later, I found this article : https://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e26.html

It explains

For example, in the code excerpt shown earlier, once the load
  operation for the pict Loader object is complete, the pict object will
  have one child display object, which is the bitmap, loaded. To access
  this bitmap display object, you can write pict.getChildAt(0).

So I began to undestand that, somehow, maybe Bitmap object are attached as children on some objects of myBigSprite.

Finally, I created a recursive function to search and destroy all Bitmap, BitmapData and ByteArray objects contained in myBigSprite AFTER the draw operation

```<code>//inside render function
bm.draw(myBigSprite, mtx, null, null, null, true);
destroyDisplayObjects(myBigSprite);
</code>```

...

```<code>private function destroyDisplayObjects(obj):void{
    if ("numChildren" in obj){
        for (var i:int = 0; i<obj.numChildren; i++)
        {
            destroyDisplayObjects(obj.getChildAt(i));
        }
    }
    else {
        if (flash.utils.getQualifiedClassName(obj) == "flash.display::Bitmap"){
            //trace ('FREE BITMAP');
            obj.bitmapData.dispose();
            obj.bitmapData = null;
            obj = null;
            return;
        }
        else if (flash.utils.getQualifiedClassName(obj) == "flash.display::BitmapData"){
            //trace ('FREE BITMAPDATA');
            obj.dispose();
            obj = null;
            return;
        }
        else if (flash.utils.getQualifiedClassName(obj) == "flash.display::ByteArray"){
            //trace ('FREE BYTEARRAY');
            obj.clear();
            obj = null;
            return;
        }

        return;
    }
}
</code>```

Et voilà, memory is 100% cleaned after the draw operation, no more leak :)

Body:
I have an AIR app that renders images from a Flash editor. You can customize several surfaces - they all have the same width and height. Each surface is then rendered by the AIR app.

I'm struggling with a memory leak I fail to address.

For each surface I need to render, I have a Sprite containing many components (other sprites - some having event listeners, BitmapDatas and other children components, sprites, etc).

I'm already aware of BitmapData issues to be garbage collected, I tested both :

creating a new BitmapData for each rendering then dispose() and point to null

reuse a single BitmapData for each rendering

Memory leak is still happening in equal proportion.

Here is my loop :

var bm:BitmapData = new BitmapData(destDim.x, destDim.y, true, bgColor);
var mtx:Matrix = new Matrix();
trace('before drawing :'+(System.privateMemory/1024));
bm.draw(myBigSprite, mtx, null, null, null, true);
trace('after drawing :'+(System.privateMemory/1024));
var result:Bitmap = new Bitmap(bm, PixelSnapping.NEVER, true);

//return result and encode Bitmap to png

result.bitmapData.dispose();
result.bitmapData = null;
result = null;

Result :

before drawing :208364
after drawing :302816
Wrote bitmap to file: surface0.png
before drawing :303296
after drawing :446160
Wrote bitmap to file: surface1.png
before drawing :446160
after drawing :565212
Wrote bitmap to file: surface2.png
before drawing :565924
after drawing :703100
Wrote bitmap to file: surface3.png
before drawing :703572
after drawing :834420
Wrote bitmap to file: surface4.png

I feel like I'm missing something in draw function behaviour. It seems like I have newly created instances of the components of myBigSprite that persists after draw operation.

I tried to completely destroy myBigSprite at the end of each loop, it does not change anything....

Any hint would be appreciated !

Body:
Ok guys, I eventually understood and fixed this issue.

First of all, I installed and ran Adobe Scout. Excellent tool.

As you may not see (plus it's in French language), I generated 3 surfaces corresponding to the edges. The "big" green bar on the right which is mass memory consuming represent "Bitmap display objects". Interesting ! Never heard of those before.

A Google search later, I found this article : https://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e26.html

It explains

For example, in the code excerpt shown earlier, once the load
  operation for the pict Loader object is complete, the pict object will
  have one child display object, which is the bitmap, loaded. To access
  this bitmap display object, you can write pict.getChildAt(0).

So I began to undestand that, somehow, maybe Bitmap object are attached as children on some objects of myBigSprite.

Finally, I created a recursive function to search and destroy all Bitmap, BitmapData and ByteArray objects contained in myBigSprite AFTER the draw operation

//inside render function
bm.draw(myBigSprite, mtx, null, null, null, true);
destroyDisplayObjects(myBigSprite);

...

private function destroyDisplayObjects(obj):void{
    if ("numChildren" in obj){
        for (var i:int = 0; i<obj.numChildren; i++)
        {
            destroyDisplayObjects(obj.getChildAt(i));
        }
    }
    else {
        if (flash.utils.getQualifiedClassName(obj) == "flash.display::Bitmap"){
            //trace ('FREE BITMAP');
            obj.bitmapData.dispose();
            obj.bitmapData = null;
            obj = null;
            return;
        }
        else if (flash.utils.getQualifiedClassName(obj) == "flash.display::BitmapData"){
            //trace ('FREE BITMAPDATA');
            obj.dispose();
            obj = null;
            return;
        }
        else if (flash.utils.getQualifiedClassName(obj) == "flash.display::ByteArray"){
            //trace ('FREE BYTEARRAY');
            obj.clear();
            obj = null;
            return;
        }

        return;
    }
}

Et voilà, memory is 100% cleaned after the draw operation, no more leak :)


问:
Is it possible to create input scanner between String value Java Console?
I try to custom my Java Console Application, but I have a problem when I try to show it in Command Prompt will appear input Scanner between String...

```<code>int a;
Scanner scan = new Scanner(System.in);
System.out.println("Input value of a: " + (a = scan.nextInt()) + " !");
</code>```

Anyone can resolve this problem, help me....
thank you

答:
1. First of all, your code runs as it is coded not as it is expected.
As your output is blank, and you are wandering why the prompt has not come yet for asking the user input, then let me tell you one thing, that it is actually asking you to enter some input right there. As soon as, you will enter, you shall see the next line of your output will be..

Input value of a: (whatEverYouEntered)

So your final output would be, (strictly as per your code..)

```<code> F:/SMK/oop>javac Main.java
 F:/SMK/oop>5 (assumed you type 5 and press enter)
 F:/SMK/oop>Input value of a: 5
</code>```

2. If you think that your code should print Input value of a: line fist and then you will enter the value, then you'll have to make changes as below.

```<code>int a;
Scanner scan = new Scanner(System.in);
System.out.print("Input value of a: ");
a = scan.nextInt();
</code>```

3. And if you are really curious about the reason why your code was behaving like that..then read this..

I would say, change your code as stated below and then run, you might get a hint, otherwise I'll explain later.

```<code>public static void main(String[] s) {
    int a = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Input value of a: " + (a = new Main().getVal()) + " !");
    System.out.println("A = " + a);
}
public int getVal(){
    System.out.println("getVal called first.");
    return 5;
}
</code>```

See the output now, it shall be.

```<code> F:/SMK/oop>javac Main.java
 F:/SMK/oop>getVal called first.
 F:/SMK/oop>Input value of a: 5
</code>```

The reason is, when JVM interprets System.out.println("Input value of a: " + (a = new Main().getVal()) + " !"); this as a single statement, and to execute it must be complete... so how will it get complete?--> By assigning the value of a. and to do so, it must call getVal() function before printing anything, right?

Exactly the same is happening in your code, as your print statement will be executed after the call of scan.nextInt() and nextInt() immediately asks for user input without showing any message in console. And once the input is provided, it will assign the value to a and now the print statement is actually complete and ready to execute. And hence, you would see the print output after the input prompt.

Hope it gives you good idea about java and programming language as well.

Happy coding :)

Body:
I try to custom my Java Console Application, but I have a problem when I try to show it in Command Prompt will appear input Scanner between String...

int a;
Scanner scan = new Scanner(System.in);
System.out.println("Input value of a: " + (a = scan.nextInt()) + " !");

Anyone can resolve this problem, help me....
thank you

Body:
1. First of all, your code runs as it is coded not as it is expected.
As your output is blank, and you are wandering why the prompt has not come yet for asking the user input, then let me tell you one thing, that it is actually asking you to enter some input right there. As soon as, you will enter, you shall see the next line of your output will be..

Input value of a: (whatEverYouEntered)

So your final output would be, (strictly as per your code..)

 F:/SMK/oop>javac Main.java
 F:/SMK/oop>5 (assumed you type 5 and press enter)
 F:/SMK/oop>Input value of a: 5

2. If you think that your code should print Input value of a: line fist and then you will enter the value, then you'll have to make changes as below.

int a;
Scanner scan = new Scanner(System.in);
System.out.print("Input value of a: ");
a = scan.nextInt();

3. And if you are really curious about the reason why your code was behaving like that..then read this..

I would say, change your code as stated below and then run, you might get a hint, otherwise I'll explain later.

public static void main(String[] s) {
    int a = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Input value of a: " + (a = new Main().getVal()) + " !");
    System.out.println("A = " + a);
}
public int getVal(){
    System.out.println("getVal called first.");
    return 5;
}

See the output now, it shall be.

 F:/SMK/oop>javac Main.java
 F:/SMK/oop>getVal called first.
 F:/SMK/oop>Input value of a: 5

The reason is, when JVM interprets System.out.println("Input value of a: " + (a = new Main().getVal()) + " !"); this as a single statement, and to execute it must be complete... so how will it get complete?--> By assigning the value of a. and to do so, it must call getVal() function before printing anything, right?

Exactly the same is happening in your code, as your print statement will be executed after the call of scan.nextInt() and nextInt() immediately asks for user input without showing any message in console. And once the input is provided, it will assign the value to a and now the print statement is actually complete and ready to execute. And hence, you would see the print output after the input prompt.

Hope it gives you good idea about java and programming language as well.

Happy coding :)


问:
Google Cloud Dataflow: Accessing Google Cloud Pub/Sub in pipeline with DirectPipelineRunner (local job)?
I have written a streaming pipeline using the Google Cloud Dataflow SDK, but I want to test my pipelines locally. My pipeline takes input data from Google Pub/Sub.

Is it possible to run jobs that access Pub/Sub (pubsubIO) using the DirectPipelineRunner (local execution, not in Google Cloud)?

I am running into permissions issues while logged in as my normal user account. I am the owner of the project with the pub/sub topic I am trying to access.

答:
Just to help anyone who would search for this,

With the latest version, you can do this. If you want to run the pipeline in local, use "DirectRunner" to run this in local. Use "DataflowRunner" to run this in the cloud.

set the staging location and the runner as shown below.

```<code>streamingOption.setStagingLocation(PipelineConstants.PUBSUB_STAGING_LOCATION);

streamingOption.setRunner(DataflowRunner.class);
</code>```

or pass it as arguments.

Can you elaborate a bit more about the permission issue that you have faced?

Body:
Just to help anyone who would search for this,

With the latest version, you can do this. If you want to run the pipeline in local, use "DirectRunner" to run this in local. Use "DataflowRunner" to run this in the cloud.

set the staging location and the runner as shown below.

streamingOption.setStagingLocation(PipelineConstants.PUBSUB_STAGING_LOCATION);

streamingOption.setRunner(DataflowRunner.class);

or pass it as arguments.

Can you elaborate a bit more about the permission issue that you have faced?


问:
Collection was modified; enumeration operation may not execute. when update values of hashtable
this code throw exception  while i am trying to update value ,first value only updated and then throw the exception "Collection was modified; enumeration operation may not execute." !!!!

```<code>        Hashtable hh = new Hashtable();
        hh.Add("val 1",null);
        hh.Add("val 2", null);

        foreach (string dd in hh.Keys)
        {
            hh[dd] = "some_value";
           // MessageBox.Show(dd.Value.ToString());
        }
</code>```

i need to update empty values in hashtables or any equivalent structure that has [key,value]??

答:
You need to make copy of hh.Keys, because you are trying to change Hashtable which is invalid operation while enumerating its keys in the foreach loop.

Try this code

```<code>foreach (string dd in new List<object>(hh.Keys.Cast<object>()))
{
    hh[dd] = "some_value";
    MessageBox.Show(dd);
}
</code>```

Body:
this code throw exception  while i am trying to update value ,first value only updated and then throw the exception "Collection was modified; enumeration operation may not execute." !!!!

        Hashtable hh = new Hashtable();
        hh.Add("val 1",null);
        hh.Add("val 2", null);

        foreach (string dd in hh.Keys)
        {
            hh[dd] = "some_value";
           // MessageBox.Show(dd.Value.ToString());
        }

i need to update empty values in hashtables or any equivalent structure that has [key,value]??

Body:
You need to make copy of hh.Keys, because you are trying to change Hashtable which is invalid operation while enumerating its keys in the foreach loop.

Try this code

foreach (string dd in new List<object>(hh.Keys.Cast<object>()))
{
    hh[dd] = "some_value";
    MessageBox.Show(dd);
}


问:
Launch adb commands in python
I try launch adb commands in python without custom modules.

try:

```<code>process = subprocess.Popen('cmd.exe',   stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, shell=True)
process.stdin.write("adb shell uninstall com.q.q".encode("utf8"))
process.stdin.write("adb shell install C:\\...\\qwerty.apk".encode("utf8"))
</code>```

but this not working. Code finish without results

答:
cannot test with your exact commands but that works fine:

```<code>import subprocess

process = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, shell=True)
o,e = process.communicate(b"dir\n")
print(o)
</code>```

(I get the contents of my directory)

so for your example, you're missing the line terminators when sending commands. The commands aren't issued to the cmd program, the pipe is broken before that.

That would work better:

```<code>import subprocess

process = subprocess.Popen('cmd.exe',   stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
process.stdin.write(b"adb shell uninstall com.q.q\n")
process.stdin.write(b"adb shell install C:\\...\\qwerty.apk\n")
o,e = process.communicate()
</code>```

but this is a very strange way to run commands. Just use check_call, with args split properly:

```<code>subprocess.check_call(["adb","shell","uninstall","com.q.q"])
subprocess.check_call(["adb","shell","install",r"C:\...\qwerty.apk"])
</code>```

Title: Launch adb commands in python

Body:
I try launch adb commands in python without custom modules.

try:

process = subprocess.Popen('cmd.exe',   stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, shell=True)
process.stdin.write("adb shell uninstall com.q.q".encode("utf8"))
process.stdin.write("adb shell install C:\\...\\qwerty.apk".encode("utf8"))

but this not working. Code finish without results

Body:
cannot test with your exact commands but that works fine:

import subprocess

process = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, shell=True)
o,e = process.communicate(b"dir\n")
print(o)

(I get the contents of my directory)

so for your example, you're missing the line terminators when sending commands. The commands aren't issued to the cmd program, the pipe is broken before that.

That would work better:

import subprocess

process = subprocess.Popen('cmd.exe',   stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
process.stdin.write(b"adb shell uninstall com.q.q\n")
process.stdin.write(b"adb shell install C:\\...\\qwerty.apk\n")
o,e = process.communicate()

but this is a very strange way to run commands. Just use check_call, with args split properly:

subprocess.check_call(["adb","shell","uninstall","com.q.q"])
subprocess.check_call(["adb","shell","install",r"C:\...\qwerty.apk"])


问:
How to stop thread If response assertion fails in Jmeter
I want to implement error handling in my script (like textcheck in LR).

I’m able to validate the Text using Response Assertion.

But my question is how to stop the thread if the Response Assertion (text check) fails.

答: If you need to limit this behaviour to one request, add a Result Status Action Handler as a child of the request, then set it to Stop Thread


问:
Sylius: how to notify payment if capture token is not in the url?
I am creating my own payment bundle with Payum. I managed to correctly generate the payment order with my payment entity and my bundle redirects correctly to the payment page of my entity (where the user enters their card and PIN number). The problem is that I can not validate the payment. My payment entity only allows me to configure a single payment confirmation asynchronous call url (and it does not allow me to send a parameter with the notification url in each order).

How do I have to proceed to obtain the payment token? Is there any way to get the payment token from the order id and then validate it?

答:
Ok, i think i've made it. This is the "solution":

First of all, i had to create an url for notifications with a controller atached.

```<code>payum_ceca_notification_url:
path: /payum/ceca/bank-notification
methods: [GET, POST]
defaults:
    _controller: CecaPlugin:Notify:do
</code>```

Then in my doAction:

```<code>    public function doAction(Request $request):Response
    {
        $params = $request->request->all();
        $order_id = (int) $params['Num_operacion'];

        $payment = $this->container->get('sylius.repository.payment')->findOneBy(['id' => $order_id]);

        $details = $payment->getDetails();
        $cecaOptions = array(
            'Environment' => $details['Environment'],
            'MerchantID' => $details['MerchantID'],
            'AcquirerBIN' => $details['AcquirerBIN'],
            'TerminalID' => $details['TerminalID'],
            'ClaveCifrado' => $details['ClaveCifrado']);
        $apiCeca = new ApiCeca($cecaOptions);
        $apiCeca->setFormHiddens(array(
            'Num_operacion' => $details['Num_operacion'],
            'Importe' => $details['Amount'],
            'URL_OK' => $details['url_ok'],
            'URL_NOK' => $details['url_nok'].'?pagocancelado=1'
        ));

        // check my sign vs the sign sent to me by payment entity
        $apiCeca->checkTransaction($params);
        $payment->setState(PaymentInterface::STATE_COMPLETED);
        $payment->getOrder()->setPaymentState(OrderPaymentStates::STATE_PAID);
        $manager = $this->container->get('sylius.manager.payment');
        $manager->persist($payment);
        $manager->flush();

        return new Response();
    }
</code>```

I know that it is not the most elegant solution but it is a solution that works, marks the order as paid.

Body:
Ok, i think i've made it. This is the "solution":

First of all, i had to create an url for notifications with a controller atached.

payum_ceca_notification_url:
path: /payum/ceca/bank-notification
methods: [GET, POST]
defaults:
    _controller: CecaPlugin:Notify:do

Then in my doAction:

    public function doAction(Request $request):Response
    {
        $params = $request->request->all();
        $order_id = (int) $params['Num_operacion'];

        $payment = $this->container->get('sylius.repository.payment')->findOneBy(['id' => $order_id]);

        $details = $payment->getDetails();
        $cecaOptions = array(
            'Environment' => $details['Environment'],
            'MerchantID' => $details['MerchantID'],
            'AcquirerBIN' => $details['AcquirerBIN'],
            'TerminalID' => $details['TerminalID'],
            'ClaveCifrado' => $details['ClaveCifrado']);
        $apiCeca = new ApiCeca($cecaOptions);
        $apiCeca->setFormHiddens(array(
            'Num_operacion' => $details['Num_operacion'],
            'Importe' => $details['Amount'],
            'URL_OK' => $details['url_ok'],
            'URL_NOK' => $details['url_nok'].'?pagocancelado=1'
        ));

        // check my sign vs the sign sent to me by payment entity
        $apiCeca->checkTransaction($params);
        $payment->setState(PaymentInterface::STATE_COMPLETED);
        $payment->getOrder()->setPaymentState(OrderPaymentStates::STATE_PAID);
        $manager = $this->container->get('sylius.manager.payment');
        $manager->persist($payment);
        $manager->flush();

        return new Response();
    }

I know that it is not the most elegant solution but it is a solution that works, marks the order as paid.


问:
Appending an element to the end of a list in Scala
I can't add an element of type T into a list List[T].
I tried with myList ::= myElement but it seems it creates a strange object and accessing to myList.last always returns the first element that was put inside the list. How can I solve this problem?

答:
This is similar to one of the answers but in different way :</p>
```<code>scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is similar to one of the answers but in different way :

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)


问:
Import Sikuli in Jython project
I am trying to include sikuli in a python based project.
I know to run sikuli I should have a jython interprater.SO I installed jython 2.5.3 and executed my file with the following command

```<code>jython test.py
</code>```

Content of test.py is

```<code>sys.path.append("path\to\sikuli-java.jar")
from org.sikuli.basics import Debug
</code>```

Error:

```<code>from org.sikuli.basics import Debug
ImportError: No module named org.sikuli.basics
</code>```

Could any one suggest How can import sikuli in my python project if I want to run it with jython interprater?

Any clues are appreciated.

Thanks in advance!!

答: You could use an IDE like PyCharm and set up your jython interpreter there. I've mentioned some steps related to this on SikuliX Bat file not running in Py Script</p>

Title: Import Sikuli in Jython project

Body:
I am trying to include sikuli in a python based project.
I know to run sikuli I should have a jython interprater.SO I installed jython 2.5.3 and executed my file with the following command

jython test.py

Content of test.py is

sys.path.append("path\to\sikuli-java.jar")
from org.sikuli.basics import Debug

Error:

from org.sikuli.basics import Debug
ImportError: No module named org.sikuli.basics

Could any one suggest How can import sikuli in my python project if I want to run it with jython interprater?

Any clues are appreciated.

Thanks in advance!!


问:
IE7/IE8 z-index not cooperating. Suggestions?
EDIT: Solution found. The pink block had overflow:visible !important, which in Internet Explorer invalidated z-index. After removing it, the logo came to the top.

See: http://bit.ly/i7ER3e

See logo "**" (beside top menu) with Firefox/Chrome, it correctly appears above left-content block (the block with pink background).

In IE7/IE8 the logo, it becomes hidden behind the pink block.

I've been messing with this for 2 hours now. Tried a lot of stuff. Can't get it to appear right in IE7/IE8.

Any suggestions?

(Note: I'm working in a really restrictive framework where I cannot simply float the logo before the menu. I have to use position:absolute to place it.)

答:
Try using:

```<code>z-index: -1;
</code>```

for the elements that should be below the logo.

Body:
Try using:

z-index: -1;

for the elements that should be below the logo.


问:
Empty view, with only clickable borders
I need to have a view with borders, and only borders should be clickable.

Here is my code which creates custom view, but when I added gesture all view becomes clickable.

```<code>class RectangleView: UIView {

  override func draw(_ rect: CGRect) {
    let aPath = UIBezierPath()
    aPath.move(to: CGPoint(x:0, y: 0))
    aPath.addLine(to: CGPoint(x:rect.width, y: 0))
    aPath.addLine(to: CGPoint(x:rect.width, y:rect.height))
    aPath.addLine(to: CGPoint(x:0, y:rect.height))
    aPath.close()
    UIColor.green.setStroke()
    aPath.stroke()
    UIColor.clear.setFill()
    aPath.fill()
  }
}
</code>```

Edited, here is the screenshot from other app

so I will click on view under my top view, this one will be in front and will be clickable, so I cant add smaller subView

答:
The most correct way here is to override func point(inside point: CGPoint, with event: UIEvent?) -> Bool for UIView subclass.

Here is example:

```<code>class CustomView: UIView {
    private let shapeLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupShapeLayer()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupShapeLayer() {
        //Draw your own shape here

        shapeLayer.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

        let innerPath = UIBezierPath(arcCenter: center, radius: frame.width / 3, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true)

        let outerPath = UIBezierPath(arcCenter: center, radius: frame.width / 4, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true)

        //Subtract inner path
        innerPath.append(outerPath.reversing())

        shapeLayer.path = innerPath.cgPath
        shapeLayer.lineWidth = 10
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.yellow.cgColor

        layer.addSublayer(shapeLayer)
    }

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return shapeLayer.path?.contains(point) ?? false
    }
}
</code>```

Now you can add UITapGestureRecognizer to check how it works:

```<code>class ViewController: UIViewController {

    @IBOutlet weak var resultLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let customView = CustomView.init(frame: view.frame)
        view.addSubview(customView)

        let recognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        view.addGestureRecognizer(recognizer)
    }

    @objc func tapAction(_ sender: UITapGestureRecognizer) {
        let location = sender.location(in: sender.view)
        let subview = view?.hitTest(location, with: nil)

        if subview is CustomView {
            resultLabel.text = "CustomView"
        }
        else {
            resultLabel.text = "Other"
        }
    }
}
</code>```

Result of tapAction:

If you need several views, there are two possible options:

Store CAShapeLayer inside one CustomView and iterate through it inside point function

Add CustomView for each instance and iterate it through inside UITapGestureRecognizer tap action

Title: Empty view, with only clickable borders

Body:
I need to have a view with borders, and only borders should be clickable.

Here is my code which creates custom view, but when I added gesture all view becomes clickable.

class RectangleView: UIView {

  override func draw(_ rect: CGRect) {
    let aPath = UIBezierPath()
    aPath.move(to: CGPoint(x:0, y: 0))
    aPath.addLine(to: CGPoint(x:rect.width, y: 0))
    aPath.addLine(to: CGPoint(x:rect.width, y:rect.height))
    aPath.addLine(to: CGPoint(x:0, y:rect.height))
    aPath.close()
    UIColor.green.setStroke()
    aPath.stroke()
    UIColor.clear.setFill()
    aPath.fill()
  }
}

Edited, here is the screenshot from other app

so I will click on view under my top view, this one will be in front and will be clickable, so I cant add smaller subView

Body:
The most correct way here is to override func point(inside point: CGPoint, with event: UIEvent?) -> Bool for UIView subclass.

Here is example:

class CustomView: UIView {
    private let shapeLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)

        setupShapeLayer()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupShapeLayer() {
        //Draw your own shape here

        shapeLayer.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

        let innerPath = UIBezierPath(arcCenter: center, radius: frame.width / 3, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true)

        let outerPath = UIBezierPath(arcCenter: center, radius: frame.width / 4, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true)

        //Subtract inner path
        innerPath.append(outerPath.reversing())

        shapeLayer.path = innerPath.cgPath
        shapeLayer.lineWidth = 10
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.yellow.cgColor

        layer.addSublayer(shapeLayer)
    }

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return shapeLayer.path?.contains(point) ?? false
    }
}

Now you can add UITapGestureRecognizer to check how it works:

class ViewController: UIViewController {

    @IBOutlet weak var resultLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let customView = CustomView.init(frame: view.frame)
        view.addSubview(customView)

        let recognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        view.addGestureRecognizer(recognizer)
    }

    @objc func tapAction(_ sender: UITapGestureRecognizer) {
        let location = sender.location(in: sender.view)
        let subview = view?.hitTest(location, with: nil)

        if subview is CustomView {
            resultLabel.text = "CustomView"
        }
        else {
            resultLabel.text = "Other"
        }
    }
}

Result of tapAction:

If you need several views, there are two possible options:

Store CAShapeLayer inside one CustomView and iterate through it inside point function

Add CustomView for each instance and iterate it through inside UITapGestureRecognizer tap action


问:
'module' object has no attribute 'to_bytes' Python
Please advise how I can cx-freeze my python program which uses serial :

```<code>    import serial
    import serial.tools.list_ports;

    print serial.tools.list_ports()
</code>```

Here's my setup.py

```<code>import sys
from cx_Freeze import setup, Executable

    setup(
        name = "My test program",
        version = "3.1",
        description = "My test",
        executables = [Executable("pystest.py", base = "Win32GUI")])
</code>```

After I build using cx_freeze, this is my error :

```<code>---------------------------
cx_Freeze: Python error in main script
---------------------------
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in <module>
    exec(code, m.__dict__)
  File "pystest.py", line 1, in <module>
  File "C:\Python27\lib\site-packages\serial\tools\list_ports.py", line 27, in <module>
    from serial.tools.list_ports_windows import *
  File "C:\Python27\lib\site-packages\serial\tools\list_ports_windows.py", line 127, in <module>
    Ports = serial.to_bytes([80, 111, 114, 116, 115]) # "Ports"
AttributeError: 'module' object has no attribute 'to_bytes'

---------------------------
OK
---------------------------
</code>```

I'm not sure why I see this error. Any advise appreciated.

Here's a screenshot for easy reading :

Thanks.

答:
Ports = serial.to_bytes([80, 111, 114, 116, 115]) # "Ports"  no attribute 'to_bytes'
two step:

1、pip install pyserial==3.4

2、pip install pyserial==2.7

i don't know the reason, but it worked

Body:
Please advise how I can cx-freeze my python program which uses serial :

    import serial
    import serial.tools.list_ports;

    print serial.tools.list_ports()

Here's my setup.py

import sys
from cx_Freeze import setup, Executable

    setup(
        name = "My test program",
        version = "3.1",
        description = "My test",
        executables = [Executable("pystest.py", base = "Win32GUI")])

After I build using cx_freeze, this is my error :

---------------------------
cx_Freeze: Python error in main script
---------------------------
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in <module>
    exec(code, m.__dict__)
  File "pystest.py", line 1, in <module>
  File "C:\Python27\lib\site-packages\serial\tools\list_ports.py", line 27, in <module>
    from serial.tools.list_ports_windows import *
  File "C:\Python27\lib\site-packages\serial\tools\list_ports_windows.py", line 127, in <module>
    Ports = serial.to_bytes([80, 111, 114, 116, 115]) # "Ports"
AttributeError: 'module' object has no attribute 'to_bytes'

---------------------------
OK
---------------------------

I'm not sure why I see this error. Any advise appreciated.

Here's a screenshot for easy reading :

Thanks.


问:
javascript if else statement with timer
I have an 'if else' statement that works. But I'd like to add another condition to it. The statement is below:

```<code>function showDateContent(){
 var d=new Date();
  if(d.getDate()>=11&& d.getMonth()+1 == 11){
   //show something
 }else{
   //show something else
    }
  }

showDateContent();
</code>```

The conditional statement that I am trying to write is like this (below), but it doesn't seem to work. Notice I am trying to get something to happen when the date is between two numbers in the 1st statement, and then I have two more conditional statements similar to my first example.

```<code>function showDateContent(){
 var d=new Date();
  if(d.getDate()> 11 && d.getDate()< 13 && d.getMonth()+1 == 11){
   //show something when the date is between 11 and 13
} else if(d.getDate()>=14&& d.getMonth()+1 == 11){
   //show something when the date is equal or past the date of the 14th
  }else{
   //show something else when the date is before the 11th
    }
  }
}

showDateContent();
</code>```

答:
You should first check if the month is correct

```<code>if(d.getMonth() + 1 == 11) {
...
}
</code>```

Then you have the 3 cases:

```<code>if(d.getDate() < 11) {

} else if(d.getDate() > 13) {

} else {

}
</code>```

So you get this:

```<code> if(d.getMonth() + 1 == 11) {

       if(d.getDate() < 11) {

       } else if(d.getDate() > 13) {

       } else {

       }
    }
</code>```

Title: javascript if else statement with timer

Body:
I have an 'if else' statement that works. But I'd like to add another condition to it. The statement is below:

function showDateContent(){
 var d=new Date();
  if(d.getDate()>=11&& d.getMonth()+1 == 11){
   //show something
 }else{
   //show something else
    }
  }

showDateContent();

The conditional statement that I am trying to write is like this (below), but it doesn't seem to work. Notice I am trying to get something to happen when the date is between two numbers in the 1st statement, and then I have two more conditional statements similar to my first example.

function showDateContent(){
 var d=new Date();
  if(d.getDate()> 11 && d.getDate()< 13 && d.getMonth()+1 == 11){
   //show something when the date is between 11 and 13
} else if(d.getDate()>=14&& d.getMonth()+1 == 11){
   //show something when the date is equal or past the date of the 14th
  }else{
   //show something else when the date is before the 11th
    }
  }
}

showDateContent();

Body:
You should first check if the month is correct

if(d.getMonth() + 1 == 11) {
...
}

Then you have the 3 cases:

if(d.getDate() < 11) {

} else if(d.getDate() > 13) {

} else {

}

So you get this:

 if(d.getMonth() + 1 == 11) {

       if(d.getDate() < 11) {

       } else if(d.getDate() > 13) {

       } else {

       }
    }


问:
Change columns order in opencv mat without copying data
I have an opencv mat which has M rows and 3 columns, is there a way to reorder the mat such that the first and last (i.e., third) columns are switched while the middle column kept in place without copying the data?

答:
OpenCV data is an array of pixels. Sometimes you can get a column or a rectangle view of an image (like with col() ). In which the data is not continuous, and it is calculated, as far as I know, with a step between rows. However the data is shared and is still an array.

Then the question becomes: can I swap two portions of an array without copying the data? Not as far as I know.

You can use optimized functions of OpenCV to swap them, but the data will be copied.

Also, non continuous data is way slower than continuous data in OpenCV functions. More can be read here.


答:
```<code><tbody>
    {{ $total = 0 }}
    @foreach($items as $items)
        <tr>
            <td>{{$item>id }}</td>
            <td>{{$item->quantity}}</td>
            <td>{{ $item->price}}</td>
            <td>{{ $item->quantity * $item->price}}</td>
            {{ $total = $total + ($item->quantity * $item->price) }}
        </tr>

    @endforeach
    <p>Sum: {{ $total }}</p>
</tbody>
</code>```

Title: Adding columns in table

Body:
I have display quantity and price attributes on my table from database but for some reasons I don't save the total into database but I display total by multiplying quantity * total on the table when data is being fetched.

Total for every column on my table is being displayed accurately. Is there a way that I can add all total columns on the table in my html?

PS: with my code, it only displays the total of the current column of the table

Table

    @foreach($items as $items)

            {{$item>id }}
            {{$item->quantity}}
            {{ $item->price}}
            {{ $item->quantity * $item->price}}

    @endforeach

Sum: {{ $item->quantity * $item->price}}


问:
launching browsers from the commandline
pretty new to protractor but this one has me stumped.

Running Angular 1.5.0 on windows 10.

I want to be able to override the browser specified in my config.js file from the command line.  After digging about I found that using the following was how to do it:
protractor --capabilities.browserName='x' config.js

however, if I try to use firefox, then chrome is launched, if I try to launch IE (using --capabilities.browserName='internet explorer' then I get an error about only having one config file.

I also tried putting in rubbish as a browser name and chrome launched - so looks like chrome is the default, from using selenium I had to specify the path to the IE driver server (and actually the chrome driver) - is protractor the same?

For reference the following is the config file - it's pretty basic (like I said I am still learning protractor)

var HtmlReporter = require('protractor-beautiful-reporter');

exports.config = {
    framework: 'jasmine',

```<code>capabilities: {
    'browserName': 'chrome'
},
seleniumAddress: 'http://localhost:4444/wd/hub',

specs: ['LA1-310-Q4.js'],

baseUrl: 'http://localhost:4200',

onPrepare: function() {
    jasmine.getEnv().addReporter(new HtmlReporter({
        baseDirectory: 'reports2/'
    }).getJasmine2Reporter());
}
</code>```

};

答:
I've managed to get this working.  It seems I wasn't aware of how important quotes were.

so using:
protractor --capabilities.browserName='firefox'  config.js
started chrome, however changing this to:
protractor --capabilities.browserName=firefox config.js
launched firefox.  For Internet Explorer, I had to use double quotes.  Sorted now.

Title: launching browsers from the commandline

Body:
pretty new to protractor but this one has me stumped.

Running Angular 1.5.0 on windows 10.

I want to be able to override the browser specified in my config.js file from the command line.  After digging about I found that using the following was how to do it:
protractor --capabilities.browserName='x' config.js

however, if I try to use firefox, then chrome is launched, if I try to launch IE (using --capabilities.browserName='internet explorer' then I get an error about only having one config file.

I also tried putting in rubbish as a browser name and chrome launched - so looks like chrome is the default, from using selenium I had to specify the path to the IE driver server (and actually the chrome driver) - is protractor the same?

For reference the following is the config file - it's pretty basic (like I said I am still learning protractor)

var HtmlReporter = require('protractor-beautiful-reporter');

exports.config = {
    framework: 'jasmine',

capabilities: {
    'browserName': 'chrome'
},
seleniumAddress: 'http://localhost:4444/wd/hub',

specs: ['LA1-310-Q4.js'],

baseUrl: 'http://localhost:4200',

onPrepare: function() {
    jasmine.getEnv().addReporter(new HtmlReporter({
        baseDirectory: 'reports2/'
    }).getJasmine2Reporter());
}

};


问:
How to configure UTF-8 encoding on incoming emails in MS Outlook?
I checked the MS Outlook (office 365, 2013 and 2010) for options to configure UTF-8 character encoding.

I found the options for out going email in: File > Options > Advanced > International Options.

BUT

I am not able to find the option to configure of incoming emails. Does anybody have any idea about this?

答: You can change the encoding of a particular email from Actions (Move menu) > Other Actions >  Encoding > More


问:
How to append a character using regex in rewrite rule?
I have to rewrite a rule in which on the basis of a first char of a string i have to append a character in url.
For example :-

```<code>/us/en/products/collections/jewelery/bracelet.html  ---->    /content/us/en/products/collections/jewelery/b/bracelet.html

/au/en/products/collections/watches/reverso.html   ----->    /content/us/en/products/collections/watches/r/reverso.html

/us/en/products/collections/watches/hybrid.html   ------>    /content/us/en/products/collections/watches/h/hybrid.html
</code>```

As you can see in above example on the basis of the last string(bracelet,reverso,hybrid). I'm appending the first character of string before it.

I have matched the last character occurrence after "/" using "(/([^/]+)$)" pattern but didn't find any way to extract first char and append it before this. Is it possible to this. If yes please guide.

答:
You can use this rule in your root .htaccess:</p>

```<code>RewriteEngine On

RewriteRule ^/?(?!content/)(.+)/([a-z])([\w-]*\.html)$ /content/$1/$2/$2$3 [L,NC]
</code>```

Body:
I have to rewrite a rule in which on the basis of a first char of a string i have to append a character in url.
For example :-

/us/en/products/collections/jewelery/bracelet.html  ---->    /content/us/en/products/collections/jewelery/b/bracelet.html

/au/en/products/collections/watches/reverso.html   ----->    /content/us/en/products/collections/watches/r/reverso.html

/us/en/products/collections/watches/hybrid.html   ------>    /content/us/en/products/collections/watches/h/hybrid.html

As you can see in above example on the basis of the last string(bracelet,reverso,hybrid). I'm appending the first character of string before it.

I have matched the last character occurrence after "/" using "(/([^/]+)$)" pattern but didn't find any way to extract first char and append it before this. Is it possible to this. If yes please guide.

Body:
You can use this rule in your root .htaccess:

RewriteEngine On

RewriteRule ^/?(?!content/)(.+)/([a-z])([\w-]*\.html)$ /content/$1/$2/$2$3 [L,NC]


问:
powershell run java process problem
I'm trying to run a java process via Powershell in Windows XP.  Here's the command:

```<code>java.exe -cp .;./common.jar -Dcontext=atest1 -Dresourcepath=. DW_Install
</code>```

So, the classpath is . and .\common.jar (I think java takes the wrong slashes, right?)  There are two environment variables, one "atest1" the other "." and the class to execute main on is DW_Install (in the default package).

This command works in cmd.exe, but doesn't is PS.  What's going on? What is PS doing while parsing this command that CMD doesn't do (or vice versa)?

Aaron

答:
The problem is that PS for some reason parses -Dresourcepath=. differently than cmd.  What works is

```<code>java -cp '.;.\common.jar' -Dcontext=atest1 "-Dresourcepath=." DW_Install
</code>```

It doesn't matter which way the slash goes, and it doesn't matter which quotes one uses (' or ").  The classpath must be escaped, however, with some kind of quotes.  A good test to see what's getting by the PS interpreter is to echo it.   The following:

```<code>echo java -cp '.;.\common.jar' -Dcontext=atest1 -Dresourcepath=. DW_Install
</code>```

yields the following output:

```<code>java
-cp
.;.\common.jar
-Dcontext=atest1
-Dresourcepath=
.
DW_Install
</code>```

(Notice the resourcepath and the value of resourcepath are not on the same line.)  Whereas the output to

```<code>echo java -cp '.;.\common.jar' -Dcontext=atest1 '-Dresourcepath=.' DW_Install
</code>```

yields the following output:

```<code>java
-cp
.;.\common.jar
-Dcontext=etaste1
-Dresourcepath=.
DW_Install
</code>```

Which is much more to our liking.

Although I wish this upon none of you, I hope that this post helps those of you that must deploy java projects on Windows machines (even though they will not run on any other platform ever).

Title: powershell run java process problem

Body:
I'm trying to run a java process via Powershell in Windows XP.  Here's the command:

java.exe -cp .;./common.jar -Dcontext=atest1 -Dresourcepath=. DW_Install

So, the classpath is . and .\common.jar (I think java takes the wrong slashes, right?)  There are two environment variables, one "atest1" the other "." and the class to execute main on is DW_Install (in the default package).

This command works in cmd.exe, but doesn't is PS.  What's going on? What is PS doing while parsing this command that CMD doesn't do (or vice versa)?

Aaron

Body:
The problem is that PS for some reason parses -Dresourcepath=. differently than cmd.  What works is

java -cp '.;.\common.jar' -Dcontext=atest1 "-Dresourcepath=." DW_Install

It doesn't matter which way the slash goes, and it doesn't matter which quotes one uses (' or ").  The classpath must be escaped, however, with some kind of quotes.  A good test to see what's getting by the PS interpreter is to echo it.   The following:

echo java -cp '.;.\common.jar' -Dcontext=atest1 -Dresourcepath=. DW_Install

yields the following output:

java
-cp
.;.\common.jar
-Dcontext=atest1
-Dresourcepath=
.
DW_Install

(Notice the resourcepath and the value of resourcepath are not on the same line.)  Whereas the output to

echo java -cp '.;.\common.jar' -Dcontext=atest1 '-Dresourcepath=.' DW_Install

yields the following output:

java
-cp
.;.\common.jar
-Dcontext=etaste1
-Dresourcepath=.
DW_Install

Which is much more to our liking.

Although I wish this upon none of you, I hope that this post helps those of you that must deploy java projects on Windows machines (even though they will not run on any other platform ever).


问:
Keil µvision 5 header file shows an error, however it is compiled without problems
I got access to this project. It is compiled in Keil µvision 5. When I compile the project it has no errors. However, when I access a header file it shows me an error, saying that s8 variable has the following error = error: unknown type name 's8'.

```<code>    typedef struct
    {
      s8 str[PARAM_TEXT_SIZE];
    }
    text_struct;
</code>```

The variable is defined as follow:

```<code>   typedef char   s8;
</code>```

I wonder whether I have misconfigured the compiler, or why this error is neglected after compiling.

PS: This is my first question in the StackOverflow site. Sorry if my question is not clear or is wrongly placed.

答:
If s8 is defined in a header, let's say foo.h, and your text_struct is defined in another header, call it bar.h then it compiles perfectly if the file that includes bar.h includes foo.h first. It is however not clean, it's usually a good practice not to rely on such pre-requisite includes.

Here's a very simple example :

foo.h

```<code>typedef int myType;
</code>```

bar.h

```<code>typedef struct {
    myType x;
} myStruct;
</code>```

main.c

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include "foo.h"
#include "bar.h"

myStruct y;

int main(void) {
    return 0;
}
</code>```

This will compile without issue, however if bar.h is statically evaluated then it'll produce an error since myType is not known here. If bar.h is included without foo.h to be included as well, then you'll have a compilation error. Here's an example :

error.c

```<code>#include "bar.h"

myStruct z;
</code>```

gcc -I. error.c -o error.o

In file included from error.c:1:0:
  bar.h:2:5: error: unknown type name 'myType'
       myType x;

Body:
I got access to this project. It is compiled in Keil µvision 5. When I compile the project it has no errors. However, when I access a header file it shows me an error, saying that s8 variable has the following error = error: unknown type name 's8'.

    typedef struct
    {
      s8 str[PARAM_TEXT_SIZE];
    }
    text_struct;

The variable is defined as follow:

   typedef char   s8;

I wonder whether I have misconfigured the compiler, or why this error is neglected after compiling.

PS: This is my first question in the StackOverflow site. Sorry if my question is not clear or is wrongly placed.

Body:
If s8 is defined in a header, let's say foo.h, and your text_struct is defined in another header, call it bar.h then it compiles perfectly if the file that includes bar.h includes foo.h first. It is however not clean, it's usually a good practice not to rely on such pre-requisite includes.

Here's a very simple example :

foo.h

typedef int myType;

bar.h

typedef struct {
    myType x;
} myStruct;

main.c

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include "foo.h"
#include "bar.h"

myStruct y;

int main(void) {
    return 0;
}

This will compile without issue, however if bar.h is statically evaluated then it'll produce an error since myType is not known here. If bar.h is included without foo.h to be included as well, then you'll have a compilation error. Here's an example :

error.c

#include "bar.h"

myStruct z;

gcc -I. error.c -o error.o

In file included from error.c:1:0:
  bar.h:2:5: error: unknown type name 'myType'
       myType x;


问:
Adding columns in table
I have display quantity and price attributes on my table from database but for some reasons I don't save the total into database but I display total by multiplying quantity * total on the table when data is being fetched.

Total for every column on my table is being displayed accurately. Is there a way that I can add all total columns on the table in my html?

PS: with my code, it only displays the total of the current column of the table

Table

```<code><tbody>
    @foreach($items as $items)
        <tr>
            <td>{{$item>id }}</td>
            <td>{{$item->quantity}}</td>
            <td>{{ $item->price}}</td>
            <td>{{ $item->quantity * $item->price}}</td>
        </tr>
    @endforeach
    <p>Sum: {{ $item->quantity * $item->price}}</p>
</tbody>
</code>```

答:
Try the following:

```<code>{{ $sum = 0 }}
<tbody>
    @foreach($items as $items)
       <tr>
          <td>{{$item>id }}</td>
          <td>{{$item->quantity}}</td>
          <td>{{ $item->price}}</td>
          <td>{{ $item->quantity * $item->price}}</td>
      </tr>
      $sum+ = $item->quantity * $item->price;
    @endforeach
    <p>Sum: {{ $sum }}</p>
</tbody>
</code>```

Title: Adding columns in table

Body:
Try the following:

{{ $sum = 0 }}
<tbody>
    @foreach($items as $items)
       <tr>
          <td>{{$item>id }}</td>
          <td>{{$item->quantity}}</td>
          <td>{{ $item->price}}</td>
          <td>{{ $item->quantity * $item->price}}</td>
      </tr>
      $sum+ = $item->quantity * $item->price;
    @endforeach
    <p>Sum: {{ $sum }}</p>
</tbody>


问:
what is the minimum data size used in the database level Projects?
I have been called for telephonic round and asked a question like how much data size have been used in the project . I think this question is about size of the project . They are expecting in Some GB . :)</p>

答:
Is it a project with some statistical analysis or something  heavily dependent on probability? Then SAMPLE SIZE is often (wrongly) worded as DATA SIZE when you speak about data gathering and DB to support that.

In simple terms -  how much data have you used to notice / link / prove some hypothesis.

It's more suited for math section of SE then. But if you need to take a quick look into more explanation then you could at least skip-read this:

sample size

If it's not this, then you should encourage the person to explain itself, and tell her it's not the standard term when speaking with DB admins. Maybe management uses it for something completely different. But IMHO it's the interviewer job to know the communication with his/her target audience, especially when being told something is not understood.

Personally, if someone pointed out something like this immediately to me during interview I would take it a s a proof he knows his domain well and is proactive in asking what he/she doesn't understand, but might be that some managers full of ego would take it as an insult.


问:
Getting HTTP-401 error for SSO application using Apache JMeter 3.0
I am getting HTTP-401 (Unauthorized) error for single sign-on (SSO) application which I am trying to test. I am passing HTTP Authorization Manager with following information:
Username/Password/Domain/Mechanism(KERBEROS).

I am getting following response headers in "View Results Tree" listener:

HTTP/1.1 401 Unauthorized
content-length: 11785
content-type: text/html
date: Thu, 09 Nov 2017 21:55:38 GMT
p3p: CP="NON CUR OTPi OUR NOR UNI"
www-authenticate: Negotiate
cache-control: no-cache
pragma: no-cache
Set-Cookie: PD-S-SESSION-ID=0_7Yn3C....Ra4+IsxI=; Path=/; Secure; HttpOnly

Can anybody help please?

Thanks,
Krunal

答:
WWW-Authenticate header has several directives which determine authentication scheme.

Negotiate value may stand either for NTLM or for Kerberos so you need to add HTTP Authorization Manager to your Test Plan and configure it accordingly (you might need to contact your system administrator or application developers to get the correct details).

See Windows Authentication with Apache JMeter article for more details on bypassing NTLM and/or Kerberos authentication challenges in JMeter tests.


问:
Unable to locate package virtualenv in ubuntu-13 on a virtual-machine
When i try to run the command:

sudo apt-get install virtualenv

The error I get in response is:

E: Unable to locate package virtualenv

答: It's also possible that you may not have run sudo apt-get update. It worked for me.


问:
Getting an IndexOutOfBoundsException: -1 when no negative numbers are involved
I've been creating a graph to run my implementation of A* on, and I seem to be stuck at a certain error for finding the neighbours of a node. My logic is that in my 2D ArrayList which represents an adjacency matrix, I have in list 1: Nodes a b c d, and in List 2, Nodes a b c d, and the indexes at which they meet should have a value other than 0 in them to show that an edge exists. This is what I'm trying to do here:

```<code>public List<Node> neighbours(Node a){
        List<Node> neighbours = new ArrayList<Node>();
        for(int i = 0; i < nodes.size() - 1; i ++){
            int n = matrix.get(matrix.indexOf(a)).get(i);
            if (n != 0){
                neighbours.add(nodes.get(i));
            }
        }
        return neighbours;
    }
</code>```

However I get a nice Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 error, I've stared at this for 30 minutes but I have no clue where this -1 is coming from. I will also add the code for the construction of the matrix as this may hold a clue:

```<code>public void addNode (Node a){
        int count = 0;
        nodes.add(a);
        matrix.add(new ArrayList<Integer>(nodes.size()));
        for (List<Integer> list : matrix){
            count++;
            int diff = Math.abs(nodes.size() - list.size());
            if (diff != 0){
                for (int i = 0; i < diff; i ++)
                    matrix.get(count-1).add(0);
            }
        }
    }
</code>```

I update the size of the matrix each time a node is added.
I hope this isn't a case where the answer is just staring me in the face but I'm too tired to see it. Thanks for any help!

答:
Are you sure, that value a is in matrix? If no then

```<code>matrix.indexOf(a)
</code>```

may return -1 when this value is not found.

Body:
I've been creating a graph to run my implementation of A* on, and I seem to be stuck at a certain error for finding the neighbours of a node. My logic is that in my 2D ArrayList which represents an adjacency matrix, I have in list 1: Nodes a b c d, and in List 2, Nodes a b c d, and the indexes at which they meet should have a value other than 0 in them to show that an edge exists. This is what I'm trying to do here:

public List<Node> neighbours(Node a){
        List<Node> neighbours = new ArrayList<Node>();
        for(int i = 0; i < nodes.size() - 1; i ++){
            int n = matrix.get(matrix.indexOf(a)).get(i);
            if (n != 0){
                neighbours.add(nodes.get(i));
            }
        }
        return neighbours;
    }

However I get a nice Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 error, I've stared at this for 30 minutes but I have no clue where this -1 is coming from. I will also add the code for the construction of the matrix as this may hold a clue:

public void addNode (Node a){
        int count = 0;
        nodes.add(a);
        matrix.add(new ArrayList<Integer>(nodes.size()));
        for (List<Integer> list : matrix){
            count++;
            int diff = Math.abs(nodes.size() - list.size());
            if (diff != 0){
                for (int i = 0; i < diff; i ++)
                    matrix.get(count-1).add(0);
            }
        }
    }

I update the size of the matrix each time a node is added.
I hope this isn't a case where the answer is just staring me in the face but I'm too tired to see it. Thanks for any help!

Body:
Are you sure, that value a is in matrix? If no then

matrix.indexOf(a)

may return -1 when this value is not found.


问:
Kotlin VerifyError: Uninitialized object exists on backward branch 90
I am using the Kotlin getting started guide to setup Kotlin for the first time on IntelliJ IDEA with the following configuration:

```<code>IntelliJ IDEA 2017.2.5
Build #IC-172.4343.14, built on September 26, 2017
JRE: 1.8.0_152-release-915-b12 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.11.6
</code>```

I created an App.kt file in a new Kotlin project with the following code:

```<code>fun main(args: Array<String>) {
    println("hello")
}
</code>```

On running the code through the IDE, I get the following error:

```<code>Error:Internal error: (java.lang.VerifyError) Uninitialized object exists on backward branch 90
Exception Details:
  Location:
    org/jetbrains/kotlin/jps/build/KotlinBuilder.createCompileEnvironment(Ljava/util/Map;Lorg/jetbrains/kotlin/incremental/components/LookupTracker;Lorg/jetbrains/jps/incremental/CompileContext;Lorg/jetbrains/kotlin/jps/build/KotlinBuilder$MessageCollectorAdapter;)Lorg/jetbrains/kotlin/compilerRunner/JpsCompilerEnvironment; @171: goto
  Reason:
    Error exists in the bytecode
  Bytecode:
    0000000: bb03 fe59 b703 ff3a 0619 063a 0719 0713
    0000010: 02d7 2cb6 0403 5719 0713 0405 bb04 0759
    0000020: 2b3a 083a 093a 0a3a 0b3a 0c19 083a 0dbb
    0000030: 0409 5919 08b9 040a 0100 b804 10b7 0411
    0000040: c002 893a 0e19 0db9 028c 0100 c000 b03a
    0000050: 0f19 0fb9 00b9 0100 3a10 1910 b900 be01
    0000060: 0099 004d 1910 b900 c201 003a 1119 0e19
    0000070: 11c0 028e 3a12 3a13 1912 b902 9101 00c0
    0000080: 00c4 b804 173a 1419 1319 1419 11c0 028e
    0000090: 3a15 3a16 3a17 1915 b902 9401 003a 1819
    00000a0: 1719 1619 18b9 041b 0300 57a7 ffaf 190e
    00000b0: 0000 3a13 190c 190b 190a 1909 1913 b704
    00000c0: 1eb6 0403 5719 0713 0420 bb04 2259 2c2b
    00000d0: 2db7 0425 b604 0357 1907 b604 283a 052a
    00000e0: b704 2c3a 0619 06c6 0010 1906 b904 3101
    00000f0: 00b6 013c 9a00 1319 04b2 0216 1304 3301
    0000100: 0701 b801 fa01 b0bb 0262 5919 0619 05b2
    0000110: 002e b604 3719 04c0 01c7 bb04 3959 b704
    0000120: 3ab7 043d b0
  Stackmap Table:
    full_frame(@90,{Object[#2],Object[#649],Object[#727],Object[#98],Object[#428],Top,Object[#1022],Object[#1022],Object[#649],Uninitialized[#28],Uninitialized[#28],Object[#1005],Object[#1022],Object[#649],Object[#649],Object[#176],Object[#187]},{})
    same_frame_extended(@174)
    full_frame(@247,{Object[#2],Object[#649],Object[#727],Object[#98],Object[#428],Object[#1102],Object[#1070],Object[#1022],Object[#649],Object[#1031],Object[#1031],Object[#1005],Object[#1022],Object[#649],Object[#649],Object[#176],Object[#187],Top,Top,Object[#649]},{})
    same_frame(@263)
java.lang.VerifyError: Uninitialized object exists on backward branch 90
Exception Details:
  Location:
    org/jetbrains/kotlin/jps/build/KotlinBuilder.createCompileEnvironment(Ljava/util/Map;Lorg/jetbrains/kotlin/incremental/components/LookupTracker;Lorg/jetbrains/jps/incremental/CompileContext;Lorg/jetbrains/kotlin/jps/build/KotlinBuilder$MessageCollectorAdapter;)Lorg/jetbrains/kotlin/compilerRunner/JpsCompilerEnvironment; @171: goto
  Reason:
    Error exists in the bytecode
  Bytecode:
    0000000: bb03 fe59 b703 ff3a 0619 063a 0719 0713
    0000010: 02d7 2cb6 0403 5719 0713 0405 bb04 0759
    0000020: 2b3a 083a 093a 0a3a 0b3a 0c19 083a 0dbb
    0000030: 0409 5919 08b9 040a 0100 b804 10b7 0411
    0000040: c002 893a 0e19 0db9 028c 0100 c000 b03a
    0000050: 0f19 0fb9 00b9 0100 3a10 1910 b900 be01
    0000060: 0099 004d 1910 b900 c201 003a 1119 0e19
    0000070: 11c0 028e 3a12 3a13 1912 b902 9101 00c0
    0000080: 00c4 b804 173a 1419 1319 1419 11c0 028e
    0000090: 3a15 3a16 3a17 1915 b902 9401 003a 1819
    00000a0: 1719 1619 18b9 041b 0300 57a7 ffaf 190e
    00000b0: 0000 3a13 190c 190b 190a 1909 1913 b704
    00000c0: 1eb6 0403 5719 0713 0420 bb04 2259 2c2b
    00000d0: 2db7 0425 b604 0357 1907 b604 283a 052a
    00000e0: b704 2c3a 0619 06c6 0010 1906 b904 3101
    00000f0: 00b6 013c 9a00 1319 04b2 0216 1304 3301
    0000100: 0701 b801 fa01 b0bb 0262 5919 0619 05b2
    0000110: 002e b604 3719 04c0 01c7 bb04 3959 b704
    0000120: 3ab7 043d b0
  Stackmap Table:
    full_frame(@90,{Object[#2],Object[#649],Object[#727],Object[#98],Object[#428],Top,Object[#1022],Object[#1022],Object[#649],Uninitialized[#28],Uninitialized[#28],Object[#1005],Object[#1022],Object[#649],Object[#649],Object[#176],Object[#187]},{})
    same_frame_extended(@174)
    full_frame(@247,{Object[#2],Object[#649],Object[#727],Object[#98],Object[#428],Object[#1102],Object[#1070],Object[#1022],Object[#649],Object[#1031],Object[#1031],Object[#1005],Object[#1022],Object[#649],Object[#649],Object[#176],Object[#187],Top,Top,Object[#649]},{})
    same_frame(@263)
    at org.jetbrains.kotlin.jps.build.KotlinBuilderService.createModuleLevelBuilders(KotlinBuilderService.java:30)
    at org.jetbrains.jps.incremental.BuilderRegistry.<init>(BuilderRegistry.java:54)
    at org.jetbrains.jps.incremental.BuilderRegistry.<init>(BuilderRegistry.java:33)
    at org.jetbrains.jps.incremental.BuilderRegistry$Holder.<clinit>(BuilderRegistry.java:36)
    at org.jetbrains.jps.incremental.BuilderRegistry.getInstance(BuilderRegistry.java:43)
    at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:133)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:295)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:125)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:236)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$$Lambda$3/1147174008.run(Unknown Source)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$$Lambda$1/684874119.run(Unknown Source)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
This is due to a bug in earlier JDK 8 versions. Open up the project structure for your project and change your project SDK to a more recent version.

Upgrading from JDK 1.8.0_11 to 1.80_72 solved the problem for me.

Body:
I am using the Kotlin getting started guide to setup Kotlin for the first time on IntelliJ IDEA with the following configuration:

IntelliJ IDEA 2017.2.5
Build #IC-172.4343.14, built on September 26, 2017
JRE: 1.8.0_152-release-915-b12 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Mac OS X 10.11.6

I created an App.kt file in a new Kotlin project with the following code:

fun main(args: Array<String>) {
    println("hello")
}

On running the code through the IDE, I get the following error:

Error:Internal error: (java.lang.VerifyError) Uninitialized object exists on backward branch 90
Exception Details:
  Location:
    org/jetbrains/kotlin/jps/build/KotlinBuilder.createCompileEnvironment(Ljava/util/Map;Lorg/jetbrains/kotlin/incremental/components/LookupTracker;Lorg/jetbrains/jps/incremental/CompileContext;Lorg/jetbrains/kotlin/jps/build/KotlinBuilder$MessageCollectorAdapter;)Lorg/jetbrains/kotlin/compilerRunner/JpsCompilerEnvironment; @171: goto
  Reason:
    Error exists in the bytecode
  Bytecode:
    0000000: bb03 fe59 b703 ff3a 0619 063a 0719 0713
    0000010: 02d7 2cb6 0403 5719 0713 0405 bb04 0759
    0000020: 2b3a 083a 093a 0a3a 0b3a 0c19 083a 0dbb
    0000030: 0409 5919 08b9 040a 0100 b804 10b7 0411
    0000040: c002 893a 0e19 0db9 028c 0100 c000 b03a
    0000050: 0f19 0fb9 00b9 0100 3a10 1910 b900 be01
    0000060: 0099 004d 1910 b900 c201 003a 1119 0e19
    0000070: 11c0 028e 3a12 3a13 1912 b902 9101 00c0
    0000080: 00c4 b804 173a 1419 1319 1419 11c0 028e
    0000090: 3a15 3a16 3a17 1915 b902 9401 003a 1819
    00000a0: 1719 1619 18b9 041b 0300 57a7 ffaf 190e
    00000b0: 0000 3a13 190c 190b 190a 1909 1913 b704
    00000c0: 1eb6 0403 5719 0713 0420 bb04 2259 2c2b
    00000d0: 2db7 0425 b604 0357 1907 b604 283a 052a
    00000e0: b704 2c3a 0619 06c6 0010 1906 b904 3101
    00000f0: 00b6 013c 9a00 1319 04b2 0216 1304 3301
    0000100: 0701 b801 fa01 b0bb 0262 5919 0619 05b2
    0000110: 002e b604 3719 04c0 01c7 bb04 3959 b704
    0000120: 3ab7 043d b0
  Stackmap Table:
    full_frame(@90,{Object[#2],Object[#649],Object[#727],Object[#98],Object[#428],Top,Object[#1022],Object[#1022],Object[#649],Uninitialized[#28],Uninitialized[#28],Object[#1005],Object[#1022],Object[#649],Object[#649],Object[#176],Object[#187]},{})
    same_frame_extended(@174)
    full_frame(@247,{Object[#2],Object[#649],Object[#727],Object[#98],Object[#428],Object[#1102],Object[#1070],Object[#1022],Object[#649],Object[#1031],Object[#1031],Object[#1005],Object[#1022],Object[#649],Object[#649],Object[#176],Object[#187],Top,Top,Object[#649]},{})
    same_frame(@263)
java.lang.VerifyError: Uninitialized object exists on backward branch 90
Exception Details:
  Location:
    org/jetbrains/kotlin/jps/build/KotlinBuilder.createCompileEnvironment(Ljava/util/Map;Lorg/jetbrains/kotlin/incremental/components/LookupTracker;Lorg/jetbrains/jps/incremental/CompileContext;Lorg/jetbrains/kotlin/jps/build/KotlinBuilder$MessageCollectorAdapter;)Lorg/jetbrains/kotlin/compilerRunner/JpsCompilerEnvironment; @171: goto
  Reason:
    Error exists in the bytecode
  Bytecode:
    0000000: bb03 fe59 b703 ff3a 0619 063a 0719 0713
    0000010: 02d7 2cb6 0403 5719 0713 0405 bb04 0759
    0000020: 2b3a 083a 093a 0a3a 0b3a 0c19 083a 0dbb
    0000030: 0409 5919 08b9 040a 0100 b804 10b7 0411
    0000040: c002 893a 0e19 0db9 028c 0100 c000 b03a
    0000050: 0f19 0fb9 00b9 0100 3a10 1910 b900 be01
    0000060: 0099 004d 1910 b900 c201 003a 1119 0e19
    0000070: 11c0 028e 3a12 3a13 1912 b902 9101 00c0
    0000080: 00c4 b804 173a 1419 1319 1419 11c0 028e
    0000090: 3a15 3a16 3a17 1915 b902 9401 003a 1819
    00000a0: 1719 1619 18b9 041b 0300 57a7 ffaf 190e
    00000b0: 0000 3a13 190c 190b 190a 1909 1913 b704
    00000c0: 1eb6 0403 5719 0713 0420 bb04 2259 2c2b
    00000d0: 2db7 0425 b604 0357 1907 b604 283a 052a
    00000e0: b704 2c3a 0619 06c6 0010 1906 b904 3101
    00000f0: 00b6 013c 9a00 1319 04b2 0216 1304 3301
    0000100: 0701 b801 fa01 b0bb 0262 5919 0619 05b2
    0000110: 002e b604 3719 04c0 01c7 bb04 3959 b704
    0000120: 3ab7 043d b0
  Stackmap Table:
    full_frame(@90,{Object[#2],Object[#649],Object[#727],Object[#98],Object[#428],Top,Object[#1022],Object[#1022],Object[#649],Uninitialized[#28],Uninitialized[#28],Object[#1005],Object[#1022],Object[#649],Object[#649],Object[#176],Object[#187]},{})
    same_frame_extended(@174)
    full_frame(@247,{Object[#2],Object[#649],Object[#727],Object[#98],Object[#428],Object[#1102],Object[#1070],Object[#1022],Object[#649],Object[#1031],Object[#1031],Object[#1005],Object[#1022],Object[#649],Object[#649],Object[#176],Object[#187],Top,Top,Object[#649]},{})
    same_frame(@263)
    at org.jetbrains.kotlin.jps.build.KotlinBuilderService.createModuleLevelBuilders(KotlinBuilderService.java:30)
    at org.jetbrains.jps.incremental.BuilderRegistry.<init>(BuilderRegistry.java:54)
    at org.jetbrains.jps.incremental.BuilderRegistry.<init>(BuilderRegistry.java:33)
    at org.jetbrains.jps.incremental.BuilderRegistry$Holder.<clinit>(BuilderRegistry.java:36)
    at org.jetbrains.jps.incremental.BuilderRegistry.getInstance(BuilderRegistry.java:43)
    at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:133)
    at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:295)
    at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:125)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:236)
    at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$$Lambda$3/1147174008.run(Unknown Source)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42)
    at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$$Lambda$1/684874119.run(Unknown Source)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)