问:
Color regions in a D3 map based on external data
I am trying to make a map in D3 of the 12 provinces of the Netherlands and color them based on some mock data in an external JSON file:

```<code>[{"_id":"Groningen","value":52},
{"_id":"Friesland","value":18},
{"_id":"Drenthe","value":87},
{"_id":"Overijssel","value":93},
{"_id":"Flevoland","value":60},
{"_id":"Gelderland","value":7},
{"_id":"Utrecht","value":26},
{"_id":"Noord-Holland","value":52},
{"_id":"Zuid-Holland","value":72},
{"_id":"Zeeland","value":41},
{"_id":"Noord-Brabant","value":78},
{"_id":"Limburg","value":19}]
</code>```

This is the code I have thus far. It successfully generates them map but right now colors each province as a function of the length of the province name (which is silly ofcourse):

```<code>var width = 960,
height = 500,
centered;

// Define color scale
var color = d3.scaleLinear()
   .domain([1, 20])
   .clamp(true)
   .range(['steelblue', "yellow"]);

var projection = d3.geoMercator()
   .scale(5500)
   .center([6, 52.1])
   .translate([width / 2, height / 2]);

var path = d3.geoPath()
   .projection(projection);

// Set svg width & height
var svg = d3.select('svg')
    .attr('width', width)
    .attr('height', height);

// Add background
svg.append('rect')
   .attr('class', 'background')
   .attr('width', width)
   .attr('height', height)

var g = svg.append('g');

var effectLayer = g.append('g')
   .classed('effect-layer', true);

var mapLayer = g.append('g')
   .classed('map-layer', true);

// Load map data
d3.json('data/provincesNL2.json', function(error, mapData) {
    var features = mapData.features;

    // Draw each province as a path
    mapLayer.selectAll('path')
      .data(features)
      .enter().append('path')
      .attr('d', path)
      .attr('vector-effect', 'non-scaling-stroke')
      .attr('fill', fillFn)
});

// Get province name
function nameFn(d){
   return d && d.properties ? d.properties.PROVINCIE : null;
}

// Get province name length
function nameLength(d){
   var n = nameFn(d);
   return n ? n.length : 0;
}

// Get province color
function fillFn(d){
   return color(nameLength(d));
};
</code>```

I just do not know how to implement the values from the JSON file to represent the color of each province along the color scale. I am not to experienced with javascript and I thought this shouldnt be too hard but I just can not figure it out. Many thanks for any help!

答:
You should specify the domain for you colour scale using min and max value of your data object.

```<code>var colour = d3.scaleLinear()
  .domain([
    d3.min(dataObject, function(d) { return d.value }),
    d3.max(dataObject, function(d) { return d.value })
  ])
  .clamp(true)
  .range(['steelblue', "yellow"]);
</code>```

In the callback function for fill attribute, you should find (you can do it various ways, depend on data structure) the value for current provinces and pass it to colour function.

```<code>.attr("fill", function(d, i) {
  var value = // here you should get for current data item ;

  return colour(value); // use this value for colour scale
})
</code>```

Check this example for Netherlands map (I modified your data a bit, to simplify the example and hardcoded topojson object).

Body:
I am trying to make a map in D3 of the 12 provinces of the Netherlands and color them based on some mock data in an external JSON file:

[{"_id":"Groningen","value":52},
{"_id":"Friesland","value":18},
{"_id":"Drenthe","value":87},
{"_id":"Overijssel","value":93},
{"_id":"Flevoland","value":60},
{"_id":"Gelderland","value":7},
{"_id":"Utrecht","value":26},
{"_id":"Noord-Holland","value":52},
{"_id":"Zuid-Holland","value":72},
{"_id":"Zeeland","value":41},
{"_id":"Noord-Brabant","value":78},
{"_id":"Limburg","value":19}]

This is the code I have thus far. It successfully generates them map but right now colors each province as a function of the length of the province name (which is silly ofcourse):

var width = 960,
height = 500,
centered;

// Define color scale
var color = d3.scaleLinear()
   .domain([1, 20])
   .clamp(true)
   .range(['steelblue', "yellow"]);

var projection = d3.geoMercator()
   .scale(5500)
   .center([6, 52.1])
   .translate([width / 2, height / 2]);

var path = d3.geoPath()
   .projection(projection);

// Set svg width & height
var svg = d3.select('svg')
    .attr('width', width)
    .attr('height', height);

// Add background
svg.append('rect')
   .attr('class', 'background')
   .attr('width', width)
   .attr('height', height)

var g = svg.append('g');

var effectLayer = g.append('g')
   .classed('effect-layer', true);

var mapLayer = g.append('g')
   .classed('map-layer', true);

// Load map data
d3.json('data/provincesNL2.json', function(error, mapData) {
    var features = mapData.features;

    // Draw each province as a path
    mapLayer.selectAll('path')
      .data(features)
      .enter().append('path')
      .attr('d', path)
      .attr('vector-effect', 'non-scaling-stroke')
      .attr('fill', fillFn)
});

// Get province name
function nameFn(d){
   return d && d.properties ? d.properties.PROVINCIE : null;
}

// Get province name length
function nameLength(d){
   var n = nameFn(d);
   return n ? n.length : 0;
}

// Get province color
function fillFn(d){
   return color(nameLength(d));
};

I just do not know how to implement the values from the JSON file to represent the color of each province along the color scale. I am not to experienced with javascript and I thought this shouldnt be too hard but I just can not figure it out. Many thanks for any help!

Body:
You should specify the domain for you colour scale using min and max value of your data object.

var colour = d3.scaleLinear()
  .domain([
    d3.min(dataObject, function(d) { return d.value }),
    d3.max(dataObject, function(d) { return d.value })
  ])
  .clamp(true)
  .range(['steelblue', "yellow"]);

In the callback function for fill attribute, you should find (you can do it various ways, depend on data structure) the value for current provinces and pass it to colour function.

.attr("fill", function(d, i) {
  var value = // here you should get for current data item ;

  return colour(value); // use this value for colour scale
})

Check this example for Netherlands map (I modified your data a bit, to simplify the example and hardcoded topojson object).


来源: stackexchange

问:
Wordpress API V2 custom fields with custom post types
I'm trying to add my custom posts to the Wordpress API, which also have custom fields.

I can view the custom posts types on the API via, /wp-json/wp/v2/fruit.

But the custom fields aren't displaying, how do you add them to the API?

答:
Take a look at "Extending the REST API / Modifying Responses", and in particular at register_rest_field.

Check out this example:

