问:
Using an Event Listener to detect clicks on buttons and then increase count on an html element
My main goal is to add the ability of this BlackJack game to show and increase the amount of games played at the bottom of the webpage using an Event Listener. I have only been learning JS for a few days and perhaps I picked a too difficult of problem but I am so close to a solution. Pretty sure I am either missing one variable needed or do not know about a certain function to make things easier.

I've already tried using the click function and I was able to successfully make a button that when clicked increased the amount on the button. I've also made the button and the header the same class name and it was able to successfully click the button to increase the number. But I believe I am missing something basic to connect the "debutton" class elements with the
 0
 to increase its amount.

var button = document.getElementsByClassName("debutton")
var gamesplayed = document.getElementById("gamesplayed")

count = 0;
for (var i = 0 ; i < button.length; i++) {
  button[i].addEventListener('click' , displaygames , false);
}

function displaygames() {
  console.log("The Button was clicked!");
  gamesplayed.count += 1;
  gamesplayed.innerHTML = "" + count;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <h1><b><em>BlackJack</em></b></h1>
  <h2>Betting</h2>
  <div>
    <button class="debutton" id="debutton" onClick="deal(1)">Bet  $1</button>
    <button class="debutton" id="debutton" onClick="deal(5)">Bet $5</button>
    <button class="debutton" id="debutton" onClick="deal(10)">Bet $10</button>
    <button class="debutton" id="debutton" onClick="deal(20)">Bet $20</button><br>
    <h2>My Money</h2>
    <div id="playermoney"><b>$100</b></div>
  </div>

  <h3><em>Games Played:</em></h3>
  <h4 class="gamesplayed" id="gamesplayed" type="number">0</h4>
</body></code>```

The console log is letting me know that I am finding the "debutton" elements successfully.

答:
```<code>gamesplayed.count += 1; should be count += 1
</code>```

By the way in my opinion you don't need the listening event if you call deal() function always on debutton, then you can increment your count variable there.

Body:
My main goal is to add the ability of this BlackJack game to show and increase the amount of games played at the bottom of the webpage using an Event Listener. I have only been learning JS for a few days and perhaps I picked a too difficult of problem but I am so close to a solution. Pretty sure I am either missing one variable needed or do not know about a certain function to make things easier.

I've already tried using the click function and I was able to successfully make a button that when clicked increased the amount on the button. I've also made the button and the header the same class name and it was able to successfully click the button to increase the number. But I believe I am missing something basic to connect the "debutton" class elements with the
 0
 to increase its amount.

var button = document.getElementsByClassName("debutton")
var gamesplayed = document.getElementById("gamesplayed")

count = 0;
for (var i = 0 ; i < button.length; i++) {
  button[i].addEventListener('click' , displaygames , false);
}

function displaygames() {
  console.log("The Button was clicked!");
  gamesplayed.count += 1;
  gamesplayed.innerHTML = "" + count;
};

BlackJack

Betting

    <button class="debutton" id="debutton" onClick="deal(1)">Bet  $1</button>
    <button class="debutton" id="debutton" onClick="deal(5)">Bet $5</button>
    <button class="debutton" id="debutton" onClick="deal(10)">Bet $10</button>
    <button class="debutton" id="debutton" onClick="deal(20)">Bet $20</button>

My Money

$100

Games Played:

0

The console log is letting me know that I am finding the "debutton" elements successfully.

Body:
gamesplayed.count += 1; should be count += 1

By the way in my opinion you don't need the listening event if you call deal() function always on debutton, then you can increment your count variable there.


来源: stackexchange

答:
Two pointers before I go into a solution. To help understand the solution I have "dumbed" this down to its simplest form. Which is a button that updates the total counter when clicked. The second is I've used jQuery as it is a really useful tool and simplifies the work that needs to be done.

```<code><button class="increase" value="10">Add</button>
<div class="total">$<span class="count">0</span></div>

<script>
    var counter = $('.total span.count');
    $(document).ready(function(){
        $(".increase").click(function(){
            currentValue = parseInt(counter.text())
            addValue = parseInt($(this).attr('value'));
            counter.text(currentValue + addValue);
        });
    });
</script>
</code>```

Above we have a button that holds a value, in this case "10". We then bind a listen event for the click of the button. When clicking the button, we extract the "value" attribute and the button total value from the span.count element and add them together before updating the text.

Also note that I've structured it this way so the currently symbol is outside of the span.count element so we can trust that the value will always be numerical.

As an important note. We need to use parseInt() to convert the values we extract to integers. Otherwise they will be used as strings and "10" + "10" will result in 1010 instead of 20.

ContentLicense: CC BY-SA 4.0

Title: Using an Event Listener to detect clicks on buttons and then increase count on an html element

Body:
Two pointers before I go into a solution. To help understand the solution I have "dumbed" this down to its simplest form. Which is a button that updates the total counter when clicked. The second is I've used jQuery as it is a really useful tool and simplifies the work that needs to be done.

<button class="increase" value="10">Add</button>
<div class="total">$<span class="count">0</span></div>

<script>
    var counter = $('.total span.count');
    $(document).ready(function(){
        $(".increase").click(function(){
            currentValue = parseInt(counter.text())
            addValue = parseInt($(this).attr('value'));
            counter.text(currentValue + addValue);
        });
    });
</script>

Above we have a button that holds a value, in this case "10". We then bind a listen event for the click of the button. When clicking the button, we extract the "value" attribute and the button total value from the span.count element and add them together before updating the text.

Also note that I've structured it this way so the currently symbol is outside of the span.count element so we can trust that the value will always be numerical.

As an important note. We need to use parseInt() to convert the values we extract to integers. Otherwise they will be used as strings and "10" + "10" will result in 1010 instead of 20.


问:
How to make the link appear in base.html in django
I am learning django, I added a new app,

the link can be displayed in friendly_link.html,

the code is as follows:

admin.py

```<code>from django.contrib import admin
from .models import FriendlyLink

admin.site.register(FriendlyLink)
</code>```

models.py

```<code>from django.db import models

class FriendlyLink(models.Model):
    title = models.CharField(max_length=100, default='', verbose_name='title')
    url = models.CharField(max_length=100, default='', verbose_name='url')

    class Meta:
        verbose_name_plural = 'links'

    def __str__(self):
        return self.title

</code>```

views.py

```<code>from django.shortcuts import render
from .models import FriendlyLink

def friendly_link(request):
    friendly_link = FriendlyLink.objects.order_by('title')
    context = {'friendly_link': friendly_link}
    return render(request, 'friendly_link.html', context)

</code>```

urls.py

```<code>from django.urls import re_path
from . import views

urlpatterns = [
    re_path(r'^links$', views.friendly_link, name='friendly_link'),
]
</code>```

friendly_link.html

```<code>{% extends "base.html" %}

{% block title %}Links{% endblock %}

{% block content %}
<ul>
  {% for link in friendly_link %}
  <li><a href="{{ link.url }}">{{ link.title }}</a></li>
  {% empty %}
  {% endfor %}
</ul>
{% endblock %}
</code>```

base.html

```<code>{% load i18n static %}<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
{% block content %}{% endblock %}

<footer>
<ul>
  <!--This code doesn't work-->
  {% for link in friendly_link %}
  <li><a href="{{ link.url }}">{{ link.title }}</a></li>
  {% empty %}
  {% endfor %}
</ul>
</footer>
...
</body>
</code>```

I want to put the link inside the  element in base.html. How do I change the code? Thank you.

答:
You should really read this documentation page:

https://django-adminlte2.readthedocs.io/en/latest/templates_and_blocks.html

Each block is clickable there and there's a detailed description on how to overwrite each one.

For your problem, you will probably nav_footer

```<code>{% block nav_footer %}
{{ block.super }}
...
{% endblock %}
</code>```

{{ block.super }} is optional and will append your content to the block instead of overwriting it.

Body:
I am learning django, I added a new app,

the link can be displayed in friendly_link.html,

the code is as follows:

admin.py

from django.contrib import admin
from .models import FriendlyLink

admin.site.register(FriendlyLink)

models.py

from django.db import models

class FriendlyLink(models.Model):
    title = models.CharField(max_length=100, default='', verbose_name='title')
    url = models.CharField(max_length=100, default='', verbose_name='url')

    class Meta:
        verbose_name_plural = 'links'

    def __str__(self):
        return self.title

views.py

from django.shortcuts import render
from .models import FriendlyLink

def friendly_link(request):
    friendly_link = FriendlyLink.objects.order_by('title')
    context = {'friendly_link': friendly_link}
    return render(request, 'friendly_link.html', context)

urls.py

from django.urls import re_path
from . import views

urlpatterns = [
    re_path(r'^links$', views.friendly_link, name='friendly_link'),
]

friendly_link.html

{% extends "base.html" %}

{% block title %}Links{% endblock %}

{% block content %}

  {% for link in friendly_link %}

{{ link.title }}

  {% empty %}
  {% endfor %}

{% endblock %}

base.html

{% load i18n static %}<!DOCTYPE html>

...

...
{% block content %}{% endblock %}

  {% for link in friendly_link %}

{{ link.title }}

  {% empty %}
  {% endfor %}

...

I want to put the link inside the  element in base.html. How do I change the code? Thank you.

Body:
You should really read this documentation page:

https://django-adminlte2.readthedocs.io/en/latest/templates_and_blocks.html

Each block is clickable there and there's a detailed description on how to overwrite each one.

For your problem, you will probably nav_footer

{% block nav_footer %}
{{ block.super }}
...
{% endblock %}

{{ block.super }} is optional and will append your content to the block instead of overwriting it.


问:
Creating and Showing Custom Post Types in Wordpress Functions.php
Reading the book http://shop.oreilly.com/product/0636920027508.do and I am on page 511 where we define a custom post type in PHP. Using the code below, its supposed to display the created post type: 'product' on the pages.

Mine is not.

Is that code accurate or am I doing something wrong?

```<code> function create_product_post_type() {
   $labels = array (
      'name' => 'Products', 'singular_name'  => 'Product'
  );

    $args = array (
    'labels'  => $labels,
    'public'  => true,
    'supports'  => array('title', 'editor', 'thumbnail', 'excerpt'),
    'taxonomies' => array( 'category') );
   register_post_type('product', $args );
 }

add_action( 'init', 'create_product_post_type' );

   function add_product_to_archives( $wp_query ) {
       $types_array = array( 'post', 'product');
   if( is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
       set_query_var( 'post_type', $types_array );

  }
}
  add_action('pre_get_posts', 'add_product_to_archives');
</code>```

The book is five years old, and I'm now using the most recent version of WordPress. Do you think this is the issue?

答:
It's possible you're missing some mandatory key for 'register_post_type'. You can check full documentation here: https://developer.wordpress.org/reference/functions/register_post_type/

(I'd recommend you to use Wordpress Codex and Developer Code Reference instead of offline books. Info changes from versions and those are the places to keep it updated):

https://developer.wordpress.org

https://codex.wordpress.org/

Try this code:

```<code>if ( ! function_exists('products_post_type') ) {

// Register Custom Post Type
function products_post_type() {

    $labels = array(
        'name'                  => _x( 'Products', 'Post Type General Name', 'your_text_domain' ),
        'singular_name'         => _x( 'Product', 'Post Type Singular Name', 'your_text_domain' ),
        'menu_name'             => __( 'Products', 'your_text_domain' ),
        'name_admin_bar'        => __( 'Products', 'your_text_domain' ),
        'archives'              => __( 'Products Archives', 'your_text_domain' ),
        'attributes'            => __( 'Products Attributes', 'your_text_domain' ),
        'parent_item_colon'     => __( 'Parent Item:', 'your_text_domain' ),
        'all_items'             => __( 'All Items', 'your_text_domain' ),
        'add_new_item'          => __( 'Add New Item', 'your_text_domain' ),
        'add_new'               => __( 'Add New', 'your_text_domain' ),
        'new_item'              => __( 'New Item', 'your_text_domain' ),
        'edit_item'             => __( 'Edit Item', 'your_text_domain' ),
        'update_item'           => __( 'Update Item', 'your_text_domain' ),
        'view_item'             => __( 'View Item', 'your_text_domain' ),
        'view_items'            => __( 'View Items', 'your_text_domain' ),
        'search_items'          => __( 'Search Item', 'your_text_domain' ),
        'not_found'             => __( 'Not found', 'your_text_domain' ),
        'not_found_in_trash'    => __( 'Not found in Trash', 'your_text_domain' ),
        'featured_image'        => __( 'Featured Image', 'your_text_domain' ),
        'set_featured_image'    => __( 'Set featured image', 'your_text_domain' ),
        'remove_featured_image' => __( 'Remove featured image', 'your_text_domain' ),
        'use_featured_image'    => __( 'Use as featured image', 'your_text_domain' ),
        'insert_into_item'      => __( 'Insert into item', 'your_text_domain' ),
        'uploaded_to_this_item' => __( 'Uploaded to this item', 'your_text_domain' ),
        'items_list'            => __( 'Items list', 'your_text_domain' ),
        'items_list_navigation' => __( 'Items list navigation', 'your_text_domain' ),
        'filter_items_list'     => __( 'Filter items list', 'your_text_domain' ),
    );
    $args = array(
        'label'                 => __( 'Product', 'your_text_domain' ),
        'description'           => __( 'Products', 'your_text_domain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail' ),
        'taxonomies'            => array( 'product_category' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-products',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
        'show_in_rest'          => false,
    );
    register_post_type( 'product', $args );

}
add_action( 'init', 'products_post_type', 0 );

}
</code>```

You should see a menu item in your Dashboard called Products.

It's possible too that you'll need to create a custom taxonomy for Products categories. Give this a try:

```<code>if ( ! function_exists( 'products_category' ) ) {

// Register Custom Taxonomy
function products_category() {

    $labels = array(
        'name'                       => _x( 'Product Categories', 'Taxonomy General Name', 'your_text_domain' ),
        'singular_name'              => _x( 'Product Category', 'Taxonomy Singular Name', 'your_text_domain' ),
        'menu_name'                  => __( 'Category', 'your_text_domain' ),
        'all_items'                  => __( 'All Items', 'your_text_domain' ),
        'parent_item'                => __( 'Parent Item', 'your_text_domain' ),
        'parent_item_colon'          => __( 'Parent Item:', 'your_text_domain' ),
        'new_item_name'              => __( 'New Item Name', 'your_text_domain' ),
        'add_new_item'               => __( 'Add New Item', 'your_text_domain' ),
        'edit_item'                  => __( 'Edit Item', 'your_text_domain' ),
        'update_item'                => __( 'Update Item', 'your_text_domain' ),
        'view_item'                  => __( 'View Item', 'your_text_domain' ),
        'separate_items_with_commas' => __( 'Separate items with commas', 'your_text_domain' ),
        'add_or_remove_items'        => __( 'Add or remove items', 'your_text_domain' ),
        'choose_from_most_used'      => __( 'Choose from the most used', 'your_text_domain' ),
        'popular_items'              => __( 'Popular Items', 'your_text_domain' ),
        'search_items'               => __( 'Search Items', 'your_text_domain' ),
        'not_found'                  => __( 'Not Found', 'your_text_domain' ),
        'no_terms'                   => __( 'No items', 'your_text_domain' ),
        'items_list'                 => __( 'Items list', 'your_text_domain' ),
        'items_list_navigation'      => __( 'Items list navigation', 'your_text_domain' ),
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'show_in_rest'               => false,
    );
    register_taxonomy( 'product_category', array( 'products' ), $args );

}
add_action( 'init', 'products_category', 0 );

}
</code>```

Body:
Reading the book http://shop.oreilly.com/product/0636920027508.do and I am on page 511 where we define a custom post type in PHP. Using the code below, its supposed to display the created post type: 'product' on the pages.

Mine is not.

Is that code accurate or am I doing something wrong?

 function create_product_post_type() {
   $labels = array (
      'name' => 'Products', 'singular_name'  => 'Product'
  );

    $args = array (
    'labels'  => $labels,
    'public'  => true,
    'supports'  => array('title', 'editor', 'thumbnail', 'excerpt'),
    'taxonomies' => array( 'category') );
   register_post_type('product', $args );
 }

add_action( 'init', 'create_product_post_type' );

   function add_product_to_archives( $wp_query ) {
       $types_array = array( 'post', 'product');
   if( is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
       set_query_var( 'post_type', $types_array );

  }
}
  add_action('pre_get_posts', 'add_product_to_archives');

The book is five years old, and I'm now using the most recent version of WordPress. Do you think this is the issue?

Body:
It's possible you're missing some mandatory key for 'register_post_type'. You can check full documentation here: https://developer.wordpress.org/reference/functions/register_post_type/

(I'd recommend you to use Wordpress Codex and Developer Code Reference instead of offline books. Info changes from versions and those are the places to keep it updated):

https://developer.wordpress.org

https://codex.wordpress.org/

Try this code:

if ( ! function_exists('products_post_type') ) {

// Register Custom Post Type
function products_post_type() {

    $labels = array(
        'name'                  => _x( 'Products', 'Post Type General Name', 'your_text_domain' ),
        'singular_name'         => _x( 'Product', 'Post Type Singular Name', 'your_text_domain' ),
        'menu_name'             => __( 'Products', 'your_text_domain' ),
        'name_admin_bar'        => __( 'Products', 'your_text_domain' ),
        'archives'              => __( 'Products Archives', 'your_text_domain' ),
        'attributes'            => __( 'Products Attributes', 'your_text_domain' ),
        'parent_item_colon'     => __( 'Parent Item:', 'your_text_domain' ),
        'all_items'             => __( 'All Items', 'your_text_domain' ),
        'add_new_item'          => __( 'Add New Item', 'your_text_domain' ),
        'add_new'               => __( 'Add New', 'your_text_domain' ),
        'new_item'              => __( 'New Item', 'your_text_domain' ),
        'edit_item'             => __( 'Edit Item', 'your_text_domain' ),
        'update_item'           => __( 'Update Item', 'your_text_domain' ),
        'view_item'             => __( 'View Item', 'your_text_domain' ),
        'view_items'            => __( 'View Items', 'your_text_domain' ),
        'search_items'          => __( 'Search Item', 'your_text_domain' ),
        'not_found'             => __( 'Not found', 'your_text_domain' ),
        'not_found_in_trash'    => __( 'Not found in Trash', 'your_text_domain' ),
        'featured_image'        => __( 'Featured Image', 'your_text_domain' ),
        'set_featured_image'    => __( 'Set featured image', 'your_text_domain' ),
        'remove_featured_image' => __( 'Remove featured image', 'your_text_domain' ),
        'use_featured_image'    => __( 'Use as featured image', 'your_text_domain' ),
        'insert_into_item'      => __( 'Insert into item', 'your_text_domain' ),
        'uploaded_to_this_item' => __( 'Uploaded to this item', 'your_text_domain' ),
        'items_list'            => __( 'Items list', 'your_text_domain' ),
        'items_list_navigation' => __( 'Items list navigation', 'your_text_domain' ),
        'filter_items_list'     => __( 'Filter items list', 'your_text_domain' ),
    );
    $args = array(
        'label'                 => __( 'Product', 'your_text_domain' ),
        'description'           => __( 'Products', 'your_text_domain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail' ),
        'taxonomies'            => array( 'product_category' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-products',
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
        'show_in_rest'          => false,
    );
    register_post_type( 'product', $args );

}
add_action( 'init', 'products_post_type', 0 );

}

You should see a menu item in your Dashboard called Products.

It's possible too that you'll need to create a custom taxonomy for Products categories. Give this a try:

if ( ! function_exists( 'products_category' ) ) {

// Register Custom Taxonomy
function products_category() {

    $labels = array(
        'name'                       => _x( 'Product Categories', 'Taxonomy General Name', 'your_text_domain' ),
        'singular_name'              => _x( 'Product Category', 'Taxonomy Singular Name', 'your_text_domain' ),
        'menu_name'                  => __( 'Category', 'your_text_domain' ),
        'all_items'                  => __( 'All Items', 'your_text_domain' ),
        'parent_item'                => __( 'Parent Item', 'your_text_domain' ),
        'parent_item_colon'          => __( 'Parent Item:', 'your_text_domain' ),
        'new_item_name'              => __( 'New Item Name', 'your_text_domain' ),
        'add_new_item'               => __( 'Add New Item', 'your_text_domain' ),
        'edit_item'                  => __( 'Edit Item', 'your_text_domain' ),
        'update_item'                => __( 'Update Item', 'your_text_domain' ),
        'view_item'                  => __( 'View Item', 'your_text_domain' ),
        'separate_items_with_commas' => __( 'Separate items with commas', 'your_text_domain' ),
        'add_or_remove_items'        => __( 'Add or remove items', 'your_text_domain' ),
        'choose_from_most_used'      => __( 'Choose from the most used', 'your_text_domain' ),
        'popular_items'              => __( 'Popular Items', 'your_text_domain' ),
        'search_items'               => __( 'Search Items', 'your_text_domain' ),
        'not_found'                  => __( 'Not Found', 'your_text_domain' ),
        'no_terms'                   => __( 'No items', 'your_text_domain' ),
        'items_list'                 => __( 'Items list', 'your_text_domain' ),
        'items_list_navigation'      => __( 'Items list navigation', 'your_text_domain' ),
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
        'show_in_rest'               => false,
    );
    register_taxonomy( 'product_category', array( 'products' ), $args );

}
add_action( 'init', 'products_category', 0 );

}


答:
gamesplayed.count direct access wont work following code may help</p>

```<code>var count = parseInt(document.getElementById("gamesplayed").innerHTML)
count += 1;
gamesplayed.innerHTML = "" + count;
</code>```

Body:
gamesplayed.count direct access wont work following code may help

var count = parseInt(document.getElementById("gamesplayed").innerHTML)
count += 1;
gamesplayed.innerHTML = "" + count;


问:
Postfix notation is changing precedence of parentheses in evalution
In a/b*(c+(d-e)) Infix notation (d-e) will be evaluated first but if we convert it into Post-fix ab/cde-+* then ab/ will be evaluated first. </p>

<p>why ab/ is evaluating first in post-fix instead of d-e? </p>

答: Multiplication and division are left-associative, meaning they are evaluated from left to right. Since a and b are terminals (no further evaluation needs to be done), ab/ is ready to be evaluated. Once we get to the last term, c+(d-e), we need to delve deeper and only then do we evaluate de-.

Body:
In a/b*(c+(d-e)) Infix notation (d-e) will be evaluated first but if we convert it into Post-fix ab/cde-+* then ab/ will be evaluated first.

why ab/ is evaluating first in post-fix instead of d-e?


问:
Wrong assembly-references for Silverlight Sketchflow project in Blend 3
In my installation of Blend 3, the SketchStyles are missing when a new project is created. I found out that this is because the following automatic references in the project are wrong:

Microsoft.Expression.Interactions

Microsoft.Expression.Prototyping.Interactivity

Microsoft.Expression.Prototyping.RunTime

Microsoft.Expression.Prototyping.SketchControls

In the project references, these all point to my project path (where they don't live).

If I remove them manually, and instead set the references to ie this: "c:\Program Files (x86)\Microsoft SDKs\Expression\Blend 3\Interactivity\Libraries\Silverlight\Microsoft.Expression.Interactions.dll" everything works.

Any ideas on why, and how to fix this? Could it be the project template somehow?

答:
Very good. The same for Expression Blend 4:</p>

```<code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Silverlight\v4.0\AssemblyFoldersEx\Expression Blend

C:\Program Files\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Silverlight\v4.0\AssemblyFoldersEx\Expression SketchFlow

C:\Program Files\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Prototyping\Libraries
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Very good. The same for Expression Blend 4:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Silverlight\v4.0\AssemblyFoldersEx\Expression Blend

C:\Program Files\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Libraries

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Silverlight\v4.0\AssemblyFoldersEx\Expression SketchFlow

C:\Program Files\Microsoft SDKs\Expression\Blend\Silverlight\v4.0\Prototyping\Libraries


问:
QT4 How to blur QPixmap image?
QT4 How to blur QPixmap image?

I am looking for something like one of the following:

```<code>Blur(pixmap);
painter.Blur();
painter.Blur(rect);
</code>```

What is the best way to do this?

答:
Add python code based on @Петър Петров answer for QT 5.</p>

```<code>def applyEffectToImage(src, effect):
    scene = QGraphicsScene()
    item = QGraphicsPixmapItem()
    item.setPixmap(QPixmap.fromImage(src))
    item.setGraphicsEffect(effect)
    scene.addItem(item)
    res = QImage(src.size(), QImage.Format_ARGB32)
    res.fill(Qt.transparent)
    ptr = QPainter(res)
    scene.render(ptr, QRectF(), QRectF(0,0, src.width(), src.height()) )
    return res

blur = QGraphicsBlurEffect()
blur.setBlurRadius(8)
source = QImage(r"C:\Users\fran\Desktop\test.png")
result = applyEffectToImage(source, blur)
result.save(r"C:\Users\fran\Desktop\result.png")
</code>```

ContentLicense: CC BY-SA 2.5

Title: QT4 How to blur QPixmap image?

Body:
QT4 How to blur QPixmap image?

I am looking for something like one of the following:

Blur(pixmap);
painter.Blur();
painter.Blur(rect);

What is the best way to do this?

Body:
Add python code based on @Петър Петров answer for QT 5.

def applyEffectToImage(src, effect):
    scene = QGraphicsScene()
    item = QGraphicsPixmapItem()
    item.setPixmap(QPixmap.fromImage(src))
    item.setGraphicsEffect(effect)
    scene.addItem(item)
    res = QImage(src.size(), QImage.Format_ARGB32)
    res.fill(Qt.transparent)
    ptr = QPainter(res)
    scene.render(ptr, QRectF(), QRectF(0,0, src.width(), src.height()) )
    return res

blur = QGraphicsBlurEffect()
blur.setBlurRadius(8)
source = QImage(r"C:\Users\fran\Desktop\test.png")
result = applyEffectToImage(source, blur)
result.save(r"C:\Users\fran\Desktop\result.png")


问:
How can I create a new column for each item in another column?
I have a column called test and it is composed by numbers from 1 to 6

```<code>test
[1,1,1,2,2,3,6]
</code>```

I want to count the numbers and make for each a new column

```<code>test                01  02   03   04   05   06
[1,1,1,2,2,3,6] => [3]  [2]  [1]  [0]  [0]  [1]

</code>```

I add an image to make it more clear

答:
You can use Counter:

```<code>from collections import Counter

test = [1,1,1,2,2,3,6]
result = Counter(test)

print(result)
</code>```

The output is a dictionary with the value as key and occurrences as value:

```<code>Counter({1: 3,
         2: 2,
         3: 1,
         6: 1})
</code>```

Edit (answer to the comment):

As explained here (How to add the missing keys in this dictionary with values as empty string using python) you can add missing keys with value 0 very simply:

```<code>max_value = max(result.keys()) + 1
result.update(dict.fromkeys(set(range(1,max_value)).difference(result), 0))

print(result)
</code>```

Here max_value denote the max value of the keys in the dictionary. The output will be:

```<code>Counter({1: 3,
         2: 2,
         3: 1,
         6: 1,
         4: 0,
         5: 0})
</code>```

Body:
I have a column called test and it is composed by numbers from 1 to 6

test
[1,1,1,2,2,3,6]

I want to count the numbers and make for each a new column

test                01  02   03   04   05   06
[1,1,1,2,2,3,6] => [3]  [2]  [1]  [0]  [0]  [1]

I add an image to make it more clear

Body:
You can use Counter:

from collections import Counter

test = [1,1,1,2,2,3,6]
result = Counter(test)

print(result)

The output is a dictionary with the value as key and occurrences as value:

Counter({1: 3,
         2: 2,
         3: 1,
         6: 1})

Edit (answer to the comment):

As explained here (How to add the missing keys in this dictionary with values as empty string using python) you can add missing keys with value 0 very simply:

max_value = max(result.keys()) + 1
result.update(dict.fromkeys(set(range(1,max_value)).difference(result), 0))

print(result)

Here max_value denote the max value of the keys in the dictionary. The output will be:

Counter({1: 3,
         2: 2,
         3: 1,
         6: 1,
         4: 0,
         5: 0})


问:
What units to pass UI methods?
Reading the Supporting Multiple Screens of the Android developer guide it says it is always best to use density independent pixels (dp) instead of pixels and it also says Android handles most of the application rendering on different density devices.

Now my question is, if we look at the padding function of the View class

setPadding (int left, int top, int
  right, int bottom)

```<code>left     the left padding in pixels
top       the top padding in pixels
right   the right padding in pixels
bottom    the bottom padding in pixels
</code>```

When I use this function is it alright to pass direct values or do I have to pass converted values, from dp to px, to best show the UI in all devices?

答:
Check out this padding reference and search for android:padding

It looks like you will need to convert from dip to pixels to set the padding.  You should convert the values from dip to pixels so that it works correctly on different devices.

Title: What units to pass UI methods?

Body:
Reading the Supporting Multiple Screens of the Android developer guide it says it is always best to use density independent pixels (dp) instead of pixels and it also says Android handles most of the application rendering on different density devices.

Now my question is, if we look at the padding function of the View class

setPadding (int left, int top, int
  right, int bottom)

left     the left padding in pixels
top       the top padding in pixels
right   the right padding in pixels
bottom    the bottom padding in pixels

When I use this function is it alright to pass direct values or do I have to pass converted values, from dp to px, to best show the UI in all devices?


问:
Allow "Special Characters" in C language on Windows
If I execute this code (compiled with command
gcc accents.c -o accents && cls && accents)
on Linux DEB (like Debian or Ubuntu), all works fine.

If I execute this code on Windows 10, it no detect Special Characters.

How I can allow special characters (Like "Àlex", that À) to work fine code on Windows?

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

void NetejaBuffer(){ while(getchar() != '\n'); }

int comparaCadena(char p1[],char p2[]){
    int i=0;
    while (p1[i]!='\0'){
            if (p1[i]!=p2[i]) return 0;
            i++;
    }
    return 1;
}

int main (){
    char Paraula1[30]="Àlex"; // Define Main Word: Àlex
    char Paraula2[30]; // Define variable for Second Word
    int i=0; // Define no go to the next step beafoure writte Main Word
    while (i==0){
            printf(" Main Word:  "); // Show text "Main Word" on terminal
            scanf("%[^\n]",Paraula2);       // Ask a word. It will save on "Paraula2" variable
            NetejaBuffer();

            if(comparaCadena(Paraula1,Paraula2)) {
                    printf(" NICE! \n "); // If word are the same on Main Word, show text "NICE!"
                    i=1; // And define variable i as 1
            }else printf("TRY AGAIN! \n "); // If word are no the same, show text "TRY AGAIN!"

    }

    return 0;
}
</code>```

答:
À is not a special character.If you observe the ASCII values you will find this character
get through this link
https://theasciicode.com.ar/extended-ascii-code/letter-a-grave-accent-lowercase-ascii-code-133.html</p>

Body:
If I execute this code (compiled with command
gcc accents.c -o accents && cls && accents)
on Linux DEB (like Debian or Ubuntu), all works fine.

If I execute this code on Windows 10, it no detect Special Characters.

How I can allow special characters (Like "Àlex", that À) to work fine code on Windows?

#include <stdio.h>

void NetejaBuffer(){ while(getchar() != '\n'); }

int comparaCadena(char p1[],char p2[]){
    int i=0;
    while (p1[i]!='\0'){
            if (p1[i]!=p2[i]) return 0;
            i++;
    }
    return 1;
}

int main (){
    char Paraula1[30]="Àlex"; // Define Main Word: Àlex
    char Paraula2[30]; // Define variable for Second Word
    int i=0; // Define no go to the next step beafoure writte Main Word
    while (i==0){
            printf(" Main Word:  "); // Show text "Main Word" on terminal
            scanf("%[^\n]",Paraula2);       // Ask a word. It will save on "Paraula2" variable
            NetejaBuffer();

            if(comparaCadena(Paraula1,Paraula2)) {
                    printf(" NICE! \n "); // If word are the same on Main Word, show text "NICE!"
                    i=1; // And define variable i as 1
            }else printf("TRY AGAIN! \n "); // If word are no the same, show text "TRY AGAIN!"

    }

    return 0;
}


问:
MediumText and textArea in my form show.blade
I need your help because I am stuck... I should create a form with a text long.

In my function up(), I have this

```<code>$table->mediumText('resume');
</code>```

In my page create.blade.php, the create works.

```<code><fieldset class="form-group {{ $errors->has('resume') ? 'has-error' : '' }}">
    <label for="form-group-input-1">Résumé</label>
    <textarea name="resume" id="resume" class="form-control" required="required" value="{{ old('resume')}}"/></textarea>
    {!! $errors->first('resume', '<span class="help-block">:message</span>') !!}
</fieldset>
</code>```

However, I don't get the value (the text) on my page show.blade.php

```<code><fieldset class="form-group">
   <label for="form-group-input-1">Résumé</label>
   <textarea name="resume" class="form-control" id="form-group-input-1" readonly="true" value="{{$livres->resume}}"/></textarea>
</fieldset>
</code>```

If I don't use textarea but input type=text it works.

Do you have an idea please?

答:
Change your code like this (textarea does not get value):</p>

```<code><textarea name="resume" class="form-control" id="form-group-input-1" readonly="true"/>{{$livres->resume}}</textarea>
</code>```

Body:
I need your help because I am stuck... I should create a form with a text long.

In my function up(), I have this

$table->mediumText('resume');

In my page create.blade.php, the create works.

<fieldset class="form-group {{ $errors->has('resume') ? 'has-error' : '' }}">
    Résumé
    <textarea name="resume" id="resume" class="form-control" required="required" value="{{ old('resume')}}"/></textarea>
    {!! $errors->first('resume', ':message') !!}
</fieldset>

However, I don't get the value (the text) on my page show.blade.php

<fieldset class="form-group">
   Résumé
   <textarea name="resume" class="form-control" id="form-group-input-1" readonly="true" value="{{$livres->resume}}"/></textarea>
</fieldset>

If I don't use textarea but input type=text it works.

Do you have an idea please?

Body:
Change your code like this (textarea does not get value):

<textarea name="resume" class="form-control" id="form-group-input-1" readonly="true"/>{{$livres->resume}}</textarea>


问:
Using SQL(ite) how do I find the lowest unique child for each parent in a one to many relationship during a JOIN?
I have two tables with a many to one relationship which represent lots and bids within an auction system. Each lot can have zero or more bids associated with it. Each bid is associated with exactly one lot.

My table structure (with irrelevant fields removed) looks something like this:

For one type of auction the winning bid is the lowest unique bid for a given lot.

E.g. if there are four bids for a given lot: [1, 1, 2, 4] the lowest unique bid is 2 (not 1).

So far I have been able to construct a query which will find the lowest unique bid for a single specific lot (assuming the lot ID is 123):

```<code>SELECT id, value FROM bid
WHERE lot = 123
AND amount = (
    SELECT value FROM bid
    WHERE lot = 123
    GROUP BY value HAVING COUNT(*) = 1
    ORDER BY value
)
</code>```

This works as I would expect (although I'm not sure it's the most graceful approach).

I would now like to construct a query which will get the lowest unique bids for all lots at once. Essentially I want to perform a JOIN on the two tables where one column is the result of something similar to the above query. I'm at a loss as to how to use the same approach for finding the lowest unique bid in a JOIN though.

Am I on the wrong track with this approach to finding the lowest unique bid? Is there another way I can achieve the same result?

Can anyone help me expand this query into a JOIN?

Is this even possible in SQL or will I have to do it in my application proper?

Thanks in advance.

(I am using SQLite 3.5.9 as found in Android 2.1)

答:
```<code>SELECT lot.name, ( SELECT MIN(bid.value) FROM bid Where bid.lot = lot.ID) AS MinBid
FROM Lot INNER JOIN
    bid on lot.ID = bid.ID
</code>```

If I understand you correctly this will give you everylot and their smallest bid

Body:
I have two tables with a many to one relationship which represent lots and bids within an auction system. Each lot can have zero or more bids associated with it. Each bid is associated with exactly one lot.

My table structure (with irrelevant fields removed) looks something like this:

For one type of auction the winning bid is the lowest unique bid for a given lot.

E.g. if there are four bids for a given lot: [1, 1, 2, 4] the lowest unique bid is 2 (not 1).

So far I have been able to construct a query which will find the lowest unique bid for a single specific lot (assuming the lot ID is 123):

SELECT id, value FROM bid
WHERE lot = 123
AND amount = (
    SELECT value FROM bid
    WHERE lot = 123
    GROUP BY value HAVING COUNT(*) = 1
    ORDER BY value
)

This works as I would expect (although I'm not sure it's the most graceful approach).

I would now like to construct a query which will get the lowest unique bids for all lots at once. Essentially I want to perform a JOIN on the two tables where one column is the result of something similar to the above query. I'm at a loss as to how to use the same approach for finding the lowest unique bid in a JOIN though.

Am I on the wrong track with this approach to finding the lowest unique bid? Is there another way I can achieve the same result?

Can anyone help me expand this query into a JOIN?

Is this even possible in SQL or will I have to do it in my application proper?

Thanks in advance.

(I am using SQLite 3.5.9 as found in Android 2.1)

Body:
SELECT lot.name, ( SELECT MIN(bid.value) FROM bid Where bid.lot = lot.ID) AS MinBid
FROM Lot INNER JOIN
    bid on lot.ID = bid.ID

If I understand you correctly this will give you everylot and their smallest bid


问:
In Keras, how to get 3D input and 3D output for LSTM layers
In my original setting, I got

```<code>X1 = (1200,40,1)
y1 = (1200,10)
</code>```

Then, I work perfectly with my codes:

```<code>model = Sequential()
model.add(LSTM(12, input_shape=(40, 1), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense(10)))
</code>```

Now, I further got another time series data same sizes as X1 and y1. i.e.,

```<code>X2 = (1200,40,1)
y2 = (1200,10)
</code>```

Now, I stack X1, X2 and y1, y2 as 3D arrays:

```<code>X_stack = (1200,40,2)
y_stack = (1200,10,2)
</code>```

Then, I try to modify my keras code like:

```<code>model = Sequential()
model.add(LSTM(12, input_shape=(40, 2), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense((10,2))))
</code>```

I want my code work directly with the 3D arrays X_stack and y_stack without reshaping them as 2D arrays. Would you give me a hand on how to modify the settings? Thank you.

答:
i can not give a short answer to this question however i think there is clarification needed about some basic concepts of LSTM (one-to-one, one-to-many,...)

As a superstructure RNNs (including LSTMs) are sequential, they are constructed to find time-like correlations,  while CNNs are spatial they are build to find space-like correlations

Then there is a further differentiation of LSTM in one-to-one, one-to-many, many-to-one and many-to-many like shown in Many to one and many to many LSTM examples in Keras

The network type that is wanted here is point 5 in Many to one and many to many LSTM examples in Keras and it says :

Many-to-many when number of steps differ from input/output length: this is freaky hard in Keras. There are no easy code snippets to code that.

It is type 5 because input shape is  X_stack = (1200,40,2)
and output shape is y_stack = (1200,10,2) so the number of timesteps differ (40 input and 10 output)

If you could manage to have an equal number of input and output timesteps you can reshape input and output data (numpy.reshape) like in keras LSTM feeding input with the right shape ( note the arrangement of the [ and ] in the arrays). This does not mean reshaping to 2D ( i.e. flattening ).
In https://machinelearningmastery.com/timedistributed-layer-for-long-short-term-memory-networks-in-python/ is a complete example for building a many-to-many LSTM with equal input and output timesteps using TimeDistributed layer

Only for completeness, for spatio-temporal data there are also CNN-LSTMs however this does not apply here because two stacked timeseries have no explicit spatial correlations  :

If you have a 3D quantity, i.e. a distribution in a volume that changes over time and want to learn this then you have to use a CNN-LSTM network. In this approach both the 3D information and the temporal information is preserved. With 3D information is preserved is meant that the spatial information is not discarded. Normally in time-like learners like LSTM this spatial information is often discarded i.e. by flattening an image before processing it in an LSTM.
A complete tutorial how a (spatio-temporal) CNN-LSTM can be built in keras is in https://machinelearningmastery.com/cnn-long-short-term-memory-networks/

Body:
In my original setting, I got

X1 = (1200,40,1)
y1 = (1200,10)

Then, I work perfectly with my codes:

model = Sequential()
model.add(LSTM(12, input_shape=(40, 1), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense(10)))

Now, I further got another time series data same sizes as X1 and y1. i.e.,

X2 = (1200,40,1)
y2 = (1200,10)

Now, I stack X1, X2 and y1, y2 as 3D arrays:

X_stack = (1200,40,2)
y_stack = (1200,10,2)

Then, I try to modify my keras code like:

model = Sequential()
model.add(LSTM(12, input_shape=(40, 2), return_sequences=True))
model.add(LSTM(12, return_sequences=True))
model.add(LSTM(6, return_sequences=False))
model.add((Dense((10,2))))

I want my code work directly with the 3D arrays X_stack and y_stack without reshaping them as 2D arrays. Would you give me a hand on how to modify the settings? Thank you.


问:
How to send input to servlet but not from action?
I've got a form that I use to post some inputs to one site but I want to post them also to my servlet - is it even possible?

I've tried to do something with submit button, I mean executing onclick with function but something is not working properly

```<code>            <input type="submit" value="value1" onclick="afterSubmit()"/>
...some inputs...
        </form>
</code>```

```<code>            form=document.getElementById("${initParam['posturl']}";
            function afterSubmit() {
                form.action="http://localhost:8080/url/servlet";
            }
        </script>
</code>```

And my servlet:

```<code>public class sendThis extends HttpServlet {

    public void doPost(HttpServletRequest request,
            HttpServletResponse response)   throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        out.println(request.getParameter("item_name_1"));
    }
}```

So when I click on submit button and then go to localhost:8080/url/servlet, I get this error:

HTTP Status 405 – Method Not Allowed

Type Status Report
Message HTTP method GET is not supported by this URL
Description The method received in the request-line is known by the origin server but not supported by the target resource.
```

答:
Add doGet method to your servlet and handle the request:

```<code>protected void doGet(HttpServletRequest request,
            HttpServletResponse response)   throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println(request.getParameter("item_name_1"));
}
</code>```

Body:
I've got a form that I use to post some inputs to one site but I want to post them also to my servlet - is it even possible?

I've tried to do something with submit button, I mean executing onclick with function but something is not working properly

            <input type="submit" value="value1" onclick="afterSubmit()"/>
...some inputs...
        </form>

            form=document.getElementById("${initParam['posturl']}";
            function afterSubmit() {
                form.action="http://localhost:8080/url/servlet";
            }
        </script>

And my servlet:

public class sendThis extends HttpServlet {

    public void doPost(HttpServletRequest request,
            HttpServletResponse response)   throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        out.println(request.getParameter("item_name_1"));
    }
}```

So when I click on submit button and then go to localhost:8080/url/servlet, I get this error:

HTTP Status 405 – Method Not Allowed

Type Status Report
Message HTTP method GET is not supported by this URL
Description The method received in the request-line is known by the origin server but not supported by the target resource.

Body:
Add doGet method to your servlet and handle the request:

protected void doGet(HttpServletRequest request,
            HttpServletResponse response)   throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println(request.getParameter("item_name_1"));
}


问:
@BasePathAwareController Exception: could not initialize proxy - no Session

@BasePathAwareController
public class MetricController {

    @Autowired
    private MetricRepository metricRepository;

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/metrics/in/{id}")
    public @ResponseBody
    MetricDTO getMetric(@PathVariable Long id) {
        return MetricDTO.fromEntity(metricRepository.getOne(id));
    }
}

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(
        uniqueConstraints = @UniqueConstraint(columnNames = {"metricType", "instanceType"}, name = "customUniqueId")
)
public class Metric implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(unique = true)
    private String name;
    private SourceType sourceType;
    private String metricTypeField;
    private String metricType;
    private String instanceType;
    private String instanceTypeField;
    @ElementCollection
    private List<String> metricIdFields;
    @ElementCollection
    private List<String> valueFields;
    @ElementCollection
    private Map<String, String> virtualFieldValueEx;
}

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class MetricDTO {
    private SourceType sourceType;
    private String metricTypeField;
    private String metricType;
    private String instanceType;
    private String instanceTypeField;
    private List<String> metricIdFields;
    private List<String> valueFields;
    private Map<String, String> virtualFieldValueEx;

    public static MetricDTO fromEntity(Metric metric) {
        return new MetricDTO(
                metric.getSourceType(),
                metric.getMetricTypeField(),
                metric.getMetricType(),
                metric.getInstanceType(),
                metric.getInstanceTypeField(),
                metric.getMetricIdFields(),
                metric.getValueFields(),
                metric.getVirtualFieldValueEx()
        );
    }
}
```

<p>Since @RepositoryRestController in Spring Data Rest is not compatible with Swagger, I changed it to @BasePathAwareController.</p>

<p>So, the problem is that the controller is not working properly.</p>

<p>The error history is as follows.</p>

<pre class="lang-java prettyprint-override"><code>Could not write JSON: failed to lazily initialize a collection of role: com.jmsight.management.entity.Metric.metricIdFields, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.jmsight.management.entity.Metric.metricIdFields, could not initialize proxy - no Session (through reference chain: com.jmsight.management.dto.MetricDTO["metricIdFields"])
</code>```

Using @RepositoryRestController works normally.
What is the problem? Is it resolvable?

答:
If you check the source of @BasePathAwareController then you can see that it's not annotated with @Controller.
So if a class is annotated only with @BasePathAwareController then it won't be picked neither by the default SpringMvc neither RepositoryRestMvc.

The former picks classes annotated with @Controller or @RequestMapping, the latter picks only classes annotated with @RepositoryRestController.

So once again, just to make it clear: @BasePathAwareController is NOT an 'extension' of @Controller, it's just a additional 'sign' annotation.
You can use @Controller together with @BasePathAwareController instead of @RequestMapping too.

I believe it's a misleading naming, or simply a bug in the implementation.

One more thing.
If you switch the from @RepositoryRestController to @Controller/@RequestMapping, then your controller will be handled a completely different way.
It could look that it works the same way, but it's called by a completely different handlerMapping: which uses different converters, argumentResolvers, even a different objectMapper.

There could be unpleasant surprises if you need to implement more complicated handler-methods in your controller-class.

Body:
@BasePathAwareController
public class MetricController {

    @Autowired
    private MetricRepository metricRepository;

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/metrics/in/{id}")
    public @ResponseBody
    MetricDTO getMetric(@PathVariable Long id) {
        return MetricDTO.fromEntity(metricRepository.getOne(id));
    }
}

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(
        uniqueConstraints = @UniqueConstraint(columnNames = {"metricType", "instanceType"}, name = "customUniqueId")
)
public class Metric implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(unique = true)
    private String name;
    private SourceType sourceType;
    private String metricTypeField;
    private String metricType;
    private String instanceType;
    private String instanceTypeField;
    @ElementCollection
    private List<String> metricIdFields;
    @ElementCollection
    private List<String> valueFields;
    @ElementCollection
    private Map<String, String> virtualFieldValueEx;
}

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class MetricDTO {
    private SourceType sourceType;
    private String metricTypeField;
    private String metricType;
    private String instanceType;
    private String instanceTypeField;
    private List<String> metricIdFields;
    private List<String> valueFields;
    private Map<String, String> virtualFieldValueEx;

    public static MetricDTO fromEntity(Metric metric) {
        return new MetricDTO(
                metric.getSourceType(),
                metric.getMetricTypeField(),
                metric.getMetricType(),
                metric.getInstanceType(),
                metric.getInstanceTypeField(),
                metric.getMetricIdFields(),
                metric.getValueFields(),
                metric.getVirtualFieldValueEx()
        );
    }
}

Since @RepositoryRestController in Spring Data Rest is not compatible with Swagger, I changed it to @BasePathAwareController.

So, the problem is that the controller is not working properly.

The error history is as follows.

Could not write JSON: failed to lazily initialize a collection of role: com.jmsight.management.entity.Metric.metricIdFields, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.jmsight.management.entity.Metric.metricIdFields, could not initialize proxy - no Session (through reference chain: com.jmsight.management.dto.MetricDTO["metricIdFields"])

Using @RepositoryRestController works normally.
What is the problem? Is it resolvable?


问:
What information is stored in a context area in plsql?
I learnt that context area in oracle is a private memory space where information needed for processing SQL statements are stored. However, I didn't get anywhere knowledge about what information is stored there.</p>

答:
Oracle has a default context named 'userenv' which stores a great deal of information about the session. We can access the information using sys_context(). For instance, to get the database name...

```<code>select sys_context('USERENV', 'DB_NAME') from dual;
</code>```

All of the valid parameters are listed in the SQL Reference for sys_context here.

Some very useful parameters are 'ACTION', 'MODULE' and 'CLIENT_INFO'. These fields are populated through dbms_application_info calls, which allows us to pass information between programs.

However, we can extend this capability further by defining out own context namespaces. This requires the CREATE CONTEXT privilege (by default only available to DBA users). Programs write to and read from context using dbms_session calls. With our own context namespace we can stash bespoke information in session memory. Fine-Grained Access control (row-level and column security) relies on this feature. So there's a lot more about contexts in the Security Guide.

Body:
Oracle has a default context named 'userenv' which stores a great deal of information about the session. We can access the information using sys_context(). For instance, to get the database name...

select sys_context('USERENV', 'DB_NAME') from dual;

All of the valid parameters are listed in the SQL Reference for sys_context here.

Some very useful parameters are 'ACTION', 'MODULE' and 'CLIENT_INFO'. These fields are populated through dbms_application_info calls, which allows us to pass information between programs.

However, we can extend this capability further by defining out own context namespaces. This requires the CREATE CONTEXT privilege (by default only available to DBA users). Programs write to and read from context using dbms_session calls. With our own context namespace we can stash bespoke information in session memory. Fine-Grained Access control (row-level and column security) relies on this feature. So there's a lot more about contexts in the Security Guide.


问:
How can I get my map legend to populate with an outside dataset?
I am trying to display a map legend with sized circles using an outside dataset file, but the legend is not displaying the actual information needed.

It seems to work if I make an array of data within the JS code, but I need it to work with the .js file that I'm pulling from.

The JavaScript I'm utilizing is below:

```<code>var map;

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {
        lat: 27.964157,
        lng: -82.452606
    },
    mapTypeControl: false,
    streetViewControl: false,
    //    mapTypeId: 'terrain',
    //     disableDefaultUI: true,
    //      gestureHandling: 'none',
    //          zoomControl: false,

});