```<code>add_action( 'rest_api_init', 'create_api_posts_meta_field' );

function create_api_posts_meta_field() {

    // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
    register_rest_field( 'post', 'post-meta-fields', array(
           'get_callback'    => 'get_post_meta_for_api',
           'schema'          => null,
        )
    );
}

function get_post_meta_for_api( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];

    //return the post meta
    return get_post_meta( $post_id );
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Take a look at "Extending the REST API / Modifying Responses", and in particular at register_rest_field.

Check out this example:

add_action( 'rest_api_init', 'create_api_posts_meta_field' );

function create_api_posts_meta_field() {

    // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
    register_rest_field( 'post', 'post-meta-fields', array(
           'get_callback'    => 'get_post_meta_for_api',
           'schema'          => null,
        )
    );
}

function get_post_meta_for_api( $object ) {
    //get the id of the post object array
    $post_id = $object['id'];

    //return the post meta
    return get_post_meta( $post_id );
}


问:
Apache Ignite: how to insert into table with IDENTITY key (SQL Server)
I have a table in SQL Server where the primary key is autogenerated (identity column), i.e.

```<code>CREATE TABLE TableName
(
     table_id INT NOT NULL IDENTITY (1,1),
     some_field VARCHAR(20),

     PRIMARY KEY (table_id)
);
</code>```

Since table_id is an autogenerated column, when I implemented the SqlFieldQuery INSERT clause I do not set any argument to table_id:

```<code>sql = new SqlFieldsQuery("INSERT INTO TableName (some_field) VALUES (?)");
cache.query(sql.setArgs("str");
</code>```

However at runtime I get the following error:

Exception in thread "main" javax.cache.CacheException: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to execute DML statement [stmt=INSERT INTO TableName (some_field) VALUES (?), params=["str"]]

at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:807)

  at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:765)

  ...

  Caused by: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to execute DML statement [stmt=INSERT INTO TableName (some_field) VALUES (?), params=["str"]]

at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1324)

  at org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1815)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1813)
          at org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:2293)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor.querySqlFields(GridQueryProcessor.java:1820)
          at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:795)
          ... 5 more
      Caused by: class org.apache.ignite.IgniteCheckedException: Key is missing from query
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.createSupplier(UpdatePlanBuilder.java:331)
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.planForInsert(UpdatePlanBuilder.java:196)
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.planForStatement(UpdatePlanBuilder.java:82)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.getPlanForStatement(DmlStatementsProcessor.java:438)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.updateSqlFields(DmlStatementsProcessor.java:164)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.updateSqlFieldsDistributed(DmlStatementsProcessor.java:222)
          at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1321)
          ... 11 more

This is how I planned to implement the insertion because it seemed more tedious to get the max table_id from the cache, increment and insert. I thought I could omit the table_id from the insert and let SQL Server insert the pk, but it doesn't seem to work like this.

Can you please tell me how this should typically be implemented in Ignite? I checked the ignite-examples, unfortunately the examples are too simple (i.e. fixed keys only, like 1 or 2).

Moreover, how does Ignite support the use of sequences?

I am using ignite-core 2.2.0. Any help is appreciated! Thank you.

答:
Ignite doesn't support identity columns [1] yet.

It may be non-obviuos, but Ignite SQL layer is built on top of key value store which can be backed by other CacheStore. Your SQL query will never go though to CacheStore as is.

Ignite internals will execute your query, save data in cache and only then update will be propagated to CacheStore which will create a new SQL query for your SQL server.

So, Ignite need the identity column value (actually a key) be known before data saved in cache.

[1] https://issues.apache.org/jira/browse/IGNITE-5625

Body:
I have a table in SQL Server where the primary key is autogenerated (identity column), i.e.

CREATE TABLE TableName
(
     table_id INT NOT NULL IDENTITY (1,1),
     some_field VARCHAR(20),

     PRIMARY KEY (table_id)
);

Since table_id is an autogenerated column, when I implemented the SqlFieldQuery INSERT clause I do not set any argument to table_id:

sql = new SqlFieldsQuery("INSERT INTO TableName (some_field) VALUES (?)");
cache.query(sql.setArgs("str");

However at runtime I get the following error:

Exception in thread "main" javax.cache.CacheException: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to execute DML statement [stmt=INSERT INTO TableName (some_field) VALUES (?), params=["str"]]

at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:807)

  at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:765)

  ...

  Caused by: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to execute DML statement [stmt=INSERT INTO TableName (some_field) VALUES (?), params=["str"]]

at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1324)

  at org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1815)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1813)
          at org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:2293)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor.querySqlFields(GridQueryProcessor.java:1820)
          at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:795)
          ... 5 more
      Caused by: class org.apache.ignite.IgniteCheckedException: Key is missing from query
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.createSupplier(UpdatePlanBuilder.java:331)
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.planForInsert(UpdatePlanBuilder.java:196)
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.planForStatement(UpdatePlanBuilder.java:82)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.getPlanForStatement(DmlStatementsProcessor.java:438)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.updateSqlFields(DmlStatementsProcessor.java:164)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.updateSqlFieldsDistributed(DmlStatementsProcessor.java:222)
          at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1321)
          ... 11 more

This is how I planned to implement the insertion because it seemed more tedious to get the max table_id from the cache, increment and insert. I thought I could omit the table_id from the insert and let SQL Server insert the pk, but it doesn't seem to work like this.

Can you please tell me how this should typically be implemented in Ignite? I checked the ignite-examples, unfortunately the examples are too simple (i.e. fixed keys only, like 1 or 2).

Moreover, how does Ignite support the use of sequences?

I am using ignite-core 2.2.0. Any help is appreciated! Thank you.


问:
Using greater than with Lo Dash
How do I filter an array using greater and less than with Lo Dash?

Using Lo Dash's _.find demo data:

```<code> var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];
</code>```

I would like to find all users over 30.

var over30 = _.find(users, function(o) { return o.age > 30; });

However this returns the first user, Barney, instead of Barney and Fred.

I've tried different combinations of the following.

```<code>_.find(users, ['age', > 30]);
</code>```

答:
You can use filter() method instead. filter  will return all elements that pass the condition while find will exit the loop and return the first element that returns true on condition.

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

var over30 = _.filter(users, ({age}) => age > 30)
console.log(over30)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Title: Using greater than with Lo Dash

Body:
How do I filter an array using greater and less than with Lo Dash?

Using Lo Dash's _.find demo data:

 var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

I would like to find all users over 30.

var over30 = _.find(users, function(o) { return o.age > 30; });

However this returns the first user, Barney, instead of Barney and Fred.

I've tried different combinations of the following.

_.find(users, ['age', > 30]);

Body:
You can use filter() method instead. filter  will return all elements that pass the condition while find will exit the loop and return the first element that returns true on condition.

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

var over30 = _.filter(users, ({age}) => age > 30)
console.log(over30)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


答:
From the DOC:

find, Iterates over elements of collection, returning the first
  element predicate returns truthy for.

find always returns the first element not all the element who satisfy the condition.

You need to use filter:

Iterates over elements of collection, returning an array of all
  elements predicate returns truthy for.

Write it like this:

```<code>var over30 = _.filter(users, function(o) { return o.age > 30; })
</code>```

Working snippet:

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

var over30 = _.filter(users, el => el.age > 30);

console.log('over30 = ', over30);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Title: Using greater than with Lo Dash

Body:
From the DOC:

find, Iterates over elements of collection, returning the first
  element predicate returns truthy for.

find always returns the first element not all the element who satisfy the condition.

You need to use filter:

Iterates over elements of collection, returning an array of all
  elements predicate returns truthy for.

Write it like this:

var over30 = _.filter(users, function(o) { return o.age > 30; })

Working snippet:

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

var over30 = _.filter(users, el => el.age > 30);

console.log('over30 = ', over30);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
draggable droppable with sortable
we trying to integrate multiple drggable and droppable. we are using sortable for ease of clone functionality in this scenario. draggable once dropped need to be draggable again.

how do we limit sortable to receive only one element and revert to original if more than one dropped onto it.

look like out and over functions of sortable are misbehaving in that case.

commented line code is for disabling dropping second element on sortable. which is not working as expected.

Two issues when you enable my commented code:

draggable clone not reverting to original place after moving out of droppable.

draggable element moved from one droppable to another reverting to draggable's original place.

For a demonstration, see this jsfiddle

script:

```<code>//  jQuery.noConflict();

jQuery( document ).ready(function() { init();});
function init() {

  var mouse_button = false;
  jQuery('.ui-draggable').live({
      mousedown: function () {
          mouse_button = true;
      },
      mouseup: function () {

          if (jQuery(this).attr('data-pos') == 'out' && jQuery(this).attr('data-id')) {
              var p = jQuery('#' + jQuery(this).attr('data-id'));
              var offset = p.offset();
              jQuery(this).hide();
              jQuery(this).animate({ left: offset.left, top: offset.top, width: jQuery(this).width, height: jQuery(this).height }, 100, function () {
                  jQuery(this).remove();
                  $( ".ui-droppable" ).each(function() {
                    if($(this).children().length == 0) {
                      $( this ).removeClass("dontDrop");
                    }
                  });
                  //if(p[0].hasAttribute("draggable"))
                  p.draggable("enable");

             //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
             //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));

              });
          }
          mouse_button = false;
      },
      mouseout: function () {
          if (mouse_button) {
              mouse_button = false;
          }
      }

  });

    jQuery( '.ui-draggable' ).draggable( {
      cursor: 'move',
      helper: 'clone',
      connectToSortable: ".ui-droppable",
      revert: function (event, ui) {
        }
    } );

    jQuery(".ui-droppable").sortable({
        cursor: "move",
        connectWith: ".ui-droppable",
        receive: function (event, ui) {

        if($(this).children().length >= 1) {

            $(this).children().addClass('filled');
            $(this).addClass('dontDrop');

            $( ".ui-droppable" ).each(function() {
              if($(this).children().length == 0) {
                $( this ).removeClass("dontDrop");
              }
            });
       //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
       //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));
        }else {
            $(this).children().removeClass('filled');
        }
        if (jQuery(this).data().sortable.currentItem) {
                jQuery(this).data().sortable.currentItem.attr('data-id', jQuery(ui.item).attr("id"));
               // if(jQuery(ui.item)[0].hasAttribute("draggable"))
                jQuery(ui.item).draggable("disable");
            }

        },
        out: function (event, ui) {  if (ui.helper) { ui.helper.attr('data-pos', 'out'); } },
        over: function (event, ui) { ui.helper.attr('data-pos', 'in'); }
    });

  }
</code>```

答:
Here's a working example: click here

You can user Jquery's draggable and droppable interactions to achieve what you want. Check the working example.

```<code>$(document).ready(function () {

  $(".ui-draggable").draggable(draggable_options) //make cards draggable

  $(".ui-droppable").droppable({ //handle card drops
    greedy: true,
    drop: function (event, ui) {
      handleDrop(this, event, ui)
    },
    accept: function () {
      return checkIfShouldAcceptTheDraggable(this)
    }
  })
})
</code>```

Title: draggable droppable with sortable

Body:
we trying to integrate multiple drggable and droppable. we are using sortable for ease of clone functionality in this scenario. draggable once dropped need to be draggable again.

how do we limit sortable to receive only one element and revert to original if more than one dropped onto it.

look like out and over functions of sortable are misbehaving in that case.

commented line code is for disabling dropping second element on sortable. which is not working as expected.

Two issues when you enable my commented code:

draggable clone not reverting to original place after moving out of droppable.

draggable element moved from one droppable to another reverting to draggable's original place.

For a demonstration, see this jsfiddle

script:

//  jQuery.noConflict();

jQuery( document ).ready(function() { init();});
function init() {

  var mouse_button = false;
  jQuery('.ui-draggable').live({
      mousedown: function () {
          mouse_button = true;
      },
      mouseup: function () {

          if (jQuery(this).attr('data-pos') == 'out' && jQuery(this).attr('data-id')) {
              var p = jQuery('#' + jQuery(this).attr('data-id'));
              var offset = p.offset();
              jQuery(this).hide();
              jQuery(this).animate({ left: offset.left, top: offset.top, width: jQuery(this).width, height: jQuery(this).height }, 100, function () {
                  jQuery(this).remove();
                  $( ".ui-droppable" ).each(function() {
                    if($(this).children().length == 0) {
                      $( this ).removeClass("dontDrop");
                    }
                  });
                  //if(p[0].hasAttribute("draggable"))
                  p.draggable("enable");

             //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
             //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));

              });
          }
          mouse_button = false;
      },
      mouseout: function () {
          if (mouse_button) {
              mouse_button = false;
          }
      }

  });

    jQuery( '.ui-draggable' ).draggable( {
      cursor: 'move',
      helper: 'clone',
      connectToSortable: ".ui-droppable",
      revert: function (event, ui) {
        }
    } );

    jQuery(".ui-droppable").sortable({
        cursor: "move",
        connectWith: ".ui-droppable",
        receive: function (event, ui) {

        if($(this).children().length >= 1) {

            $(this).children().addClass('filled');
            $(this).addClass('dontDrop');

            $( ".ui-droppable" ).each(function() {
              if($(this).children().length == 0) {
                $( this ).removeClass("dontDrop");
              }
            });
       //     $('.ui-droppable').sortable('option', 'connectWith',$('.ui-droppable').not('.dontDrop'));
       //     $('.ui-draggable').draggable('option', 'connectToSortable',$('.ui-droppable').not('.dontDrop'));
        }else {
            $(this).children().removeClass('filled');
        }
        if (jQuery(this).data().sortable.currentItem) {
                jQuery(this).data().sortable.currentItem.attr('data-id', jQuery(ui.item).attr("id"));
               // if(jQuery(ui.item)[0].hasAttribute("draggable"))
                jQuery(ui.item).draggable("disable");
            }

        },
        out: function (event, ui) {  if (ui.helper) { ui.helper.attr('data-pos', 'out'); } },
        over: function (event, ui) { ui.helper.attr('data-pos', 'in'); }
    });

  }

Body:
Here's a working example: click here

You can user Jquery's draggable and droppable interactions to achieve what you want. Check the working example.

$(document).ready(function () {

  $(".ui-draggable").draggable(draggable_options) //make cards draggable

  $(".ui-droppable").droppable({ //handle card drops
    greedy: true,
    drop: function (event, ui) {
      handleDrop(this, event, ui)
    },
    accept: function () {
      return checkIfShouldAcceptTheDraggable(this)
    }
  })
})


问:
Clicking A Link Two Times
I have a link like this :

```<code><a href="#" onclick="renkDegistir()" title="Yaz .......
</code>```

And JS code :

```<code>function renkDegistir()
    {
        $("#cont #main article").addClass("siyah-stil");
    }
</code>```

When click this link siyah-stil class is added to article. But i want to do, if link clicked 2nd time remove siyah-stil class.

In summary ,

```<code>on first click : addClass("siyah-stil");
on second click : removeClass("siyah-stil");
</code>```

答:
Try using toggleClass():

```<code>function renkDegistir()
{
    $("#cont #main article").toggleClass("siyah-stil");
}
</code>```

But I'd suggest also removing the in-line onclick attribute, and switching to jQuery's click() event-handler:

```<code>$('a').click(
    function(){
        $("#cont #main article").toggleClass("siyah-stil");
    });
</code>```

Edited to address @Eray's comment (below):

Can you explain [to] me , why jQuery's click() function [is] better than in-line onclick attribute?

The reason I prefer to use non-inline code is that it reduces the complexity of changing the onClick events; since they get changed in one place, rather than having to change the onclick attribute in every a (or other) element. Admittedly, you could achieve that benefit by simply changing the renkDegistir() function, but then you end up with functions named for posterity, rather than the inherent nature of the function.

It also makes it easier for others to take over, and adapt your code, and to iron out bugs when they appear.

ContentLicense: CC BY-SA 2.5

Title: Clicking A Link Two Times

Body:
I have a link like this :

<a href="#" onclick="renkDegistir()" title="Yaz .......

And JS code :

function renkDegistir()
    {
        $("#cont #main article").addClass("siyah-stil");
    }

When click this link siyah-stil class is added to article. But i want to do, if link clicked 2nd time remove siyah-stil class.

In summary ,

on first click : addClass("siyah-stil");
on second click : removeClass("siyah-stil");

Body:
Try using toggleClass():

function renkDegistir()
{
    $("#cont #main article").toggleClass("siyah-stil");
}

But I'd suggest also removing the in-line onclick attribute, and switching to jQuery's click() event-handler:

$('a').click(
    function(){
        $("#cont #main article").toggleClass("siyah-stil");
    });

Edited to address @Eray's comment (below):

Can you explain [to] me , why jQuery's click() function [is] better than in-line onclick attribute?

The reason I prefer to use non-inline code is that it reduces the complexity of changing the onClick events; since they get changed in one place, rather than having to change the onclick attribute in every a (or other) element. Admittedly, you could achieve that benefit by simply changing the renkDegistir() function, but then you end up with functions named for posterity, rather than the inherent nature of the function.

It also makes it easier for others to take over, and adapt your code, and to iron out bugs when they appear.


问:
Exit if no active profile is set
How can I exit from the application before any action is performed (especially bean creation) if there is no active profile?

I've done this with such configuration:

```<code>@Profile("default")
@Configuration
public class NoActiveProfileKiller {
    public NoActiveProfileKiller() {
        throw new UnsupportedOperationException("No active profile is selected");
    }
}
</code>```

But this performs JPA actions at least.

答:
I would do something like:</p>

```<code>    public static void main(String[] args) {
        final SpringApplication app = new SpringApplication(App.class);
        final SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
        // check if spring profile is set from outside.
        if (!source.containsProperty("spring.profiles.active") &&
            !System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
            System.err.println("No Profile set, exiting");
            System.exit(0);
        }
    }
</code>```

Title: Exit if no active profile is set

Body:
How can I exit from the application before any action is performed (especially bean creation) if there is no active profile?

I've done this with such configuration:

@Profile("default")
@Configuration
public class NoActiveProfileKiller {
    public NoActiveProfileKiller() {
        throw new UnsupportedOperationException("No active profile is selected");
    }
}

But this performs JPA actions at least.

Body:
I would do something like:

    public static void main(String[] args) {
        final SpringApplication app = new SpringApplication(App.class);
        final SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
        // check if spring profile is set from outside.
        if (!source.containsProperty("spring.profiles.active") &&
            !System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
            System.err.println("No Profile set, exiting");
            System.exit(0);
        }
    }


问:
App specific filters in Tomcat
I have two applications running on different ports of my Tomcat. I have added a filter in my web.xml. This filter class exists in only one of the two applications code/war file. When I start the tomcat, I get <code> java.lang.ClassNotFoundException: com.abc.filter.MyFilter </code>
The result is, application which has filter class runs fine, but other one does not start. My question is : Is there any way to specify application specific filters in Tomcat web.xml so we can load the applications which do not have a particular filter class?
Thanks.</p>

答: Yes, you can setup app specific configurations by adding a web.xml file in the application's WEB-INF folder instead of setting up global configurations by modifying the XMLs in Tomcat's conf folder

Title: App specific filters in Tomcat

Body:
I have two applications running on different ports of my Tomcat. I have added a filter in my web.xml. This filter class exists in only one of the two applications code/war file. When I start the tomcat, I get  java.lang.ClassNotFoundException: com.abc.filter.MyFilter
The result is, application which has filter class runs fine, but other one does not start. My question is : Is there any way to specify application specific filters in Tomcat web.xml so we can load the applications which do not have a particular filter class?
Thanks.


问:
Python picture grid in loop
I encountered a problem as I tried to fill a tkinter grid with a loop

```<code>i=0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    imageLabel.grid(row=0, column=i)
    i = i + 1
</code>```

With this code I try to create a row with different pictures side by side.
But it shows only the last image which is in the categories array (this array was filled by a SQL-execute btw).

After a few researches I found out, that it seems that python overwrites the reference of the picture on each iteration.

So I tried to change the code and save the references in a array:

```<code>folderPictures = []
i = 0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    folderPictures.append(imageLabel)

for pictures in folderPictures:
        pictures.grid(row=0, column=i)
        i = +1
</code>```

unfortunately this doesn't work either. What do I do wrong?

Thanks and best regards
Franz

答: Instead of overwriting self.image each time, keep a separate reference for each image. For instance, you could make self.image into an array (self.images[0,1,...]) and keep each image in a different slot.</p>

Title: Python picture grid in loop

Body:
I encountered a problem as I tried to fill a tkinter grid with a loop

i=0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    imageLabel.grid(row=0, column=i)
    i = i + 1

With this code I try to create a row with different pictures side by side.
But it shows only the last image which is in the categories array (this array was filled by a SQL-execute btw).

After a few researches I found out, that it seems that python overwrites the reference of the picture on each iteration.

So I tried to change the code and save the references in a array:

folderPictures = []
i = 0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    folderPictures.append(imageLabel)

for pictures in folderPictures:
        pictures.grid(row=0, column=i)
        i = +1

unfortunately this doesn't work either. What do I do wrong?

Thanks and best regards
Franz


问:
How to remove/delete last character from printed list in python
I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

```<code>num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1
</code>```

Result I got:

```<code>24=2*2*2*3*
</code>```

Result I want:

```<code>24=2*2*2*3
</code>```

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong.
Thank you.

答:
```<code>import sys
sys.stdout.write('\b \b') ##at the end of the program
</code>```

result:

```<code>write number: 24
24=2*2*2*3
</code>```

Body:
I am creating simple program which finds the smallest multiplicators of a number (not sure if this is the right term). However, I can not find a way to delete last "*" from the listed result. What am I doing wrong? Please help.

num = int(input("write number: "))
print(num, end = "=")
div = 2
while num > 1:
    if num % div == 0:
        num = num / div
        print(div, end = "*")
    else:
        div += 1

Result I got:

24=2*2*2*3*

Result I want:

24=2*2*2*3

I tried to use sep="" instead of end="", tried \b, [:-1] but this does not work or I am just doing it wrong.
Thank you.

Body:
import sys
sys.stdout.write('\b \b') ##at the end of the program

result:

write number: 24
24=2*2*2*3


问:
Loop through elements with matching data attribute values
I have the following setup:

    $( document ).on( 'click touch', '.target', function() {
        if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
           alert('do stuff');
        }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
</div></code>```

Whenever user clicks on .target element, I want to do stuff to all divs within the closest .list. So if user clicks on .target with post-id data value 1,  it should so something to all others with the same data attribute value...

How do I do this type of loop with jQuery?

答:
Just grab the ID and then find the rest - no need for each:

$(document).on('click touch', '.target', function() {
  var id = $(this).data("post-id"), $list=$(this).closest(".list");
  $list.find(".target").removeClass("red") // reset in list
  $list.find(".target[data-post-id=" + id + "]").addClass("red"); // set same IDs
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
  color: red
}</code>```

a

b

a

a

b

```

Body:
I have the following setup:

    $( document ).on( 'click touch', '.target', function() {
        if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
           alert('do stuff');
        }
    });

a

b

a

a

b

Whenever user clicks on .target element, I want to do stuff to all divs within the closest .list. So if user clicks on .target with post-id data value 1,  it should so something to all others with the same data attribute value...

How do I do this type of loop with jQuery?

Body:
Just grab the ID and then find the rest - no need for each:

$(document).on('click touch', '.target', function() {
  var id = $(this).data("post-id"), $list=$(this).closest(".list");
  $list.find(".target").removeClass("red") // reset in list
  $list.find(".target[data-post-id=" + id + "]").addClass("red"); // set same IDs
});