var script = document.createElement('script');

script.src = 'https://trialscout.com/Scripts/landscapedata/tampadata_geojsonp.js';
document.getElementsByTagName('head')[0].appendChild(script);

map.data.setStyle(function (feature) {
    var nctcount = feature.getProperty('count_of_nct_id');
    return {
        icon: getCircle(nctcount)
    };
});

var icons = [];

var legend = document.getElementById('legend');
for (var key in icons) {
var type = icons[key];
var name = type.name;
var icon = type.icon;
var scale = type.scale;
var opacity = type.fillOpacity;
var div = document.createElement('div');
div.innerHTML = "<img src='data:image/svg+xml;utf8,<svg viewBox=\"0 0 100 100\" height=\"" + 8 * scale / 8 + "\" width=\"" + 8 * scale / 8 + "\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"50\" style=\"fill: green; stroke: white; stroke-width: 1;\" opacity=\"" + opacity + "\"/></svg>'> " + name;
legend.appendChild(div);
}

  map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);

}

function getCircle(nctcount) {
var nctamt = nctcount;
if (nctamt <= 10) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: 1,
        fillColor: 'green',
        scale: 5,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 10"
    };
}

else if (nctamt <= 100) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .8,
        fillColor: 'green',
        scale: 10,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 100"
    };
}