.red {
  color: red
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
  <div>
    <div class="target" data-post-id="1">a</div>
  </div>
  <div>
    <div class="target" data-post-id="2">b</div>
  </div>
  <div>
    <div class="target" data-post-id="1">a</div>
  </div>
  <div>
    <div class="target" data-post-id="1">a</div>
  </div>
  <div>
    <div class="target" data-post-id="2">b</div>
  </div>
</div>


问:
JAVA: Reading nextLine from file excluding all whitespace
I'm currently stumped to how I can read from a text file whilst removing all whitespace.  I have tried using the delimiter and string split to find no success.  The problem is: my task requires me to read several lines of text from a text file and store it in an array.

However one of the lines has a visible 'gap' or several whitespaces (denoted by the speech marks here) which I assume is causing me problems.

Here is a sample of the text file:

```<code>jy1 10 10 10 10 10

mp1 6 5 6 " " 7 5

ls1 9 7 12 14 15

mp2 10 12 15 15 14

lb1 12 12 12 12 12
</code>```

And here is my code:

```<code>try {
    FileReader reader= new FileReader(attendancesFile.txt);
    String line="";
    Scanner in=new Scanner(reader);

// reading from file line by line
    while (in.hasNextLine())    {
        line=in.nextLine();
        // splitting line read in separate words
        String tokens[]=line.split(" ");

        // creates an array of attendances
        // using 5 separate attendances represented as integer values from file
        String id= tokens [0];
        int attend1= Integer.parseInt(tokens [1]);
        int attend2= Integer.parseInt(tokens [2]);
        int attend3= Integer.parseInt(tokens [3]);
        int attend4= Integer.parseInt(tokens [4]);
        int attend5= Integer.parseInt(tokens [5]);
        int [] attend= {attend1, attend2, attend3, attend4, attend5};

        // uses FP method to find Fitness Class with given ID
        // sets the attendance for Fitness Class with given ID
        fp.classByID(id).setAttendance(attend);
    }
    reader.close();
    in.close();
}
catch (IOException e)   {
    System.err.println("Reading from file error.");
}
</code>```

Ideally I should have 5 arrays, each of which stores the 5 integer numbers from each line of the file. I will then pass these arrays to another class where a method adds this array of int to an object array.

However, it gives me an error: Exception in thread "main" java.lang.NumberFormatException: For input string: "" which I assume is due to the white space being read and added to the array. I have tested to print out each array & it appears as though the fourth array only has 4 elements & a blank space.

答:
```<code>String tokens[]=line.split(" ");
</code>```

This only seperates on a single white space.
Change it to

```<code>String tokens[]=line.split("\\s+");
</code>```

This is any amount of whitespace

This is a useful guideline for different regex pattern composites.

\\s - matches single whitespace character

\\s+ - matches sequence of one or more whitespace characters.

Body:
I'm currently stumped to how I can read from a text file whilst removing all whitespace.  I have tried using the delimiter and string split to find no success.  The problem is: my task requires me to read several lines of text from a text file and store it in an array.

However one of the lines has a visible 'gap' or several whitespaces (denoted by the speech marks here) which I assume is causing me problems.

Here is a sample of the text file:

jy1 10 10 10 10 10

mp1 6 5 6 " " 7 5

ls1 9 7 12 14 15

mp2 10 12 15 15 14

lb1 12 12 12 12 12

And here is my code:

try {
    FileReader reader= new FileReader(attendancesFile.txt);
    String line="";
    Scanner in=new Scanner(reader);

// reading from file line by line
    while (in.hasNextLine())    {
        line=in.nextLine();
        // splitting line read in separate words
        String tokens[]=line.split(" ");

        // creates an array of attendances
        // using 5 separate attendances represented as integer values from file
        String id= tokens [0];
        int attend1= Integer.parseInt(tokens [1]);
        int attend2= Integer.parseInt(tokens [2]);
        int attend3= Integer.parseInt(tokens [3]);
        int attend4= Integer.parseInt(tokens [4]);
        int attend5= Integer.parseInt(tokens [5]);
        int [] attend= {attend1, attend2, attend3, attend4, attend5};

        // uses FP method to find Fitness Class with given ID
        // sets the attendance for Fitness Class with given ID
        fp.classByID(id).setAttendance(attend);
    }
    reader.close();
    in.close();
}
catch (IOException e)   {
    System.err.println("Reading from file error.");
}

Ideally I should have 5 arrays, each of which stores the 5 integer numbers from each line of the file. I will then pass these arrays to another class where a method adds this array of int to an object array.

However, it gives me an error: Exception in thread "main" java.lang.NumberFormatException: For input string: "" which I assume is due to the white space being read and added to the array. I have tested to print out each array & it appears as though the fourth array only has 4 elements & a blank space.

Body:
String tokens[]=line.split(" ");

This only seperates on a single white space.
Change it to

String tokens[]=line.split("\\s+");

This is any amount of whitespace

This is a useful guideline for different regex pattern composites.

\\s - matches single whitespace character

\\s+ - matches sequence of one or more whitespace characters.


问:
Include after Union method not working (Entity Framework Core 2)
I have this simple code, using EF Core 2.

I perform 2 subqueries and the result is the Union of them. The problem is that the Include method in after the Union doesn't load the navigation properties (Role is always null).

```<code>public static void Main()
{
     using (var context = new MyDbContext())
     {
         IQueryable<User> a = SomeQuery(context);
         IQueryable<User> b = SomeOtherQuery(context);

         var union = a.Union(b);
         var resultingList = union.Include(x => x.Role); // Include doesn't work
     }
}
</code>```

What should I do to effectively load navigation properties after composing with the Union method?

NOTE: The problem also happens with the Concat method.

答:
You are accessing the IQueryable out of the context of the MyDbContext object. There is no db connection at that time. Make sure you do all db access withing the context of the MyDbContext (using scope):</p>

```<code> public IEnumarable<User> GetItems()
 {
   IEnumarable<User> resultingList;
   using (var context = new MyDbContext())
   {
     IQueryable<User> a = SomeQuery(context);
     IQueryable<User> b = SomeOtherQuery(context);

     var union = a.Union(b);
     resultingList = union.Include(x => x.Role).ToList();
   }
   return resultingList;
 }
</code>```

Body:
I have this simple code, using EF Core 2.

I perform 2 subqueries and the result is the Union of them. The problem is that the Include method in after the Union doesn't load the navigation properties (Role is always null).

public static void Main()
{
     using (var context = new MyDbContext())
     {
         IQueryable<User> a = SomeQuery(context);
         IQueryable<User> b = SomeOtherQuery(context);

         var union = a.Union(b);
         var resultingList = union.Include(x => x.Role); // Include doesn't work
     }
}

What should I do to effectively load navigation properties after composing with the Union method?

NOTE: The problem also happens with the Concat method.

Body:
You are accessing the IQueryable out of the context of the MyDbContext object. There is no db connection at that time. Make sure you do all db access withing the context of the MyDbContext (using scope):

 public IEnumarable<User> GetItems()
 {
   IEnumarable<User> resultingList;
   using (var context = new MyDbContext())
   {
     IQueryable<User> a = SomeQuery(context);
     IQueryable<User> b = SomeOtherQuery(context);

     var union = a.Union(b);
     resultingList = union.Include(x => x.Role).ToList();
   }
   return resultingList;
 }


问:
jquery ajax while loop in odd order
I cant understand what I'm doing wrong on this one. I've got a while loop running an AJAX function to get data from a PHP file for the amount of people selected from a dropdown.

$(document).on('change', '#attendingCount', function() {
  $(".person-container").html("");
  var amount = $(this).val();
  var i = 0;

  while (i < amount) {
    getPerson(i);
    i++;
  }
});

getPerson(0);

function getPerson(e) {
  $.ajax({
    type: 'post',
    url: './person.php',
    data: {
      "amount": e
    },
    success: function(data) {
      $(".person-container").append(data);
    },
    error: function() {
      console.log('error');
    }
  });
}
```

When the result gets pumped out though, the order of them is completely random.
What is it exactly I'm doing wrong?!

答: AJAX works in an asynchronous way, not necessarily the first request you send is going to return data first, that's the problem here. Doing an AJAX call in a while loop is not the best solution.</p>

Title: jquery ajax while loop in odd order

Body:
I cant understand what I'm doing wrong on this one. I've got a while loop running an AJAX function to get data from a PHP file for the amount of people selected from a dropdown.

$(document).on('change', '#attendingCount', function() {
  $(".person-container").html("");
  var amount = $(this).val();
  var i = 0;

  while (i < amount) {
    getPerson(i);
    i++;
  }
});

getPerson(0);

function getPerson(e) {
  $.ajax({
    type: 'post',
    url: './person.php',
    data: {
      "amount": e
    },
    success: function(data) {
      $(".person-container").append(data);
    },
    error: function() {
      console.log('error');
    }
  });
}

When the result gets pumped out though, the order of them is completely random.
What is it exactly I'm doing wrong?!


问:
How do I create an empty vector of dates?
Is it possible to create an empty vector of dates in r?

I can create an empty vector of integers, doubles, logicals etc:

```<code>> integer()
integer(0)
> double()
numeric(0)
> logical()
logical(0)
> length(integer())
[1] 0
</code>```

but this meme doesn't work for dates, as date() returns the current system date and time. So, how would I create an emtpy vector of dates?

答:
Using the lubridate package and deciding what your intended format will be (eg. yyyy/mm/dd) you can use:

```<code>lubridate::ymd()
# or
lubridate::mdy()
</code>```

etc.

Body:
Is it possible to create an empty vector of dates in r?

I can create an empty vector of integers, doubles, logicals etc:

> integer()
integer(0)
> double()
numeric(0)
> logical()
logical(0)
> length(integer())
[1] 0

but this meme doesn't work for dates, as date() returns the current system date and time. So, how would I create an emtpy vector of dates?

Body:
Using the lubridate package and deciding what your intended format will be (eg. yyyy/mm/dd) you can use:

lubridate::ymd()
# or
lubridate::mdy()

etc.


问:
Understanding Hibernate Fetch
I know hibernate has lazy as default fetching strategy, but there are some things unclear to me so i hope you can explain it to me. What i want to do is to get a tile marked as start tile.

Query:

```<code>@NamedQuery(name = "Tile.findStartTileByGame",
  query = "SELECT t FROM Tile t WHERE t.game = :game " +
    "and t.startTile = true and t.blockWalkable = false")
</code>```

Tile:

```<code> public class Tile{

 @OneToOne(mappedBy="tile")
 private GameCharacter character;

 @OneToOne(mappedBy="tile")
 private GameObject gameObject;
</code>```

Game:

```<code> @OneToMany(mappedBy="game")
 private List<Tile> tiles;
</code>```

When i run my query and never use the object hibernate still joins me character and gameobject. So i have 3 Queries. I know i can solve this by a fetch join, but my question is why does hibernate fetch both entites at all? Even when i annotate them with fetch=FetchType.LAZY it will be queried.

My DAO:

```<code>  public static Tile getFreeStartTile(EntityManager em, Game game) {
   TypedQuery<Tile> query = em.createNamedQuery("Tile.findStartTileByGame", Tile.class);
   query.setParameter("game", game);
  List<Tile> result = query.getResultList();
  ...
</code>```

Before i fix this i would like to understand why it happens.
Thanks in advance
m

答:
The reason it happens is that they're marked nullable.  When proxying is used, Hibernate still needs to know the difference between ones to proxy and ones that are actually just plain null.

When the relationship is a collection, it can give you an empty collection then check later.  But when it's OneToOne, it has to look in the DB anyway to find out if the field should be null, or if it could be proxied and lazy loaded.  Since it has to look anyway, it just loads it.

If you mark both fetch=FetchType.LAZY and optional=false you can get lazy fetching on onetoone.  Of course if the column actual is nullable, you're SOL.

Title: Understanding Hibernate Fetch

Body:
I know hibernate has lazy as default fetching strategy, but there are some things unclear to me so i hope you can explain it to me. What i want to do is to get a tile marked as start tile.

Query:

@NamedQuery(name = "Tile.findStartTileByGame",
  query = "SELECT t FROM Tile t WHERE t.game = :game " +
    "and t.startTile = true and t.blockWalkable = false")

Tile:

 public class Tile{

 @OneToOne(mappedBy="tile")
 private GameCharacter character;

 @OneToOne(mappedBy="tile")
 private GameObject gameObject;

Game:

 @OneToMany(mappedBy="game")
 private List<Tile> tiles;

When i run my query and never use the object hibernate still joins me character and gameobject. So i have 3 Queries. I know i can solve this by a fetch join, but my question is why does hibernate fetch both entites at all? Even when i annotate them with fetch=FetchType.LAZY it will be queried.

My DAO:

  public static Tile getFreeStartTile(EntityManager em, Game game) {
   TypedQuery<Tile> query = em.createNamedQuery("Tile.findStartTileByGame", Tile.class);
   query.setParameter("game", game);
  List<Tile> result = query.getResultList();
  ...

Before i fix this i would like to understand why it happens.
Thanks in advance
m


问:
Displaying and Uploading Image with php and mysqli
I am trying to display images that I have uploaded to my MySQL database.
The uploading process is working properly, but I have issues in displaying from it and I don't know where I am going wrong.

This is my DB:

```<code> CREATE TABLE `data` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `dozent` varchar(32) NOT NULL DEFAULT '',
  `datum` date NOT NULL,
  `text` text NOT NULL,
  `Ort` varchar(45) NOT NULL DEFAULT '',
  `gastvortraege` varchar(30) NOT NULL DEFAULT '',
  `src` blob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
</code>```

The data I upload is inserted with this code:

```<code>require("vortraege_db.php");

$stmt = $con->stmt_init();

$name = mysqli_real_escape_string($con,$_POST['name']);
$title = mysqli_real_escape_string($con,$_POST['titel']);
$text = mysqli_real_escape_string($con,$_POST['text']);
$ort = mysqli_real_escape_string($con,$_POST ['ort']);
$date = mysqli_real_escape_string($con,$_POST['datum']);

$path = $_FILES['image']['tmp_name'];

if(isset($_POST['gast']))
    $uniname = mysqli_real_escape_string($con,$_POST['gast_text']);
else {
    $uniname = mysqli_real_escape_string($con,'');
}

$image = file_get_contents($path);
$image = mysqli_real_escape_string($con, $image);

$stmt->prepare("INSERT INTO data(dozent,datum,`text`,Ort,gastvortraege,src) VALUES(?,?,?,?,?,?)");
$stmt->bind_param('sssssb',$name,$date,$text,$ort,$uniname,$image);
$result = $stmt->execute();

if($result)
    echo "Datensätze erfolgreich hochgeladen";
else {
    echo "Es ist irgendwas schiefgelaufen, bitte erneut versuchen.";
}
</code>```

Just for testing purpose I used many code snippets I found on stackoverflow, that was the latest one:

```<code>$sql = "SELECT * FROM  `data`";
$sth = $con->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['src'] ).'"/>';
</code>```

With all of the code I tried I got the same result: a white page.

答:
Can you try to change this line:

```<code>echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['src'] ).'"/>';
</code>```

To this:

```<code>foreach($result as $r){
  echo "<img src='".$r['src']."' />";
}
</code>```

Body:
I am trying to display images that I have uploaded to my MySQL database.
The uploading process is working properly, but I have issues in displaying from it and I don't know where I am going wrong.

This is my DB:

 CREATE TABLE `data` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `dozent` varchar(32) NOT NULL DEFAULT '',
  `datum` date NOT NULL,
  `text` text NOT NULL,
  `Ort` varchar(45) NOT NULL DEFAULT '',
  `gastvortraege` varchar(30) NOT NULL DEFAULT '',
  `src` blob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The data I upload is inserted with this code:

require("vortraege_db.php");

$stmt = $con->stmt_init();

$name = mysqli_real_escape_string($con,$_POST['name']);
$title = mysqli_real_escape_string($con,$_POST['titel']);
$text = mysqli_real_escape_string($con,$_POST['text']);
$ort = mysqli_real_escape_string($con,$_POST ['ort']);
$date = mysqli_real_escape_string($con,$_POST['datum']);

$path = $_FILES['image']['tmp_name'];

if(isset($_POST['gast']))
    $uniname = mysqli_real_escape_string($con,$_POST['gast_text']);
else {
    $uniname = mysqli_real_escape_string($con,'');
}

$image = file_get_contents($path);
$image = mysqli_real_escape_string($con, $image);

$stmt->prepare("INSERT INTO data(dozent,datum,`text`,Ort,gastvortraege,src) VALUES(?,?,?,?,?,?)");
$stmt->bind_param('sssssb',$name,$date,$text,$ort,$uniname,$image);
$result = $stmt->execute();

if($result)
    echo "Datensätze erfolgreich hochgeladen";
else {
    echo "Es ist irgendwas schiefgelaufen, bitte erneut versuchen.";
}

Just for testing purpose I used many code snippets I found on stackoverflow, that was the latest one:

$sql = "SELECT * FROM  `data`";
$sth = $con->query($sql);
$result=mysqli_fetch_array($sth);
echo '';

With all of the code I tried I got the same result: a white page.

Body:
Can you try to change this line:

echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['src'] ).'"/>';

To this:

foreach($result as $r){
  echo "<img src='".$r['src']."' />";
}


问:
Cant return manually generated id
I am trying to return the value of new_id but with no success. Any help?

```<code>create or replace FUNCTION create_election (name        VARCHAR,
                             description VARCHAR,
                           type          VARCHAR,
                           subtype       VARCHAR,
                           started_at    VARCHAR,
                           ended_at      VARCHAR)
RETURN INT
IS
v_id int;
BEGIN
    INSERT INTO election VALUES  (
          (  SELECT nvl(max(id)+1, 0) AS new_id FROM  election ) ,
          name,  description,  type, subtype, started_at, ended_at,
          0,  0,  0
) RETURNING new_id into v_id ;
END;
</code>```

--- UPDATE ---
I choose the solution based on best practices. Thx for the help.

答:
I think you need this line before the END which ends the function:

```<code>RETURN v_id;
</code>```

You are getting the data into the local variable v_id but not returning it from the function.

Title: Cant return manually generated id

Body:
I am trying to return the value of new_id but with no success. Any help?

create or replace FUNCTION create_election (name        VARCHAR,
                             description VARCHAR,
                           type          VARCHAR,
                           subtype       VARCHAR,
                           started_at    VARCHAR,
                           ended_at      VARCHAR)
RETURN INT
IS
v_id int;
BEGIN
    INSERT INTO election VALUES  (
          (  SELECT nvl(max(id)+1, 0) AS new_id FROM  election ) ,
          name,  description,  type, subtype, started_at, ended_at,
          0,  0,  0
) RETURNING new_id into v_id ;
END;

--- UPDATE ---
I choose the solution based on best practices. Thx for the help.

Body:
I think you need this line before the END which ends the function:

RETURN v_id;

You are getting the data into the local variable v_id but not returning it from the function.


问:
Conditionally choose a value on the left hand side of an assignment statement?
Is it possible to conditionally choose a value on the left hand side of an assignment statement (in C#)?

If I was assigning one of two values to a single variable, I could do this:

```<code>var1 = (mode == "A" ?
          someList.Any(itm => itm.prop == value) :
          someList.Any(itm => itm.prop == value2)  );

or

var1 = someList.Any(itm => itm.prop == (mode == "A" ? value : value2));
</code>```

But suppose I want to populate one of two variables with a value:

```<code>if (mode == "A")
    var1 = someList.Any(itm => itm.prop == value);

if (mode == "B")
    var2 = someList.Any(itm => itm.prop == value);
</code>```

Is there any way to do this in one line? (non working) example:

```<code>(mode == "A" ? var1 : var2) = someList.Any(itm => itm.prop == value);
</code>```

[I know I can introduce a variable and assign it to var1 or var2 before getting from somelist

```<code>var temp = (mode == "A" ? var1 : var2);
temp = someList.Any(itm => itm.prop == value);
</code>```

]

UPDATE
@HimBromBeere - I know that there are restrictions on the target of an assignment, and I don't need to do this, I just wondered if it was possible, in the same way that usage of the conditional operator is possible.

The code snippets were meant to illustrate and further explain the question.

...But I succeeded in getting two wonderful, useful nuggets of information from @EricLippert and @Servy: The ConditionalAssignment / SelectVariable function and the C# ref function.

I'll probably never use them (Eric - I'll stick to IF), but it helps me to grow.

Thanks everyone for all the useful feedback.

答:
You could do this with a helper method, but please do not.  Just write the code like normal C# code; if you want a conditional assignment then write a conditional assignment with an if.

The helper method would be:

```<code>static void ConditionalAssignment<T>(bool b, ref T v1, ref T v2, T value)
{
  if (b) v1 = value else v2 = value;
}
</code>```

And then at the call site

```<code>ConditionalAssignment(condition, ref v1, ref v2, value);
</code>```

In general the way you do something "in one line" is you make a method that does whatever you want and then call it. Methods are the fundamental technique for abstractions in C#.

In cases like this where the abstraction is a single statement wrapped up in a method, it's often better to just put that statement in line. This is definitely such a case. If you want the behaviour of an if then just write an if please.

Body:
Is it possible to conditionally choose a value on the left hand side of an assignment statement (in C#)?

If I was assigning one of two values to a single variable, I could do this:

var1 = (mode == "A" ?
          someList.Any(itm => itm.prop == value) :
          someList.Any(itm => itm.prop == value2)  );

or

var1 = someList.Any(itm => itm.prop == (mode == "A" ? value : value2));

But suppose I want to populate one of two variables with a value:

if (mode == "A")
    var1 = someList.Any(itm => itm.prop == value);

if (mode == "B")
    var2 = someList.Any(itm => itm.prop == value);

Is there any way to do this in one line? (non working) example:

(mode == "A" ? var1 : var2) = someList.Any(itm => itm.prop == value);

[I know I can introduce a variable and assign it to var1 or var2 before getting from somelist

var temp = (mode == "A" ? var1 : var2);
temp = someList.Any(itm => itm.prop == value);

]

UPDATE
@HimBromBeere - I know that there are restrictions on the target of an assignment, and I don't need to do this, I just wondered if it was possible, in the same way that usage of the conditional operator is possible.

The code snippets were meant to illustrate and further explain the question.

...But I succeeded in getting two wonderful, useful nuggets of information from @EricLippert and @Servy: The ConditionalAssignment / SelectVariable function and the C# ref function.

I'll probably never use them (Eric - I'll stick to IF), but it helps me to grow.

Thanks everyone for all the useful feedback.

Body:
You could do this with a helper method, but please do not.  Just write the code like normal C# code; if you want a conditional assignment then write a conditional assignment with an if.

The helper method would be:

static void ConditionalAssignment<T>(bool b, ref T v1, ref T v2, T value)
{
  if (b) v1 = value else v2 = value;
}

And then at the call site

ConditionalAssignment(condition, ref v1, ref v2, value);

In general the way you do something "in one line" is you make a method that does whatever you want and then call it. Methods are the fundamental technique for abstractions in C#.

In cases like this where the abstraction is a single statement wrapped up in a method, it's often better to just put that statement in line. This is definitely such a case. If you want the behaviour of an if then just write an if please.


问:
Safari pauses all animation on redirect / form submission
I have an animation that triggers when a link is clicked. It is a jQuery animation that enlarges a div then fades out. To ensure speed, at the exact same time that the link is clicked, the redirect is fired off. This has to happen and I cannot put the redirect in the success function of jQuery's animate(). This redirect is done via a form submission. On Chrome, Firefox, and IE it works as expected, the animation plays and if the page loads entirely before the finish of the animation, it redirects but the animation does play.

On Safari (primarily testing on iPad), as soon as the link is clicked, the page seemingly 'freezes' and the animation fails to execute. There are also GIF's that are on the screen at page load, and if I click a link while those GIF's are on screen and animating, they pause as well. I have seen a post that says to set a timeout, apply styling, then submit, but the problem is that although the HTML will apply that CSS style, it still freezes the screen, and they are not dealing with animation, just static CSS styling.

Here is some example code to show the method of how I am accomplishing this (it is not tested just trying to illustrate my point, so there may be missing parts or syntax errors):

var someData = 'foo'; //This value is irrelevant, just there for syntactical consistency.
$("#link").on("click", function() {
    var form = $("<form method='POST'></form>");
    form.attr("action", "http://someurl.com");
    var input = $("<input type='hidden'/>");
    input.val(someData);
    form.append(input);
    $(document.body).append(form);
    form.submit();

    //Form has been submitted, now run a short animation for the remaining life of the current page
    $(this).animate({width: "100px", height: "100px", opacity: "0"}, 150);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="link" style="width: 100px; height: 100px; background-color: #FFF">Click Me</div></code>```

Essentially, I need to make sure that once the Safari browser begins to load a new page / link, it does not stop updating the current page. This sounds like a problem in Safari from what I have seen, but this issue has also not been run into very commonly across the web as I have seen. There are posts dealing with GIF animations, but this is a CSS style animation.

Thanks for any help!

答:
You could use a setTimeout to go to the link after the animation.</p>

```<code>var someData = 'foo'; //This value is irrelevant, just there for syntactical consistency.

$("#link").on("click", function() {
    setTimeout(doThisAfterTimeExpires,2000);
    $(this).animate({width: "100px", height: "100px", opacity: "0"}, 150);
});

function doThisAfterTimeExpires(){

    var form = $("<form method='POST'></form>");
    form.attr("action", "http://someurl.com");
    var input = $("<input type='hidden'/>");
    input.val(someData);
    form.append(input);
    $(document.body).append(form);
    form.submit();

}
</code>```

Body:
I have an animation that triggers when a link is clicked. It is a jQuery animation that enlarges a div then fades out. To ensure speed, at the exact same time that the link is clicked, the redirect is fired off. This has to happen and I cannot put the redirect in the success function of jQuery's animate(). This redirect is done via a form submission. On Chrome, Firefox, and IE it works as expected, the animation plays and if the page loads entirely before the finish of the animation, it redirects but the animation does play.

On Safari (primarily testing on iPad), as soon as the link is clicked, the page seemingly 'freezes' and the animation fails to execute. There are also GIF's that are on the screen at page load, and if I click a link while those GIF's are on screen and animating, they pause as well. I have seen a post that says to set a timeout, apply styling, then submit, but the problem is that although the HTML will apply that CSS style, it still freezes the screen, and they are not dealing with animation, just static CSS styling.

Here is some example code to show the method of how I am accomplishing this (it is not tested just trying to illustrate my point, so there may be missing parts or syntax errors):

var someData = 'foo'; //This value is irrelevant, just there for syntactical consistency.
$("#link").on("click", function() {
    var form = $("<form method='POST'></form>");
    form.attr("action", "http://someurl.com");
    var input = $("<input type='hidden'/>");
    input.val(someData);
    form.append(input);
    $(document.body).append(form);
    form.submit();

    //Form has been submitted, now run a short animation for the remaining life of the current page
    $(this).animate({width: "100px", height: "100px", opacity: "0"}, 150);
  });

Click Me

Essentially, I need to make sure that once the Safari browser begins to load a new page / link, it does not stop updating the current page. This sounds like a problem in Safari from what I have seen, but this issue has also not been run into very commonly across the web as I have seen. There are posts dealing with GIF animations, but this is a CSS style animation.

Thanks for any help!

Body:
You could use a setTimeout to go to the link after the animation.

var someData = 'foo'; //This value is irrelevant, just there for syntactical consistency.

$("#link").on("click", function() {
    setTimeout(doThisAfterTimeExpires,2000);
    $(this).animate({width: "100px", height: "100px", opacity: "0"}, 150);
});

function doThisAfterTimeExpires(){

    var form = $("<form method='POST'></form>");
    form.attr("action", "http://someurl.com");
    var input = $("<input type='hidden'/>");
    input.val(someData);
    form.append(input);
    $(document.body).append(form);
    form.submit();

}


答:
Using queries like SELECT nvl(max(id)+1, 0) AS new_id FROM  election to generate IDs is a bad practice. You will get duplicated values each time, when two or more users will invoke this function.

Oracle has sequences for this. Sequences always generate unique values. First, create sequence:

```<code>create sequence election_seq;
</code>```

Then use it in your function:

```<code>create or replace FUNCTION create_election (name        VARCHAR,
                             description VARCHAR,
                           type          VARCHAR,
                           subtype       VARCHAR,
                           started_at    VARCHAR,
                           ended_at      VARCHAR)
RETURN INT
IS
v_id int;
BEGIN
  v_id := election_seq.nextval;
  INSERT INTO election VALUES
  (v_id, name,  description,  type, subtype, started_at, ended_at, 0,  0,  0);
END;
</code>```

Title: Cant return manually generated id

Body:
Using queries like SELECT nvl(max(id)+1, 0) AS new_id FROM  election to generate IDs is a bad practice. You will get duplicated values each time, when two or more users will invoke this function.

Oracle has sequences for this. Sequences always generate unique values. First, create sequence:

create sequence election_seq;

Then use it in your function:

create or replace FUNCTION create_election (name        VARCHAR,
                             description VARCHAR,
                           type          VARCHAR,
                           subtype       VARCHAR,
                           started_at    VARCHAR,
                           ended_at      VARCHAR)
RETURN INT
IS
v_id int;
BEGIN
  v_id := election_seq.nextval;
  INSERT INTO election VALUES
  (v_id, name,  description,  type, subtype, started_at, ended_at, 0,  0,  0);
END;


问:
Converting date variable as character to numeric in r
I have a dataframe with a time period column that is saved as characters and is in the following format:

```<code>x
[1] "00:17:31.199"          "1 day 01:37:46.22"     "00:43:11.51"           "01:18:37.721" ...
</code>```

I would like to convert the values of this column to hours (and hour decimals) 31/ so that the returning column is

```<code>[1] 0.28 25.61 0.71 1.3 ...
</code>```

in which 0.28 is 17/60 hours and 25.61 is equal to 24+1+37/60. Note that everything is saved as characters. I couldn't find any command in baseR or lubridate to figure this out. Any help?

答:
So, I ended up doing the following based on @Mako212 and @thelatemail:

```<code>days <- gsub("(\\d+)(?=\\sday).*", "\\1", x, perl=TRUE) # extracting the number of days
hours <- gsub(".*(\\S*\\s+\\S+)", "\\1", x, perl=TRUE) # getting rid of days
ind <- grep("(\\d+)(?=\\sday).*", x, perl=TRUE) # getting the indices of elements that have days
</code>```

Then I used as.difftime in order to calculate the time difference in hours.

```<code>time.hours <- as.difftime(x, format="%H:%M:%OS", units="hours")
</code>```

Now, I need to calculate the days that I extracted in vector days in terms of hours and add it to time.hours.

```<code>for (i in ind) {
time.hours[ind] <- as.numeric(days[ind])*24 +
    as.difftime(hours[ind], format="%H:%M:%OS", units="hours")
}
</code>```

Note that there might be a more efficient way of doing the above loop but that's how I did it.

Body:
I have a dataframe with a time period column that is saved as characters and is in the following format:

x
[1] "00:17:31.199"          "1 day 01:37:46.22"     "00:43:11.51"           "01:18:37.721" ...

I would like to convert the values of this column to hours (and hour decimals) 31/ so that the returning column is

[1] 0.28 25.61 0.71 1.3 ...

in which 0.28 is 17/60 hours and 25.61 is equal to 24+1+37/60. Note that everything is saved as characters. I couldn't find any command in baseR or lubridate to figure this out. Any help?

Body:
So, I ended up doing the following based on @Mako212 and @thelatemail:

days <- gsub("(\\d+)(?=\\sday).*", "\\1", x, perl=TRUE) # extracting the number of days
hours <- gsub(".*(\\S*\\s+\\S+)", "\\1", x, perl=TRUE) # getting rid of days
ind <- grep("(\\d+)(?=\\sday).*", x, perl=TRUE) # getting the indices of elements that have days

Then I used as.difftime in order to calculate the time difference in hours.

time.hours <- as.difftime(x, format="%H:%M:%OS", units="hours")

Now, I need to calculate the days that I extracted in vector days in terms of hours and add it to time.hours.

for (i in ind) {
time.hours[ind] <- as.numeric(days[ind])*24 +
    as.difftime(hours[ind], format="%H:%M:%OS", units="hours")
}

Note that there might be a more efficient way of doing the above loop but that's how I did it.


答:
Just loop through all the elements that has the same data-post-id value as the clicked element using jQuery's each().

$( document ).on( 'click touch', '.target', function() {
    $("[data-post-id=" + $(this).data('post-id') + "]").each(function(){
        $(this).css("color", "red");
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="list">
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
</div></code>```

Title: Loop through elements with matching data attribute values

Body:
I have the following setup:

    $( document ).on( 'click touch', '.target', function() {
        if ($(this).data("post-id") == $(this).closest('.list').find('.target').data("post-id")) {
           alert('do stuff');
        }
    });

a

b

a

a

b

Whenever user clicks on .target element, I want to do stuff to all divs within the closest .list. So if user clicks on .target with post-id data value 1,  it should so something to all others with the same data attribute value...

How do I do this type of loop with jQuery?

Body:
Just loop through all the elements that has the same data-post-id value as the clicked element using jQuery's each().

$( document ).on( 'click touch', '.target', function() {
    $("[data-post-id=" + $(this).data('post-id') + "]").each(function(){
        $(this).css("color", "red");
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="list">
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="1">a</div></div>
  <div><div class="target" data-post-id="2">b</div></div>
</div>


答:
toggleClass does exactly that.

http://api.jquery.com/toggleClass/

Title: Clicking A Link Two Times

Body:
I have a link like this :

<a href="#" onclick="renkDegistir()" title="Yaz .......

And JS code :

function renkDegistir()
    {
        $("#cont #main article").addClass("siyah-stil");
    }

When click this link siyah-stil class is added to article. But i want to do, if link clicked 2nd time remove siyah-stil class.

In summary ,

on first click : addClass("siyah-stil");
on second click : removeClass("siyah-stil");


答:
You need to add select into before insert as

```<code>  SELECT nvl(max(id)+1, 0) into v_id  FROM  election
</code>```

And use v_id later in insert and return .

Title: Cant return manually generated id

Body:
You need to add select into before insert as

  SELECT nvl(max(id)+1, 0) into v_id  FROM  election

And use v_id later in insert and return .


问:
HAXM setup failed in android studio
I have an error saying installation did not complete successfully,see IDE log for Errors. When i saw, it said "Failed to update status to COMPLETE: HAXM setup failed!". Please can anyone tell me what is wrong

Failed to update status to COMPLETE: HAXM setup failed!
com.android.repository.api.PackageOperation$StatusChangeListenerException: HAXM setup failed!
 at com.android.tools.idea.sdk.install.HaxmInstallListener.statusChanged(HaxmInstallListener.java:57)
 at com.android.repository.impl.installer.AbstractPackageOperation.updateStatus(AbstractPackageOperation.java:450)
 at com.android.repository.impl.installer.AbstractPackageOperation.complete(AbstractPackageOperation.java:176)
 at com.android.tools.idea.sdk.wizard.InstallTask.completePackages(InstallTask.java:151)
 at com.android.tools.idea.sdk.wizard.InstallTask.run(InstallTask.java:107)
 at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:726)
 at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:176)
 at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:556)
 at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:501)
 at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:66)
 at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:163)
 at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:137)
 at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:334)
 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)```

答:
Try the following link to install the Intel HAXM manually from Intel site. You may have to disable Hyper-V in Windows Features.

Installation Instructions for Intel® Hardware Accelerated Execution Manager (Intel® HAXM) - Microsoft Windows

Title: HAXM setup failed in android studio


问:
Unable to edit form input using redux
I've created a container called siteEdit.js. It handles creating & editing "sites".

I've setup actionCreators that handles taking the form data and submitting it to the API. This works perfectly.

But when you visit the container using a route that contains an ID it will run an actionCreator that will fetch for the "Site" data based on the id param.

This all works as expected, but since I'm using redux, I'm setting the Input value with the props. for example, this.props.title

I'm trying to stay away from using the redux-form package for now.

Container:

```<code>import React, {Component} from 'react';
import { connect } from 'react-redux';

import {createSite, getSite} from '../../actions/siteActions';

class SiteEdit extends Component {
  constructor(props) {
    super(props)
    this.state = {
      title: '',
      url: '',
      description: '',
      approvedUsers: []
    }
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  componentWillMount() {
    if(this.props.params.id) {
      this.props.dispatch(getSite(this.props.params.id))
    }
  }

  handleInputChange(e) {
    const target = e.target
    const value = target.type === 'checkbox' ? target.checked : target.value
    const name = target.name

    this.setState({
      [name]: value
    })
  }

  handleSubmit(e) {
    e.preventDefault()
    this.props.dispatch(createSite(this.state))
  }

  render() {

    const {title, url, description, approvedUsers} = this.props

    return (
      <div className="SiteEdit">
        <h1>NEW SITE</h1>
        <form onSubmit={this.handleSubmit}>

          <div className="block">
            <label>Site Name</label>
            <input
              className="input"
              type="text"
              value={title ? title : this.state.title}
              onChange={this.handleInputChange}
              name="title" />
          </div>
          <div className="block">
            <label>Site URL</label>
            <input
              className="input"
              type="text"
              value={this.state.url}
              onChange={this.handleInputChange}
              name="url" />
          </div>
          <div className="block">
            <label>Description</label>
            <input
              className="textarea"
              type="textarea"
              value={this.state.description}
              onChange={this.handleInputChange}
              name="description" />
          </div>
          <div className="block">
            <label>Approved Users</label>
            <input
              className="input"
              type="text"
              value={this.state.approvedUsers}
              onChange={this.handleInputChange}
              name="approvedUsers" />
          </div>

          <button className="button--action">Create</button>
        </form>
      </div>
    )
  }
}

const mapStateToProps = (state) => ({
  title: state.sites.showSite.title,
  url: state.sites.showSite.url,
  description: state.sites.showSite.description,
  approvedUsers: state.sites.showSite.approvedUsers
})

SiteEdit = connect(mapStateToProps)(SiteEdit)

export default SiteEdit
</code>```

ActionCreators:

```<code>import config from '../config'
import { push } from 'react-router-redux'

const apiUrl = config.api.url

// List all sites
export const LIST_SITES_START = 'LIST_SITES_START'
export const LIST_SITES_SUCCESS = 'LIST_SITES_SUCCES'
export const LIST_SITES_ERROR = 'LIST_SITES_ERROR'

export function sitesListStart(data) {
  return { type: LIST_SITES_START, data }
}

export function sitesListSuccess(data) {
  return { type: LIST_SITES_SUCCESS, data }
}

export function sitesListError(data) {
  return { type: LIST_SITES_ERROR, data }
}

export function listSites() {
  return (dispatch) => {
    dispatch(sitesListStart())
    fetch(`${apiUrl}/listSites`)
    .then(res => res.json())
    .then(json => {
      dispatch(sitesListSuccess(json))
    })
    .catch(error => {
      dispatch(sitesListError)
    })
  }
}

// Create & Edit Sites
export const CREATE_SITE_START = 'CREATE_SITE_START'
export const CREATE_SITE_SUCESS = 'CREATE_SITE_SUCCESS'
export const CREATE_SITE_ERROR = 'CREATE_SITE_ERROR'

export function siteCreateStart(data) {
  return { type: CREATE_SITE_START, data}
}

export function siteCreateSuccess(data) {
  return { type: CREATE_SITE_SUCCESS, data}
}

export function siteCreateError(error) {
  return { type: CREATE_SITE_ERROR, error}
}

export function createSite(data) {
  return (dispatch) => {
    dispatch(siteCreateStart())
    fetch(`${apiUrl}/createSite`, {
      method: 'post',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
    .then(res => res.json())
    .then(json => {
      dispatch(push('/'))
      dispatch(siteCreateSuccess())
    })
    .catch(error => {
      dispatch(siteCreateError())
    })

  }
}

// Get Single Site
export const GET_SITE_START = 'GET_SITE_START'
export const GET_SITE_SUCCESS = 'GET_SITE_SUCCESS'
export const GET_SITE_ERROR = 'GET_SITE_ERROR'

export function getSiteStart(data) {
  return { type: GET_SITE_START, data}
}

export function getSiteSuccess(data) {
  return { type: GET_SITE_SUCCESS, data}
}

export function getSiteError(error) {
  return { type: GET_SITE_ERROR, error}
}

export function getSite(id) {
  return (dispatch) => {
    dispatch(getSiteStart())
    fetch(`${apiUrl}/getSite/${id}`)
    .then(res => res.json())
    .then(json => {
      dispatch(getSiteSuccess(json))
    })
    .catch(error => {
      dispatch(getSiteError())
    })
  }
}
</code>```

Reducers:

```<code>import {push} from 'react-router-redux'
import {
  LIST_SITES_START,
  LIST_SITES_SUCCESS,
  LIST_SITES_ERROR,
  GET_SITE_START,
  GET_SITE_SUCCESS,
  GET_SITE_ERROR
} from '../actions/siteActions'

const initialState = {
  sitesList: {
    sites: [],
    error: null,
    loading: true
  },
  showSite: {
    title: '',
    url: '',
    description: '',
    approvedUsers: [],
    loading: true
  }
}

export default function (state = initialState, action) {
  switch (action.type) {
    // List Sites
    case LIST_SITES_START:
      return Object.assign({}, state, {
        sitesList: Object.assign({}, state.sitesList, {
          loading: true
        })
      })
    case LIST_SITES_SUCCESS:
      return Object.assign({}, state, {
        sitesList: Object.assign({}, state.sitesList, {
          sites: action.data,
          loading: false
        })
      })
    case LIST_SITES_ERROR:
      return Object.assign({}, state, {
        error: action.error,
        loading: false
      })

    case GET_SITE_START:
      return Object.assign({}, state, {
        showSite: Object.assign({}, state.showSite, {
          loading: true
        })
      })
    case GET_SITE_SUCCESS:
      return Object.assign({}, state, {
        showSite: Object.assign({}, state.showSite, {
          ...action.data,
          loading: false
        })
      })
    case GET_SITE_ERROR:
      return Object.assign({}, state, {
        showSite: Object.assign({}, state.showSite, {
          error: action.error,
          loading: false
        })
      })

    default:
      return state
  }
}
</code>```

答:
You are setting the ternary for the value with the props.title taking precedent, like so just to re-iterate -

```<code> const { title } = this.props;
 ...
 value={title ? title : this.state.title}
</code>```

Your onChange logic is correct and is probably updating your components local state correctly, however you still have this.props.title, so it will take precedent in that ternary.

There are a bunch of ways you could handle this, it will depend on order of operations really (that is when props.title will be truthy or not). Assuming you have the title when the component mounts you can do something in the constructor like:

```<code> constructor(props) {
    super(props)
    this.state = {
      title: props.title,   << set default here
      url: '',
      description: '',
      approvedUsers: []
    }
</code>```

then in the input you only need to set the value to the state title

```<code>value={this.state.title}
</code>```

This will depend on when the props.title value comes into your component of course, if it is not there for mount, this will not work as intended.

You could also pass a function to evaluate all of this for the value of the input as well - inside of which you would more verbosely check the props.title vs the state.title and decide which one to return as your value.

```<code> <input value={this.returnTitleValue} ..  << something like so
</code>```

Hope this helps!

Title: Unable to edit form input using redux

Body:
I've created a container called siteEdit.js. It handles creating & editing "sites".

I've setup actionCreators that handles taking the form data and submitting it to the API. This works perfectly.

But when you visit the container using a route that contains an ID it will run an actionCreator that will fetch for the "Site" data based on the id param.

This all works as expected, but since I'm using redux, I'm setting the Input value with the props. for example, this.props.title

I'm trying to stay away from using the redux-form package for now.

Container:

import React, {Component} from 'react';
import { connect } from 'react-redux';

import {createSite, getSite} from '../../actions/siteActions';

class SiteEdit extends Component {
  constructor(props) {
    super(props)
    this.state = {
      title: '',
      url: '',
      description: '',
      approvedUsers: []
    }
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleInputChange = this.handleInputChange.bind(this)
  }

  componentWillMount() {
    if(this.props.params.id) {
      this.props.dispatch(getSite(this.props.params.id))
    }
  }

  handleInputChange(e) {
    const target = e.target
    const value = target.type === 'checkbox' ? target.checked : target.value
    const name = target.name

    this.setState({
      [name]: value
    })
  }

  handleSubmit(e) {
    e.preventDefault()
    this.props.dispatch(createSite(this.state))
  }

  render() {

    const {title, url, description, approvedUsers} = this.props

    return (

NEW SITE

        <form onSubmit={this.handleSubmit}>

            Site Name
            <input
              className="input"
              type="text"
              value={title ? title : this.state.title}
              onChange={this.handleInputChange}
              name="title" />

            Site URL
            <input
              className="input"
              type="text"
              value={this.state.url}
              onChange={this.handleInputChange}
              name="url" />

            Description
            <input
              className="textarea"
              type="textarea"
              value={this.state.description}
              onChange={this.handleInputChange}
              name="description" />

            Approved Users
            <input
              className="input"
              type="text"
              value={this.state.approvedUsers}
              onChange={this.handleInputChange}
              name="approvedUsers" />

          <button className="button--action">Create</button>
        </form>

    )
  }
}

const mapStateToProps = (state) => ({
  title: state.sites.showSite.title,
  url: state.sites.showSite.url,
  description: state.sites.showSite.description,
  approvedUsers: state.sites.showSite.approvedUsers
})

SiteEdit = connect(mapStateToProps)(SiteEdit)

export default SiteEdit

ActionCreators:

import config from '../config'
import { push } from 'react-router-redux'

const apiUrl = config.api.url

// List all sites
export const LIST_SITES_START = 'LIST_SITES_START'
export const LIST_SITES_SUCCESS = 'LIST_SITES_SUCCES'
export const LIST_SITES_ERROR = 'LIST_SITES_ERROR'

export function sitesListStart(data) {
  return { type: LIST_SITES_START, data }
}

export function sitesListSuccess(data) {
  return { type: LIST_SITES_SUCCESS, data }
}

export function sitesListError(data) {
  return { type: LIST_SITES_ERROR, data }
}

export function listSites() {
  return (dispatch) => {
    dispatch(sitesListStart())
    fetch(`${apiUrl}/listSites`)
    .then(res => res.json())
    .then(json => {
      dispatch(sitesListSuccess(json))
    })
    .catch(error => {
      dispatch(sitesListError)
    })
  }
}

// Create & Edit Sites
export const CREATE_SITE_START = 'CREATE_SITE_START'
export const CREATE_SITE_SUCESS = 'CREATE_SITE_SUCCESS'
export const CREATE_SITE_ERROR = 'CREATE_SITE_ERROR'

export function siteCreateStart(data) {
  return { type: CREATE_SITE_START, data}
}

export function siteCreateSuccess(data) {
  return { type: CREATE_SITE_SUCCESS, data}
}

export function siteCreateError(error) {
  return { type: CREATE_SITE_ERROR, error}
}

export function createSite(data) {
  return (dispatch) => {
    dispatch(siteCreateStart())
    fetch(`${apiUrl}/createSite`, {
      method: 'post',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
    .then(res => res.json())
    .then(json => {
      dispatch(push('/'))
      dispatch(siteCreateSuccess())
    })
    .catch(error => {
      dispatch(siteCreateError())
    })

  }
}

// Get Single Site
export const GET_SITE_START = 'GET_SITE_START'
export const GET_SITE_SUCCESS = 'GET_SITE_SUCCESS'
export const GET_SITE_ERROR = 'GET_SITE_ERROR'

export function getSiteStart(data) {
  return { type: GET_SITE_START, data}
}

export function getSiteSuccess(data) {
  return { type: GET_SITE_SUCCESS, data}
}

export function getSiteError(error) {
  return { type: GET_SITE_ERROR, error}
}

export function getSite(id) {
  return (dispatch) => {
    dispatch(getSiteStart())
    fetch(`${apiUrl}/getSite/${id}`)
    .then(res => res.json())
    .then(json => {
      dispatch(getSiteSuccess(json))
    })
    .catch(error => {
      dispatch(getSiteError())
    })
  }
}

Reducers:

import {push} from 'react-router-redux'
import {
  LIST_SITES_START,
  LIST_SITES_SUCCESS,
  LIST_SITES_ERROR,
  GET_SITE_START,
  GET_SITE_SUCCESS,
  GET_SITE_ERROR
} from '../actions/siteActions'

const initialState = {
  sitesList: {
    sites: [],
    error: null,
    loading: true
  },
  showSite: {
    title: '',
    url: '',
    description: '',
    approvedUsers: [],
    loading: true
  }
}

export default function (state = initialState, action) {
  switch (action.type) {
    // List Sites
    case LIST_SITES_START:
      return Object.assign({}, state, {
        sitesList: Object.assign({}, state.sitesList, {
          loading: true
        })
      })
    case LIST_SITES_SUCCESS:
      return Object.assign({}, state, {
        sitesList: Object.assign({}, state.sitesList, {
          sites: action.data,
          loading: false
        })
      })
    case LIST_SITES_ERROR:
      return Object.assign({}, state, {
        error: action.error,
        loading: false
      })

    case GET_SITE_START:
      return Object.assign({}, state, {
        showSite: Object.assign({}, state.showSite, {
          loading: true
        })
      })
    case GET_SITE_SUCCESS:
      return Object.assign({}, state, {
        showSite: Object.assign({}, state.showSite, {
          ...action.data,
          loading: false
        })
      })
    case GET_SITE_ERROR:
      return Object.assign({}, state, {
        showSite: Object.assign({}, state.showSite, {
          error: action.error,
          loading: false
        })
      })

    default:
      return state
  }
}

Body:
You are setting the ternary for the value with the props.title taking precedent, like so just to re-iterate -

 const { title } = this.props;
 ...
 value={title ? title : this.state.title}

Your onChange logic is correct and is probably updating your components local state correctly, however you still have this.props.title, so it will take precedent in that ternary.

There are a bunch of ways you could handle this, it will depend on order of operations really (that is when props.title will be truthy or not). Assuming you have the title when the component mounts you can do something in the constructor like:

 constructor(props) {
    super(props)
    this.state = {
      title: props.title,   << set default here
      url: '',
      description: '',
      approvedUsers: []
    }

then in the input you only need to set the value to the state title

value={this.state.title}

This will depend on when the props.title value comes into your component of course, if it is not there for mount, this will not work as intended.

You could also pass a function to evaluate all of this for the value of the input as well - inside of which you would more verbosely check the props.title vs the state.title and decide which one to return as your value.

 <input value={this.returnTitleValue} ..  << something like so

Hope this helps!