else if (nctamt <= 250) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .6,
        fillColor: 'green',
        scale: 15,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 250"
    };
}

else if (nctamt <= 500) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .4,
        fillColor: 'green ',
        scale: 20,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 500"
    };
}

else if (nctamt <= 2000) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .2,
        fillColor: 'green',
        scale: 25,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 2000"
    };
}

else {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .2,
        fillColor: 'green',
        scale: 35,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "> 2000"
    };
}

}

function tslandscape_callback(response) {
map.data.addGeoJson(response);
}
</code>```

My Fiddle for the project is here: https://jsfiddle.net/Strawmr/uoc8vwhf/7/

答:
One option would be to use the code from my answer to your earlier question, and make a function that creates a fixed legend (rather than trying to generate it dynamically from your data).

```<code>function makeLegend(map) {
  var legendmap = {
    scale1: {population: 8},
    scale2: {population: 80},
    scale3: {population: 200},
    scale4: {population: 450},
    scale5: {population: 1900},
    scale6: {population: 5000}
  };
  var icons = [];
  // Construct the circle for each value in legendmap.
  // Note: We scale the area of the circle based on the population.
  for (var entry in legendmap) {
    // Add the circle for this entry to the map.
    var icon = getCircle(legendmap[entry].population);
    if (!icons[icon.scale])
      icons[icon.scale] = icon;
  }

  var legend = document.getElementById('legend');
  for (var key in icons) {
    var type = icons[key];
    var name = type.name;
    var icon = type.icon;
    var scale = type.scale;
    var opacity = type.fillOpacity;
    var div = document.createElement('div');
    div.innerHTML = "<img src='data:image/svg+xml;utf8,<svg viewBox=\"0 0 100 100\" height=\"" + 8 * scale / 8 + "\" width=\"" + 8 * scale / 8 + "\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"50\" style=\"fill: green; stroke: white; stroke-width: 1;\" opacity=\"" + opacity + "\"/></svg>'> " + name;
    legend.appendChild(div);
  }
  // add the created legend to the map
  map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
}
</code>```

proof of concept fiddle

code snippet

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {
      lat: 27.964157,
      lng: -82.452606
    },
    mapTypeControl: false,
    streetViewControl: false,
    styles: styles,
  });

  var script = document.createElement('script');
  script.src = 'https://trialscout.com/Scripts/landscapedata/tampadata_geojsonp.js';
  document.getElementsByTagName('head')[0].appendChild(script);

  map.data.setStyle(function(feature) {
    var nctcount = feature.getProperty('count_of_nct_id');
    return {
      icon: getCircle(nctcount)
    };
  });

  makeLegend(map);
}

function getCircle(nctcount) {
  var nctamt = nctcount;
  if (nctamt <= 10) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 1,
      fillColor: 'green',
      scale: 5,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 10"
    };
  } else if (nctamt <= 100) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.8,
      fillColor: 'green',
      scale: 10,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 100"
    };
  } else if (nctamt <= 250) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.6,
      fillColor: 'green',
      scale: 15,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 250"
    };
  } else if (nctamt <= 500) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.4,
      fillColor: 'green ',
      scale: 20,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 500"
    };
  } else if (nctamt <= 2000) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.2,
      fillColor: 'green',
      scale: 25,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 2000"
    };
  } else {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.2,
      fillColor: 'green',
      scale: 35,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "> 2000"
    };
  }

}

function tslandscape_callback(response) {
  map.data.addGeoJson(response);
}

function makeLegend(map) {
  // entries in the legend
  var legendmap = {
    scale1: {population: 8},
    scale2: {population: 80},
    scale3: {population: 200},
    scale4: {population: 450},
    scale5: {population: 1900},
    scale6: {population: 5000}
  };
  var icons = [];
  // Construct the circle for each value in legendmap.
  // Note: We scale the area of the circle based on the population.
  for (var entry in legendmap) {
    // Add the circle for this entry to the map.
    var circle = getCircle(legendmap[entry].population);
    if (!icons[circle.scale])
      icons[circle.scale] = circle;
  }

  var legend = document.getElementById('legend');
  for (var key in icons) {
    var type = icons[key];
    var name = type.name;
    var icon = type.icon;
    var scale = type.scale;
    var opacity = type.fillOpacity;
    var div = document.createElement('div');
    div.innerHTML = "<img src='data:image/svg+xml;utf8,<svg viewBox=\"0 0 100 100\" height=\"" + 8 * scale / 8 + "\" width=\"" + 8 * scale / 8 + "\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"50\" style=\"fill: green; stroke: white; stroke-width: 1;\" opacity=\"" + opacity + "\"/></svg>'> " + name;
    legend.appendChild(div);
  }
  // add the created legend to the map
  map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
}
var styles = [{
  "featureType": "all",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#ff0000"
  }]
}, {
  "featureType": "administrative",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "administrative",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#06262d"
  }]
}, {
  "featureType": "administrative.country",
  "elementType": "labels",
  "stylers": [{
    "visibility": "off"
  }]
}, {
  "featureType": "administrative.locality",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#085c66"
  }]
}, {
  "featureType": "administrative.neighborhood",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#7ca7ad"
  }, {
    "visibility": "on"
  }]
}, {
  "featureType": "landscape",
  "elementType": "all",
  "stylers": [{
    "color": "#f2f2f2"
  }]
}, {
  "featureType": "landscape",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#f7f8f9"
  }]
}, {
  "featureType": "landscape",
  "elementType": "labels.text",
  "stylers": [{
    "visibility": "on"
  }]
}, {
  "featureType": "landscape",
  "elementType": "labels.text.fill",
  "stylers": [{
    "visibility": "simplified"
  }, {
    "color": "#ff0000"
  }]
}, {
  "featureType": "landscape.natural.terrain",
  "elementType": "labels.text.fill",
  "stylers": [{
    "visibility": "simplified"
  }]
}, {
  "featureType": "poi",
  "elementType": "all",
  "stylers": [{
    "visibility": "off"
  }]
}, {
  "featureType": "poi.park",
  "elementType": "geometry",
  "stylers": [{
    "visibility": "on"
  }, {
    "color": "#e3ece7"
  }]
}, {
  "featureType": "road",
  "elementType": "all",
  "stylers": [{
    "saturation": -100
  }, {
    "lightness": 45
  }]
}, {
  "featureType": "road.highway",
  "elementType": "all",
  "stylers": [{
    "visibility": "simplified"
  }]
}, {
  "featureType": "road.highway",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "road.highway",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#0a5d66"
  }]
}, {
  "featureType": "road.highway",
  "elementType": "labels.icon",
  "stylers": [{
    "visibility": "on"
  }, {
    "hue": "#00e8ff"
  }, {
    "saturation": "22"
  }, {
    "gamma": "1"
  }]
}, {
  "featureType": "road.arterial",
  "elementType": "geometry.stroke",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "road.arterial",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#7ca7ad"
  }]
}, {
  "featureType": "road.arterial",
  "elementType": "labels.icon",
  "stylers": [{
    "visibility": "off"
  }]
}, {
  "featureType": "road.local",
  "elementType": "geometry.stroke",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "road.local",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#afc6c6"
  }]
}, {
  "featureType": "road.local",
  "elementType": "labels.icon",
  "stylers": [{
    "visibility": "simplified"
  }]
}, {
  "featureType": "transit",
  "elementType": "all",
  "stylers": [{
    "visibility": "off"
  }]
}, {
  "featureType": "transit.station.airport",
  "elementType": "all",
  "stylers": [{
    "visibility": "on"
  }]
}, {
  "featureType": "transit.station.airport",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "transit.station.airport",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#0a5d66"
  }]
}, {
  "featureType": "water",
  "elementType": "all",
  "stylers": [{
    "color": "#46bcec"
  }, {
    "visibility": "on"
  }]
}, {
  "featureType": "water",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#afc6c6"
  }]
}, {
  "featureType": "water",
  "elementType": "labels.text",
  "stylers": [{
    "color": "#0a5d66"
  }]
}]```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

#map {
  height: 100%;
  width: 100%;
}

#legend {
  font-family: Arial, sans-serif;
  background: #fff;
  padding: 10px;
  margin: 10px;
  border: 3px solid #000;
}

#legend h3 {
  margin-top: 0;
}

#legend img {
  vertical-align: middle;
}</code>```

```

Body:
I am trying to display a map legend with sized circles using an outside dataset file, but the legend is not displaying the actual information needed.

It seems to work if I make an array of data within the JS code, but I need it to work with the .js file that I'm pulling from.

The JavaScript I'm utilizing is below:

var map;

function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {
        lat: 27.964157,
        lng: -82.452606
    },
    mapTypeControl: false,
    streetViewControl: false,
    //    mapTypeId: 'terrain',
    //     disableDefaultUI: true,
    //      gestureHandling: 'none',
    //          zoomControl: false,

});

var script = document.createElement('script');

script.src = 'https://trialscout.com/Scripts/landscapedata/tampadata_geojsonp.js';
document.getElementsByTagName('head')[0].appendChild(script);

map.data.setStyle(function (feature) {
    var nctcount = feature.getProperty('count_of_nct_id');
    return {
        icon: getCircle(nctcount)
    };
});

var icons = [];

var legend = document.getElementById('legend');
for (var key in icons) {
var type = icons[key];
var name = type.name;
var icon = type.icon;
var scale = type.scale;
var opacity = type.fillOpacity;
var div = document.createElement('div');
div.innerHTML = "<img src='data:image/svg+xml;utf8,<svg viewBox=\"0 0 100 100\" height=\"" + 8 * scale / 8 + "\" width=\"" + 8 * scale / 8 + "\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"50\" style=\"fill: green; stroke: white; stroke-width: 1;\" opacity=\"" + opacity + "\"/></svg>'> " + name;
legend.appendChild(div);
}

  map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);

}

function getCircle(nctcount) {
var nctamt = nctcount;
if (nctamt <= 10) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: 1,
        fillColor: 'green',
        scale: 5,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 10"
    };
}

else if (nctamt <= 100) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .8,
        fillColor: 'green',
        scale: 10,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 100"
    };
}

else if (nctamt <= 250) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .6,
        fillColor: 'green',
        scale: 15,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 250"
    };
}

else if (nctamt <= 500) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .4,
        fillColor: 'green ',
        scale: 20,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 500"
    };
}

else if (nctamt <= 2000) {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .2,
        fillColor: 'green',
        scale: 25,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "<= 2000"
    };
}

else {
    return {
        path: google.maps.SymbolPath.CIRCLE,
        fillOpacity: .2,
        fillColor: 'green',
        scale: 35,
        strokeColor: 'white',
        strokeWeight: .5,
        name: "> 2000"
    };
}

}

function tslandscape_callback(response) {
map.data.addGeoJson(response);
}

My Fiddle for the project is here: https://jsfiddle.net/Strawmr/uoc8vwhf/7/

Body:
One option would be to use the code from my answer to your earlier question, and make a function that creates a fixed legend (rather than trying to generate it dynamically from your data).

function makeLegend(map) {
  var legendmap = {
    scale1: {population: 8},
    scale2: {population: 80},
    scale3: {population: 200},
    scale4: {population: 450},
    scale5: {population: 1900},
    scale6: {population: 5000}
  };
  var icons = [];
  // Construct the circle for each value in legendmap.
  // Note: We scale the area of the circle based on the population.
  for (var entry in legendmap) {
    // Add the circle for this entry to the map.
    var icon = getCircle(legendmap[entry].population);
    if (!icons[icon.scale])
      icons[icon.scale] = icon;
  }

  var legend = document.getElementById('legend');
  for (var key in icons) {
    var type = icons[key];
    var name = type.name;
    var icon = type.icon;
    var scale = type.scale;
    var opacity = type.fillOpacity;
    var div = document.createElement('div');
    div.innerHTML = "<img src='data:image/svg+xml;utf8,<svg viewBox=\"0 0 100 100\" height=\"" + 8 * scale / 8 + "\" width=\"" + 8 * scale / 8 + "\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"50\" style=\"fill: green; stroke: white; stroke-width: 1;\" opacity=\"" + opacity + "\"/></svg>'> " + name;
    legend.appendChild(div);
  }
  // add the created legend to the map
  map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
}

proof of concept fiddle

code snippet

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {
      lat: 27.964157,
      lng: -82.452606
    },
    mapTypeControl: false,
    streetViewControl: false,
    styles: styles,
  });

  var script = document.createElement('script');
  script.src = 'https://trialscout.com/Scripts/landscapedata/tampadata_geojsonp.js';
  document.getElementsByTagName('head')[0].appendChild(script);

  map.data.setStyle(function(feature) {
    var nctcount = feature.getProperty('count_of_nct_id');
    return {
      icon: getCircle(nctcount)
    };
  });

  makeLegend(map);
}

function getCircle(nctcount) {
  var nctamt = nctcount;
  if (nctamt <= 10) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 1,
      fillColor: 'green',
      scale: 5,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 10"
    };
  } else if (nctamt <= 100) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.8,
      fillColor: 'green',
      scale: 10,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 100"
    };
  } else if (nctamt <= 250) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.6,
      fillColor: 'green',
      scale: 15,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 250"
    };
  } else if (nctamt <= 500) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.4,
      fillColor: 'green ',
      scale: 20,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 500"
    };
  } else if (nctamt <= 2000) {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.2,
      fillColor: 'green',
      scale: 25,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "<= 2000"
    };
  } else {
    return {
      path: google.maps.SymbolPath.CIRCLE,
      fillOpacity: 0.2,
      fillColor: 'green',
      scale: 35,
      strokeColor: 'white',
      strokeWeight: 0.5,
      name: "> 2000"
    };
  }

}

function tslandscape_callback(response) {
  map.data.addGeoJson(response);
}

function makeLegend(map) {
  // entries in the legend
  var legendmap = {
    scale1: {population: 8},
    scale2: {population: 80},
    scale3: {population: 200},
    scale4: {population: 450},
    scale5: {population: 1900},
    scale6: {population: 5000}
  };
  var icons = [];
  // Construct the circle for each value in legendmap.
  // Note: We scale the area of the circle based on the population.
  for (var entry in legendmap) {
    // Add the circle for this entry to the map.
    var circle = getCircle(legendmap[entry].population);
    if (!icons[circle.scale])
      icons[circle.scale] = circle;
  }

  var legend = document.getElementById('legend');
  for (var key in icons) {
    var type = icons[key];
    var name = type.name;
    var icon = type.icon;
    var scale = type.scale;
    var opacity = type.fillOpacity;
    var div = document.createElement('div');
    div.innerHTML = "<img src='data:image/svg+xml;utf8,<svg viewBox=\"0 0 100 100\" height=\"" + 8 * scale / 8 + "\" width=\"" + 8 * scale / 8 + "\" xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"50\" style=\"fill: green; stroke: white; stroke-width: 1;\" opacity=\"" + opacity + "\"/></svg>'> " + name;
    legend.appendChild(div);
  }
  // add the created legend to the map
  map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);
}
var styles = [{
  "featureType": "all",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#ff0000"
  }]
}, {
  "featureType": "administrative",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "administrative",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#06262d"
  }]
}, {
  "featureType": "administrative.country",
  "elementType": "labels",
  "stylers": [{
    "visibility": "off"
  }]
}, {
  "featureType": "administrative.locality",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#085c66"
  }]
}, {
  "featureType": "administrative.neighborhood",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#7ca7ad"
  }, {
    "visibility": "on"
  }]
}, {
  "featureType": "landscape",
  "elementType": "all",
  "stylers": [{
    "color": "#f2f2f2"
  }]
}, {
  "featureType": "landscape",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#f7f8f9"
  }]
}, {
  "featureType": "landscape",
  "elementType": "labels.text",
  "stylers": [{
    "visibility": "on"
  }]
}, {
  "featureType": "landscape",
  "elementType": "labels.text.fill",
  "stylers": [{
    "visibility": "simplified"
  }, {
    "color": "#ff0000"
  }]
}, {
  "featureType": "landscape.natural.terrain",
  "elementType": "labels.text.fill",
  "stylers": [{
    "visibility": "simplified"
  }]
}, {
  "featureType": "poi",
  "elementType": "all",
  "stylers": [{
    "visibility": "off"
  }]
}, {
  "featureType": "poi.park",
  "elementType": "geometry",
  "stylers": [{
    "visibility": "on"
  }, {
    "color": "#e3ece7"
  }]
}, {
  "featureType": "road",
  "elementType": "all",
  "stylers": [{
    "saturation": -100
  }, {
    "lightness": 45
  }]
}, {
  "featureType": "road.highway",
  "elementType": "all",
  "stylers": [{
    "visibility": "simplified"
  }]
}, {
  "featureType": "road.highway",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "road.highway",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#0a5d66"
  }]
}, {
  "featureType": "road.highway",
  "elementType": "labels.icon",
  "stylers": [{
    "visibility": "on"
  }, {
    "hue": "#00e8ff"
  }, {
    "saturation": "22"
  }, {
    "gamma": "1"
  }]
}, {
  "featureType": "road.arterial",
  "elementType": "geometry.stroke",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "road.arterial",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#7ca7ad"
  }]
}, {
  "featureType": "road.arterial",
  "elementType": "labels.icon",
  "stylers": [{
    "visibility": "off"
  }]
}, {
  "featureType": "road.local",
  "elementType": "geometry.stroke",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "road.local",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#afc6c6"
  }]
}, {
  "featureType": "road.local",
  "elementType": "labels.icon",
  "stylers": [{
    "visibility": "simplified"
  }]
}, {
  "featureType": "transit",
  "elementType": "all",
  "stylers": [{
    "visibility": "off"
  }]
}, {
  "featureType": "transit.station.airport",
  "elementType": "all",
  "stylers": [{
    "visibility": "on"
  }]
}, {
  "featureType": "transit.station.airport",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#e7e8e9"
  }]
}, {
  "featureType": "transit.station.airport",
  "elementType": "labels.text.fill",
  "stylers": [{
    "color": "#0a5d66"
  }]
}, {
  "featureType": "water",
  "elementType": "all",
  "stylers": [{
    "color": "#46bcec"
  }, {
    "visibility": "on"
  }]
}, {
  "featureType": "water",
  "elementType": "geometry.fill",
  "stylers": [{
    "color": "#afc6c6"
  }]
}, {
  "featureType": "water",
  "elementType": "labels.text",
  "stylers": [{
    "color": "#0a5d66"
  }]
}]

html,
body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

#map {
  height: 100%;
  width: 100%;
}

#legend {
  font-family: Arial, sans-serif;
  background: #fff;
  padding: 10px;
  margin: 10px;
  border: 3px solid #000;
}

#legend h3 {
  margin-top: 0;
}

#legend img {
  vertical-align: middle;
}

<div id="map"></div>
<div id="legend"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>


问:
Problem Passing a function reference in Kotlin
The following line of code is throwing a compile error related to Renderer::onScoreChange. The reported error is:
Type mismatch.
Required:(Int, Int) → Unit
Found: KFunction3<Renderer, @ParameterName Int, @ParameterName Int, Unit>

```<code>var score by EngineObserver<Int>(20, Renderer::onScoreChange)
</code>```

I'm trying to pass a function reference to a custom Delegate extending from the ObservableProperty class but not sure why its not recognizing the passed member function as satisfying the requirements of the function argument. Thoughts from anyone?

```<code>class EngineObserver<T>(
   initialValue: T,
   val notify : (oldVal : T, newVal : T) -> Unit
) : ObservableProperty<T>(initialValue) {
   override fun afterChange(property: KProperty<*>,
                            oldValue: T,
                            newValue: T) {
        super.afterChange(property, oldValue, newValue)
        notify(oldValue, newValue)
   }
}

class Renderer {
   fun onScoreChange(oldVal : Int, newVal : Int){
      println("Score changed from $oldVal to $newVal")
   }
}
</code>```

答:
Miha_x64 is right. To make your code work, you have to do the following:

```<code>class Renderer {
    companion object {
        fun onScoreChange(oldVal: Int, newVal: Int) {
            println("Score changed from $oldVal to $newVal")
        }
    }
}

var score by EngineObserver<Int>(20, Renderer.Companion::onScoreChange)
</code>```

Alternatively, if you have a Renderer instance you want to call that method on, you can do:

```<code>val renderer = Renderer()
var score by EngineObserver<Int>(20, renderer::onScoreChange)
</code>```

Body:
The following line of code is throwing a compile error related to Renderer::onScoreChange. The reported error is:
Type mismatch.
Required:(Int, Int) → Unit
Found: KFunction3<Renderer, @ParameterName Int, @ParameterName Int, Unit>

var score by EngineObserver<Int>(20, Renderer::onScoreChange)

I'm trying to pass a function reference to a custom Delegate extending from the ObservableProperty class but not sure why its not recognizing the passed member function as satisfying the requirements of the function argument. Thoughts from anyone?

class EngineObserver<T>(
   initialValue: T,
   val notify : (oldVal : T, newVal : T) -> Unit
) : ObservableProperty<T>(initialValue) {
   override fun afterChange(property: KProperty<*>,
                            oldValue: T,
                            newValue: T) {
        super.afterChange(property, oldValue, newValue)
        notify(oldValue, newValue)
   }
}

class Renderer {
   fun onScoreChange(oldVal : Int, newVal : Int){
      println("Score changed from $oldVal to $newVal")
   }
}

Body:
Miha_x64 is right. To make your code work, you have to do the following:

class Renderer {
    companion object {
        fun onScoreChange(oldVal: Int, newVal: Int) {
            println("Score changed from $oldVal to $newVal")
        }
    }
}

var score by EngineObserver<Int>(20, Renderer.Companion::onScoreChange)

Alternatively, if you have a Renderer instance you want to call that method on, you can do:

val renderer = Renderer()
var score by EngineObserver<Int>(20, renderer::onScoreChange)


问:
Ajax call, see elements visualy but Javascript doesn't see them
I would really appreciate your help, as I been looking over and over and completely lost in what could go wrong.

I have an Ajax call to web service, and from this call I am building some HTML structure. Up to this point everything is good, the data get pulled and I can visually see the structure.

However as my code continues and I try to read those elements later for some more manipulations, JavaScript doesn't see them at all, and on element counts I am getting zero.

Some relevant code from the project.
This function that runs first and basically builds the needed HTML piece

```<code>                $.ajax({
                    type: "POST",
                    url: "HistoryEventsWebService.asmx/getEventsData",
                    data: event_types,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) { //on success
                        var results = result.d;

                        $('#insidediv_container').empty();

                        for (var i = 0; i < results.length; i++) {
                            var insidediv = '';
                            insidediv += '<div class="insidediv">';
                            insidediv += '<span class="month">' + results[i].month + '</span><span class="day">' + results[i].day + '</span><span class="year">' + results[i].year + '</span>';
                            insidediv += '<div class="header"><span>Jan 08, 2010 - event one</span> </div>';
                            insidediv += '<div class="contentdiv">' + results[i].event_desc + '</div>';
                            insidediv += '</div>';

                            $('#insidediv_container').append(insidediv);
                        }
                    }
                });
                return false;
</code>```

Right after this upper function is done, my code is continued to next function, and that's where I have my problem!

```<code> var currentbox = 0;
            var current_box_old = 0;
            var box_size = ($('.insidediv').width() + 1).toString();
            var box_count = $('.container2 > div > div').length - 1;

            //console.log(box_count);
            var min_range = 0;

            setScale(); //making slider visual elements

            //slider code
            $("#slider").slider({
                min: min_range,
                max: box_count,
                value: 0,
                animate: true,
                //step: 1,
                slide: function (event, ui) {
                    current_box_old = currentbox;
                    currentbox = ui.value;
                    if (currentbox > current_box_old)
                        $('#insidediv_container').animate({ "margin-left": "-=" + box_size + "px" }, "normal");
                    else
                        $('#insidediv_container').animate({ "margin-left": "+=" + box_size + "px" }, "normal");
                }
            });
</code>```

Thank you in advance.

答:
The reason this isn't working is that the whole of the code you want executed must be inside the ajax success method. Because the ajax post is asynchronous, the ajax method 'returns' almost instantly and flow immediately flows to your second block of code. However, because it got there so quickly, the ajax post hasn't received it's results yet, so the success method hasn't been called yet, which in turn means that the elements you're looking for have not yet been inserted into the DOM.

If these are the rough modular steps in what your code is doing:

```
$.ajax (A) -> http post (B) -> success (C) -> add elements to DOM (D)
|
v
update new DOM elements (E)
```

Then the actual flow of code is A, B, E, C, D and not A, B, C, D, E.

Hope this helps!

Body:
I would really appreciate your help, as I been looking over and over and completely lost in what could go wrong.

I have an Ajax call to web service, and from this call I am building some HTML structure. Up to this point everything is good, the data get pulled and I can visually see the structure.

However as my code continues and I try to read those elements later for some more manipulations, JavaScript doesn't see them at all, and on element counts I am getting zero.

Some relevant code from the project.
This function that runs first and basically builds the needed HTML piece

                $.ajax({
                    type: "POST",
                    url: "HistoryEventsWebService.asmx/getEventsData",
                    data: event_types,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (result) { //on success
                        var results = result.d;

                        $('#insidediv_container').empty();

                        for (var i = 0; i < results.length; i++) {
                            var insidediv = '';
                            insidediv += '
';
                            insidediv += '' + results[i].month + '' + results[i].day + '' + results[i].year + '';
                            insidediv += '
Jan 08, 2010 - event one
';
                            insidediv += '
' + results[i].event_desc + '
';
                            insidediv += '
';

                            $('#insidediv_container').append(insidediv);
                        }
                    }
                });
                return false;

Right after this upper function is done, my code is continued to next function, and that's where I have my problem!

 var currentbox = 0;
            var current_box_old = 0;
            var box_size = ($('.insidediv').width() + 1).toString();
            var box_count = $('.container2 > div > div').length - 1;

            //console.log(box_count);
            var min_range = 0;

            setScale(); //making slider visual elements

            //slider code
            $("#slider").slider({
                min: min_range,
                max: box_count,
                value: 0,
                animate: true,
                //step: 1,
                slide: function (event, ui) {
                    current_box_old = currentbox;
                    currentbox = ui.value;
                    if (currentbox > current_box_old)
                        $('#insidediv_container').animate({ "margin-left": "-=" + box_size + "px" }, "normal");
                    else
                        $('#insidediv_container').animate({ "margin-left": "+=" + box_size + "px" }, "normal");
                }
            });

Thank you in advance.

Body:
The reason this isn't working is that the whole of the code you want executed must be inside the ajax success method. Because the ajax post is asynchronous, the ajax method 'returns' almost instantly and flow immediately flows to your second block of code. However, because it got there so quickly, the ajax post hasn't received it's results yet, so the success method hasn't been called yet, which in turn means that the elements you're looking for have not yet been inserted into the DOM.

If these are the rough modular steps in what your code is doing:

$.ajax (A) -> http post (B) -> success (C) -> add elements to DOM (D)
|
v
update new DOM elements (E)

Then the actual flow of code is A, B, E, C, D and not A, B, C, D, E.

Hope this helps!


问:
I need to take off
 from data using react
I receive data from database like this :

```<code>description:<p>my name is ....</p>
</code>```

I put this in a table, all I need is to put the text only, how can I remove the

?

答:
You can remove your html tags by using regex</p>

```<code>const htmlRemoveRegex = /(<([^>]+)>)/gi;
const newString = description.replace(htmlRemoveRegex, '');
</code>```

Title: I need to take off <p> from data using react

Body:
I receive data from database like this :

description:
my name is ....

I put this in a table, all I need is to put the text only, how can I remove the

?

Body:
You can remove your html tags by using regex

const htmlRemoveRegex = /(<([^>]+)>)/gi;
const newString = description.replace(htmlRemoveRegex, '');


问:
Sqlite order by rows order
I am using this query

```<code>"select * from SomeTable group by SomeColumn"
</code>```

It is returns list with accenting order, but i need to same order like in database.

For example the order in database is:

```<code>p

a

s
</code>```

But result is:

```<code>a

i

p
</code>```

Sample

The result need to be like distinct by CityEN but with all columns and order like 1.Paris 2.Amsterdam 3.Istanbul

答: Your query does not enforce any order with ORDER BY clause so no assumption about row order should be made. If you want specific order add i.e. ORDER BY SomeColumn. See docs about all available order options: https://www.sqlite.org/lang_select.html#orderby

Title: Sqlite order by rows order

Body:
I am using this query

"select * from SomeTable group by SomeColumn"

It is returns list with accenting order, but i need to same order like in database.

For example the order in database is:

p

a

s

But result is:

a

i

p

Sample

The result need to be like distinct by CityEN but with all columns and order like 1.Paris 2.Amsterdam 3.Istanbul


问:
Does the 'S' in SQL stand for "standard" or "structured"?
I'm thinking "structured", but my dad claims that when he taught a class that involved SQL (decades ago), they used "standard".  I was wondering if this changed over time, or is he mistaken?  I googled it with "standard" and did see some pages that said that's what it stands for.  Any old timers willing to give a history lesson?</p>

答:
Wikipedia says first:

SQL often referred to as Structured Query Language.

And then further down:

SQL was developed at IBM by Donald D. Chamberlin and Raymond F. Boyce in the early 1970s. This version, initially called SEQUEL (Structured English Query Language).

There's no mention of "standard query language" on the whole page.

The other test of course is to search Google for "structured query language" vs "standard query language". For which I currently get 913,000 results compared to 124,000. So clearly "structured" wins, however interestingly there was apparently a divided preference at one time. This site says:

In the early days of the system there was divided preference between Standard Query Language and Structured Query Language but it did not make a whole lot of difference since most people most of the time called it by the acronym SQL. Now the overwhelming but not complete preference is for Structured Query Language.