问:
State is only pushed to component when action is dispatched twice
I have a simple array my store and a single action to add an item to this array if the value doesn't already exist.

The problem I'm experiencing is that my component subscription doesn't receive the updated state until the action is dispatched twice.

After that, it works as expected. My initial state is an empty array as expected, but I'm not understanding why the state isn't pushed when the action is dispatched, and the new state object is returned.

the reducer:

export function addressFormsReducer(state = initialState, action: Action): AddressFormState {
  switch (action.type) {
    case AddressFormActions.ZIP_CODE_LOOKUP_SUCCESS: {
      const zipCodeLookupResult = <IZipCodeLookupResult>action.payload;
      const index = _.findIndex(state, <IZipCodeLookupResult>{ formId: zipCodeLookupResult.formId });

      if (index >= 0) {
        state = [...state.slice(0, index), zipCodeLookupResult, ...state.slice(index + 1)];
      }
      else {
        state.push(zipCodeLookupResult);
      }

      return state;
    }

    default: {
      return state;
    }

  }
}
```

<p>the component subscription:</p>

<pre class="lang-js prettyprint-override"><code>ngOnInit(): void {
    ...

    this.sub = this.store.select<AddressFormState>('addressForms').subscribe(addressFormState => {
      let stateObj = addressFormState.filter(state => state.formId === 'ordering-provider')[0];
      if (stateObj) {
        this.zipCodeNotFound = stateObj.zipCodeNotFound;
      }
    });
  }
</code>```

Why might that be happening?

答:
This is likely due to you mutating the state by calling state.push. Selecting from the store uses distinctUntilChanged, which uses object equality to detect if the state has changed.  For this reason, it's important to always treat the state as immutable. Try this instead:

```<code>if (index >= 0) {
    state = [...state.slice(0, index), zipCodeLookupResult, ...state.slice(index + 1)];
}
else {
    state = [...state, zipCodeLookupResult];
}
</code>```

Body:
I have a simple array my store and a single action to add an item to this array if the value doesn't already exist.

The problem I'm experiencing is that my component subscription doesn't receive the updated state until the action is dispatched twice.

After that, it works as expected. My initial state is an empty array as expected, but I'm not understanding why the state isn't pushed when the action is dispatched, and the new state object is returned.

the reducer:

export function addressFormsReducer(state = initialState, action: Action): AddressFormState {
  switch (action.type) {
    case AddressFormActions.ZIP_CODE_LOOKUP_SUCCESS: {
      const zipCodeLookupResult = <IZipCodeLookupResult>action.payload;
      const index = _.findIndex(state, <IZipCodeLookupResult>{ formId: zipCodeLookupResult.formId });

      if (index >= 0) {
        state = [...state.slice(0, index), zipCodeLookupResult, ...state.slice(index + 1)];
      }
      else {
        state.push(zipCodeLookupResult);
      }

      return state;
    }

    default: {
      return state;
    }

  }
}

the component subscription:

ngOnInit(): void {
    ...

    this.sub = this.store.select<AddressFormState>('addressForms').subscribe(addressFormState => {
      let stateObj = addressFormState.filter(state => state.formId === 'ordering-provider')[0];
      if (stateObj) {
        this.zipCodeNotFound = stateObj.zipCodeNotFound;
      }
    });
  }

Why might that be happening?

Body:
This is likely due to you mutating the state by calling state.push. Selecting from the store uses distinctUntilChanged, which uses object equality to detect if the state has changed.  For this reason, it's important to always treat the state as immutable. Try this instead:

if (index >= 0) {
    state = [...state.slice(0, index), zipCodeLookupResult, ...state.slice(index + 1)];
}
else {
    state = [...state, zipCodeLookupResult];
}


来源: stackexchange

问:
Is WebGet functionally equivalent to WebInvoke(Method = "GET")?
This question already asks what I'm asking, but I want some clarification on the answer.

The answer states that WebGet and WebInvoke are similar, and that the primary difference is the Method parameter.

But if the Method parameter is set to "GET", is it actually functionally equivalent, or are there other differences?

答:
It is not.

I just spent few hours trying to replace WCF DataContractJsonSerializer with Newtonsoft JsonSerializer using MessageFormatter based on this and
 this samples

found out (the hard way) there IS difference in using WebGet and WebInvoke(Method="GET").

With WebInvoke the request goes through different pipeline in WCF stack, trying to deserialize the expected message (method IDispatchMessageFormatter.DeserializeRequest() gets invoked) which is not the case with WebGet.

The lesson learned: use WebGet for GET operation

ContentLicense: CC BY-SA 3.0


问:
Problems with discovering modules inside metaclass's __new__
Basically, I want to load all functions of a specific module (if it exists) and merge them with the class methods. If I had the __module__ of the class that is being built inside __new__ I could build the path straight to the module and import it. I'm looking for a get_module_fns to solve my problem. I wish to do something like:

```<code>get_module_fns('pathto.mod1.toimport')
</code>```

and if it exists, it will return all functions as a dict.

Here's the link for the code and tests.

```<code># mtcl.py
import inspect
import imp

def get_module_fns(module_name, module_path):
    try:
        mod_loaded = imp.load_source(module_name, module_path)
        module_fns = [(name, func) for name, func in
                      inspect.getmembers(mod_loaded, inspect.isfunction)]
    except FileNotFoundError as e:
        return {}
    except ImportError as e:
        return {}
    return dict(module_fns)

class GetModuleFunctions(type):

    def __new__(cls, name, bases, namespaces, **kwargs):

        module_functions = get_module_fns('toimport', './toimport.py')
        namespaces.update(module_functions)

        new_class = super(GetModuleFunctions, cls).__new__(
            cls, name, bases, namespaces)

        new_class._mdl_fns = module_functions

        return new_class

class ClassBase(metaclass=GetModuleFunctions):

    def __init__(self, *args, **kwargs):
        super(ClassBase, self).__init__(*args, **kwargs)

    @property
    def module_functions(self):
        return self.__class__._mdl_fns
</code>```

```<code># mod0.py
from .mtcl import ClassBase

class M0(ClassBase):

    def function_m0(self):
        return 0
</code>```

```<code># mod1/__init__.py
from ..mtcl import ClassBase

class M1(ClassBase):

    def function_m1(self):
        return 1
</code>```

```<code># mod1/toimport.py

def function_1(obj,  *args, **kwargs):
    return 1
</code>```

```<code># mod1/mod2/__init__.py
from ...mtcl import ClassBase

class M2(ClassBase):

    def function_m2(self):
        return 2
</code>```

```<code># mod1/mod2/toimport.py

def function_2(obj,  *args, **kwargs):
    return 2
</code>```

答:
Try the following:

```<code>import inspect
import importlib

def get_module_fns(cls, module_name):
    try:
        mod_loaded = importlib.import_module(
            '%s.%s' % (cls.__module__, module_name)
        )
        module_fns = [(name, func) for name, func in
                      inspect.getmembers(mod_loaded, inspect.isfunction)]
    except ModuleNotFoundError as e:
        return {}
    except ImportError as e:
        return {}
    return dict(module_fns)

class GetModuleFunctions(type):

    def __new__(cls, *args, **kwargs):
        new_class = super(GetModuleFunctions, cls).__new__(
            cls, *args, **kwargs)
        module_functions = get_module_fns(new_class, 'toimport')
        for name, fn in module_functions.items():
            setattr(new_class, name, fn)
        new_class._mdl_fns = module_functions
        return new_class
</code>```

Since you're looking for a module within your class' module, this should do it:

```<code>mod_loaded = importlib.import_module(
    '%s.%s' % (cls.__module__, module_name)
)
</code>```

Sadly, you can't use namespace after __new__.super:

```<code>for name, fn in module_functions.items():
    setattr(new_class, name, fn)
</code>```

Body:
Basically, I want to load all functions of a specific module (if it exists) and merge them with the class methods. If I had the __module__ of the class that is being built inside __new__ I could build the path straight to the module and import it. I'm looking for a get_module_fns to solve my problem. I wish to do something like:

get_module_fns('pathto.mod1.toimport')

and if it exists, it will return all functions as a dict.

Here's the link for the code and tests.

# mtcl.py
import inspect
import imp

def get_module_fns(module_name, module_path):
    try:
        mod_loaded = imp.load_source(module_name, module_path)
        module_fns = [(name, func) for name, func in
                      inspect.getmembers(mod_loaded, inspect.isfunction)]
    except FileNotFoundError as e:
        return {}
    except ImportError as e:
        return {}
    return dict(module_fns)

class GetModuleFunctions(type):

    def __new__(cls, name, bases, namespaces, **kwargs):

        module_functions = get_module_fns('toimport', './toimport.py')
        namespaces.update(module_functions)

        new_class = super(GetModuleFunctions, cls).__new__(
            cls, name, bases, namespaces)

        new_class._mdl_fns = module_functions

        return new_class

class ClassBase(metaclass=GetModuleFunctions):

    def __init__(self, *args, **kwargs):
        super(ClassBase, self).__init__(*args, **kwargs)

    @property
    def module_functions(self):
        return self.__class__._mdl_fns

# mod0.py
from .mtcl import ClassBase

class M0(ClassBase):

    def function_m0(self):
        return 0

# mod1/__init__.py
from ..mtcl import ClassBase

class M1(ClassBase):

    def function_m1(self):
        return 1

# mod1/toimport.py

def function_1(obj,  *args, **kwargs):
    return 1

# mod1/mod2/__init__.py
from ...mtcl import ClassBase

class M2(ClassBase):

    def function_m2(self):
        return 2

# mod1/mod2/toimport.py

def function_2(obj,  *args, **kwargs):
    return 2

Body:
Try the following:

import inspect
import importlib

def get_module_fns(cls, module_name):
    try:
        mod_loaded = importlib.import_module(
            '%s.%s' % (cls.__module__, module_name)
        )
        module_fns = [(name, func) for name, func in
                      inspect.getmembers(mod_loaded, inspect.isfunction)]
    except ModuleNotFoundError as e:
        return {}
    except ImportError as e:
        return {}
    return dict(module_fns)

class GetModuleFunctions(type):

    def __new__(cls, *args, **kwargs):
        new_class = super(GetModuleFunctions, cls).__new__(
            cls, *args, **kwargs)
        module_functions = get_module_fns(new_class, 'toimport')
        for name, fn in module_functions.items():
            setattr(new_class, name, fn)
        new_class._mdl_fns = module_functions
        return new_class

Since you're looking for a module within your class' module, this should do it:

mod_loaded = importlib.import_module(
    '%s.%s' % (cls.__module__, module_name)
)

Sadly, you can't use namespace after __new__.super:

for name, fn in module_functions.items():
    setattr(new_class, name, fn)


问:
ASP.Net 4.5 - Web Method Does Not Get Called From JQuery
I have set break points in the C# code and the web method is not invoked. I should see four rows returned from the database.

I do not get any errors - the only thing I see in the console is an error on the the length (in the javascript for loop ie i < data.d.length).

Relevant Code

TestApp.aspx.cs

```<code>    namespace WebApplication1
{
    public class User
    {
        public int?   TestID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

    public partial class TestApp : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static User[] Get()
        {
            try
            {
                List<User> details = FetchData("sp_LoadData", null);
                return details.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
</code>```

TestApp.aspx

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestApp.aspx.cs" Inherits="WebApplication1.TestApp" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
    <script src="TestApp.js"></script>
</head>
<body>
    <form id="form1">

                        <table id="example" class="display" cellspacing="1" width="100%" border="1">
                            <thead style="border: solid thin;">
                                <tr>
                                    <th>First name</th>
                                    <th>Last name</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Delete</th>
                                </tr>
                            </thead>
                        </table>
</code>```

TestApp.js

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

function BindGrid() {
    var t = $('#example').DataTable();
    t.rows().remove().draw();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "TestApp.aspx/Get",
        data: "{}",
        dataType: "json",

        success: function (data) {
            for (var i = 0; i < data.d.length; i++) {
                //debugger;
                t.row.add([
                            '<a class="table-edit" onclick="showRecord(' + data.d[i].TestID + ');">' + data.d[i].FirstName + '</a>',
                            data.d[i].LastName,
                            data.d[i].Email,
                            data.d[i].Phone,
                            '<button type="button" onclick="deleteRecord(' + data.d[i].TestID + ');">Delete</button>'
                ]).draw(false);
            }
        },
        error: function (result) {
            debugger;
            alert("Error");
        }
    });
};
</code>```

答:
"I do not get any errors - the only thing I see in the console is an error on the the length", so you DO get an error :)

When you are checking the length, you are assuming there is always an array defined as 'd' in data.  You should add a check to validate your assumptions:

```<code>if (data && data.d && data.d.length) {
  for (var i = 0; i < data.d.length; i++) {
     ...
</code>```

Body:
I have set break points in the C# code and the web method is not invoked. I should see four rows returned from the database.

I do not get any errors - the only thing I see in the console is an error on the the length (in the javascript for loop ie i < data.d.length).

Relevant Code

TestApp.aspx.cs

    namespace WebApplication1
{
    public class User
    {
        public int?   TestID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
    }

    public partial class TestApp : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static User[] Get()
        {
            try
            {
                List<User> details = FetchData("sp_LoadData", null);
                return details.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

TestApp.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestApp.aspx.cs" Inherits="WebApplication1.TestApp" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1">

                                    First name
                                    Last name
                                    Email
                                    Phone
                                    Delete

TestApp.js

$(document).ready(function () {
    BindGrid();

function BindGrid() {
    var t = $('#example').DataTable();
    t.rows().remove().draw();

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "TestApp.aspx/Get",
        data: "{}",
        dataType: "json",

        success: function (data) {
            for (var i = 0; i < data.d.length; i++) {
                //debugger;
                t.row.add([
                            '' + data.d[i].FirstName + '',
                            data.d[i].LastName,
                            data.d[i].Email,
                            data.d[i].Phone,
                            '<button type="button" onclick="deleteRecord(' + data.d[i].TestID + ');">Delete</button>'
                ]).draw(false);
            }
        },
        error: function (result) {
            debugger;
            alert("Error");
        }
    });
};

Body:
"I do not get any errors - the only thing I see in the console is an error on the the length", so you DO get an error :)

When you are checking the length, you are assuming there is always an array defined as 'd' in data.  You should add a check to validate your assumptions:

if (data && data.d && data.d.length) {
  for (var i = 0; i < data.d.length; i++) {
     ...


问:
Show Custom Post based on selected custom taxonomy in Wordpress
In the current website i am building i build the following functionality.

Current situation to give a better understanding of the problem.

There is a page called blog. This page display's all the blogs (posts) in a list. There is a aside with all the categories the posts have. The user can select a category. Once the user clicks on it the user will go to the category.php and see all the posts that have that specific category.

I want to create the same scenario but than with a custom post type. I have a template part; 'offer-list-template.php'

offer-list-template.php (here i get all the offers and display them);

```<code>  <?php
      // set up or arguments for our custom query
      $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
      $query_args = array(
        'post_type' => 'Offers',
        'posts_per_page' => 10,
        'paged' => $paged
      );
      // create a new instance of WP_Query
      $the_query = new WP_Query( $query_args );
    ?>

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); // run the loop ?>
  <?php

   //$objectData is used in post-listing-item.php

    $objectData->title = get_the_title($post);
    $objectData->content = get_the_content($post);
    $objectData->permalink = get_the_permalink($post);
    $objectData->thumbnail = get_the_post_thumbnail($post);
    $objectData->posttype = get_post_type($post);

    include(locate_template('template-parts/post-listing-item.php'));
  ?>
<?php endwhile; ?>
</code>```

In the same file there is the aside which shows the categories. offer_category is the taxonomy slug.

```<code>  <?php $terms = get_terms( 'offer_category' );
    foreach ( $terms as $term ) {

        // The $term is an object, so we don't need to specify the $taxonomy.
        $term_link = get_term_link( $term );

        // If there was an error, continue to the next term.
        if ( is_wp_error( $term_link ) ) {
            continue;
        }

        // We successfully got a link. Print it out.
        echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '</a><span>('. $term->count . ')</span></li>';
    }
    ?>
    </ul
</code>```

The result is:

If the user clicks on the categorie it goes to: taxonomy-offer-category.php (taxonomy-slug.php)

Here i need to display the posts (post_type->offers) that have the selected category.

Registration of the custom post type:

```<code>//Register Custom post type for Offers.
function create_posttype_offer() {
  $args = array(
    'labels' => array(
      'name' => __('Offers', ''),
      'singular_name' => __('Offer'),
      'all_items' => __('All Offers'),
      'add_new_item' => __('Add New Offer'),
      'edit_item' => __('Edit Offer'),
      'view_item' => __('View Offer')
    ),
    'public' => true,
    'has_archive' => true,
    'rewrite' => array('slug' => 'Offers'),
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'capability_type' => 'page',
    'supports' => array('title', 'editor', 'thumbnail'),
    'exclude_from_search' => true,
    'menu_position' => 70,
    'has_archive' => true,
    'menu_icon' => 'dashicons-star-filled'
    );
  register_post_type('Offers', $args);
}
add_action( 'init', 'create_posttype_offer');

// Register Custom Categoeries for Custom Post Type Offers
function taxonomies_offer() {
$labels = array(
    'name'              => _x( 'Categories', 'taxonomy general name' ),
    'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
    'search_items'      => __( 'Search Categories' ),
    'all_items'         => __( 'All Categories' ),
    'parent_item'       => __( 'Parent Category' ),
    'parent_item_colon' => __( 'Parent Category:' ),
    'edit_item'         => __( 'Edit Category' ),
    'update_item'       => __( 'Update Category' ),
    'add_new_item'      => __( 'Add New Category' ),
    'new_item_name'     => __( 'New Category' ),
    'menu_name'         => __( 'Categories' ),
    );

$args = array(
    'labels' => $labels,
    'hierarchical' => true,
    );

register_taxonomy( 'offer_category', 'offers', $args );
}
add_action( 'init', 'taxonomies_offer', 0 );
</code>```

When i use the default post type and i call category.php which has the following code is will display the posts with the selected category. But with a custom post type i can't find a way to manage it.

```<code>  <?php if (have_posts() ) : while ( have_posts() ) : the_post(); // run the loop ?>
    <?php

     //$objectData is used in post-listing-item.php

      $objectData->title = get_the_title($post);
      $objectData->content = get_the_content($post);
      $objectData->permalink = get_the_permalink($post);
      $objectData->thumbnail = get_the_post_thumbnail($post);
      $objectData->posttype = get_post_type($post);

      include(locate_template('template-parts/post-listing-item.php'));
    ?>
  <?php endwhile; ?>
</code>```

This is the post-listing-item (view)

```<code><article class="post-item">
     <figure>
       <?php echo $objectData->thumbnail ?>
     </figure>

     <div class="content">
       <a href="<?php echo $objectData->permalink ?>">
           <h2><?php echo $objectData->title ?></h2>
       </a>

       <p><?php echo $objectData->content ?></p>

       <div class="read-more-button">
         <a href="<?php echo $objectData->permalink ?>">read more
         <span>
           <svg class="next-arrow"><use xlink:href="#next-arrow" /></svg>
         </span>
         </a>
       </div>
     </div>
 </article>
</code>```

答:
By understanding, you have to have a query for having all the custom taxonomy post to load by the following code:

```<code>$terms = get_terms(
        array(
            'taxonomy' => 'offer_category',
            'hide_empty' => false,
            )
        );

foreach ($terms as $term){
     $args = array(
           'post_type' => 'Offers',
           'tax_query' => array(
                                 array(
                                     'taxonomy' => 'offer_category',
                                     'field'    => 'slug',
                                     'terms'    =>  $term->slug,
                                  ),
                          ),
             );
      $query = new WP_Query($args);
      if($query->have_posts()): while($query->have_posts()): $query->the_post();

            the_title();
            the_content();
      endwhile;
      wp_reset_postdata();
      endif;
 }
</code>```

Hope this works for you

Body:
In the current website i am building i build the following functionality.

Current situation to give a better understanding of the problem.

There is a page called blog. This page display's all the blogs (posts) in a list. There is a aside with all the categories the posts have. The user can select a category. Once the user clicks on it the user will go to the category.php and see all the posts that have that specific category.

I want to create the same scenario but than with a custom post type. I have a template part; 'offer-list-template.php'

offer-list-template.php (here i get all the offers and display them);

  <?php
      // set up or arguments for our custom query
      $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
      $query_args = array(
        'post_type' => 'Offers',
        'posts_per_page' => 10,
        'paged' => $paged
      );
      // create a new instance of WP_Query
      $the_query = new WP_Query( $query_args );
    ?>

<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); // run the loop ?>
  <?php

   //$objectData is used in post-listing-item.php

    $objectData->title = get_the_title($post);
    $objectData->content = get_the_content($post);
    $objectData->permalink = get_the_permalink($post);
    $objectData->thumbnail = get_the_post_thumbnail($post);
    $objectData->posttype = get_post_type($post);

    include(locate_template('template-parts/post-listing-item.php'));
  ?>
<?php endwhile; ?>

In the same file there is the aside which shows the categories. offer_category is the taxonomy slug.

  <?php $terms = get_terms( 'offer_category' );
    foreach ( $terms as $term ) {

        // The $term is an object, so we don't need to specify the $taxonomy.
        $term_link = get_term_link( $term );

        // If there was an error, continue to the next term.
        if ( is_wp_error( $term_link ) ) {
            continue;
        }

        // We successfully got a link. Print it out.
        echo '
' . $term->name . '('. $term->count . ')
';
    }
    ?>
    </ul

The result is:

If the user clicks on the categorie it goes to: taxonomy-offer-category.php (taxonomy-slug.php)

Here i need to display the posts (post_type->offers) that have the selected category.

Registration of the custom post type:

//Register Custom post type for Offers.
function create_posttype_offer() {
  $args = array(
    'labels' => array(
      'name' => __('Offers', ''),
      'singular_name' => __('Offer'),
      'all_items' => __('All Offers'),
      'add_new_item' => __('Add New Offer'),
      'edit_item' => __('Edit Offer'),
      'view_item' => __('View Offer')
    ),
    'public' => true,
    'has_archive' => true,
    'rewrite' => array('slug' => 'Offers'),
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'capability_type' => 'page',
    'supports' => array('title', 'editor', 'thumbnail'),
    'exclude_from_search' => true,
    'menu_position' => 70,
    'has_archive' => true,
    'menu_icon' => 'dashicons-star-filled'
    );
  register_post_type('Offers', $args);
}
add_action( 'init', 'create_posttype_offer');

// Register Custom Categoeries for Custom Post Type Offers
function taxonomies_offer() {
$labels = array(
    'name'              => _x( 'Categories', 'taxonomy general name' ),
    'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
    'search_items'      => __( 'Search Categories' ),
    'all_items'         => __( 'All Categories' ),
    'parent_item'       => __( 'Parent Category' ),
    'parent_item_colon' => __( 'Parent Category:' ),
    'edit_item'         => __( 'Edit Category' ),
    'update_item'       => __( 'Update Category' ),
    'add_new_item'      => __( 'Add New Category' ),
    'new_item_name'     => __( 'New Category' ),
    'menu_name'         => __( 'Categories' ),
    );

$args = array(
    'labels' => $labels,
    'hierarchical' => true,
    );

register_taxonomy( 'offer_category', 'offers', $args );
}
add_action( 'init', 'taxonomies_offer', 0 );

When i use the default post type and i call category.php which has the following code is will display the posts with the selected category. But with a custom post type i can't find a way to manage it.

  <?php if (have_posts() ) : while ( have_posts() ) : the_post(); // run the loop ?>
    <?php

     //$objectData is used in post-listing-item.php

      $objectData->title = get_the_title($post);
      $objectData->content = get_the_content($post);
      $objectData->permalink = get_the_permalink($post);
      $objectData->thumbnail = get_the_post_thumbnail($post);
      $objectData->posttype = get_post_type($post);

      include(locate_template('template-parts/post-listing-item.php'));
    ?>
  <?php endwhile; ?>

This is the post-listing-item (view)

       <?php echo $objectData->thumbnail ?>

       <a href="<?php echo $objectData->permalink ?>">

<?php echo $objectData->title ?>

<?php echo $objectData->content ?>

         <a href="<?php echo $objectData->permalink ?>">read more

           <svg class="next-arrow"><use xlink:href="#next-arrow" /></svg>

Body:
By understanding, you have to have a query for having all the custom taxonomy post to load by the following code:

$terms = get_terms(
        array(
            'taxonomy' => 'offer_category',
            'hide_empty' => false,
            )
        );

foreach ($terms as $term){
     $args = array(
           'post_type' => 'Offers',
           'tax_query' => array(
                                 array(
                                     'taxonomy' => 'offer_category',
                                     'field'    => 'slug',
                                     'terms'    =>  $term->slug,
                                  ),
                          ),
             );
      $query = new WP_Query($args);
      if($query->have_posts()): while($query->have_posts()): $query->the_post();

            the_title();
            the_content();
      endwhile;
      wp_reset_postdata();
      endif;
 }

Hope this works for you


问:
How to read until end of file C, fscanf
What i read from a file: a P1/ s/ e/ t etc. / for different line. After specific letters(like 'a') come some data i have to collect so i don't want to use fgets. It doesn't end running. Could you help me, please? </p>

```<code>char com[21];
fscanf(src,"%s",com);
while(com!=EOF)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
    fscanf(src,"%s",com);
}
</code>```

答:
Simple way is to test if fscanf() succeeded as the loop condition and you don't need a fscanf() before the loop:

```<code>char com[21];

while(fscanf(src,"%20s",com) == 1)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
}
</code>```

fscanf() returns the number of items successfully scanned. So, you don't need to check if it' returned EOF.

Note that I changed the format string to avoid buffer overflow. I suggest you use fgets() instead of fscanf() (and remember to take care of newline chars if it matters).

Title: How to read until end of file C, fscanf

Body:
What i read from a file: a P1/ s/ e/ t etc. / for different line. After specific letters(like 'a') come some data i have to collect so i don't want to use fgets. It doesn't end running. Could you help me, please?

char com[21];
fscanf(src,"%s",com);
while(com!=EOF)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
    fscanf(src,"%s",com);
}

Body:
Simple way is to test if fscanf() succeeded as the loop condition and you don't need a fscanf() before the loop:

char com[21];

while(fscanf(src,"%20s",com) == 1)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
}

fscanf() returns the number of items successfully scanned. So, you don't need to check if it' returned EOF.

Note that I changed the format string to avoid buffer overflow. I suggest you use fgets() instead of fscanf() (and remember to take care of newline chars if it matters).


问:
List of versions of WriteLine missing from parenthese in Visual Studio
I'm trying to follow a tutorial in Visual Studio and I notice in the lesson that the teacher is able to scroll through all the 19 different versions of WriteLine if he clicks in the parenthesis and when I try to follow, clicking the down arrow, my cursor just travels down the Visual Studio page and I am unable the scroll though different versions of WriteLine. I've attached two screenshots to clarify what I mean. Any feedback would be great.

答:
The answer is quiet simple, while your typing cursor is between the two brackets,

press Ctrl + Shift + Space

Then the scrollable window will open, and you will be free to scrool through the overloads with the down/up arrow keys.


问:
Height 100% and css issue with footer
I am currently working on a script and in some pages there isn't enough content.In this case I want the page to cover 100% of the browser and put the footer at the bottom.I tried many codes and nothing seems to work I ended up by having a code like this:

```<code><div class="container">
<div id=nav>
NAV
</div>
<div id=core>
    <div id=content>
        <div id=tophea>
           TOP Content
        </div>
        <div id=msgs>
       MSG Content
        </div>
    </div>
    <div id="footer">
    Footer
    </div>
    </div>
</div>
</code>```

and css like this :

```<code>#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}
</code>```

Here is my jsfiddle : https://jsfiddle.net/k8k7o36b/

Any help will be appreciate. I'll be more than thankful if you add small explanation so I can understand what were I doing wrong.
Thanks

答:
Here is a generic flexbox solution.

flex-grow: 1; tells main to fill the remaining space. This also has the benefit of not having to set a specific height on your footer.

Flexbox Support

Chrome 21+

Firefox 28+

IE 10+

Edge

Safari 6.1+

*Some might support the 2012 syntax or require a prefix like -webkit-

html {
  height: 100%;
}
body {
  margin: 0;
  display: flex;
  flex-direction: column;
  min-height: 100%;
}
header {
  background-color: indianred;
}
main {
  flex-grow: 1;
  background-color: skyblue;
}
footer {
  background-color: gold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  Header
</header>
<main>
  Content
</main>
<footer>
  Footer
</footer></code>```

Title: Height 100% and css issue with footer

Body:
I am currently working on a script and in some pages there isn't enough content.In this case I want the page to cover 100% of the browser and put the footer at the bottom.I tried many codes and nothing seems to work I ended up by having a code like this:

NAV

           TOP Content

       MSG Content

    Footer

and css like this :

#container{
  height:100%
}
#nav{
  height:55px;
}
#core{
  height:100%
}
#content{
  height:100%;
  background:red;
}

Here is my jsfiddle : https://jsfiddle.net/k8k7o36b/

Any help will be appreciate. I'll be more than thankful if you add small explanation so I can understand what were I doing wrong.
Thanks

Body:
Here is a generic flexbox solution.

flex-grow: 1; tells main to fill the remaining space. This also has the benefit of not having to set a specific height on your footer.

Flexbox Support

Chrome 21+

Firefox 28+

IE 10+

Edge

Safari 6.1+

*Some might support the 2012 syntax or require a prefix like -webkit-

html {
  height: 100%;
}
body {
  margin: 0;
  display: flex;
  flex-direction: column;
  min-height: 100%;
}
header {
  background-color: indianred;
}
main {
  flex-grow: 1;
  background-color: skyblue;
}
footer {
  background-color: gold;
}

<header>
  Header
</header>
<main>
  Content
</main>
<footer>
  Footer
</footer>


问:
Unable to see whole pdf content after indexing pdf file in ES
Below is my code to index a pdf url in Elasticsearch:

```<code>import requests
from elasticsearch import Elasticsearch
es = Elasticsearch()
body = {
     "description" : "Extract attachment information",
     "processors" : [
        {
            "attachment" : {
            "field" : "data"
        }
      }
 ]
}
es.index(index='_ingest', doc_type='pipeline', id='attachment', body=body)
url = 'https://pubs.vmware.com/nsx-63/topic/com.vmware.ICbase/PDF/nsx_63_cross_vc_install.pdf'
response = requests.get(url)
import base64

data = base64.b64encode(response.content).decode('ascii')
 result2 = es.index(index='my_index', doc_type='my_type', pipeline='attachment',
              body={'data': data})
 result2
 doc = es.get(index='my_index', doc_type='my_type', id=result2['_id'],   _source_exclude=['data'])
 doc
 print(doc['_source']['attachment']['content'])
</code>```

Last line is printing the contents of pdf file till 63 page only out of 126.
Do I need to change any settings somewhere(already tried to increase the console o/p,dint helped).

Please provide pointers on this.

答:
There is a limit of 100000 characters extracted.
You can change it in the pipeline definition by setting indexed_chars.

See https://www.elastic.co/guide/en/elasticsearch/plugins/current/using-ingest-attachment.html

Body:
Below is my code to index a pdf url in Elasticsearch:

import requests
from elasticsearch import Elasticsearch
es = Elasticsearch()
body = {
     "description" : "Extract attachment information",
     "processors" : [
        {
            "attachment" : {
            "field" : "data"
        }
      }
 ]
}
es.index(index='_ingest', doc_type='pipeline', id='attachment', body=body)
url = 'https://pubs.vmware.com/nsx-63/topic/com.vmware.ICbase/PDF/nsx_63_cross_vc_install.pdf'
response = requests.get(url)
import base64

data = base64.b64encode(response.content).decode('ascii')
 result2 = es.index(index='my_index', doc_type='my_type', pipeline='attachment',
              body={'data': data})
 result2
 doc = es.get(index='my_index', doc_type='my_type', id=result2['_id'],   _source_exclude=['data'])
 doc
 print(doc['_source']['attachment']['content'])

Last line is printing the contents of pdf file till 63 page only out of 126.
Do I need to change any settings somewhere(already tried to increase the console o/p,dint helped).

Please provide pointers on this.


问:
Cannot open include file: 'io.h': No such file or directory
I was trying to compile a simple .pyx file using Cython.

```<code>print("hello")
</code>```

Here's my setup.py:

```<code>from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("hello.pyx")
)
</code>```

Then I run the command.

```<code>python setup.py build_ext --inplace
</code>```

The error is shown below. I've struggled on googling it but found nothing helpful.

```<code>    running build_ext
    building 'hello' extension
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD
-IC:\Users\Jackie\AppData\Local\Continuum\Anaconda3\include -IC:\Users\Jackie\AppData\Local\Continuum\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE"
"-IC:\Program Files (x86)\Windows Kits\10\include\wdf\ucrt"
"-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6\include\um"
"-IC:\Program Files (x86)\Windows Kits\8.1\include\shared"
"-IC:\Program Files (x86)\Windows Kits\8.1\include\um" "-IC:\Program
Files (x86)\Windows Kits\8.1\include\winrt" /Tchello.c
/Fobuild\temp.win32-3.5\Release\hello.obj
    hello.c
    c:\users\jackie\appdata\local\continuum\anaconda3\include\pyconfig.h(68):
fatal error C1083: Cannot open include file: 'io.h': No such file or
directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2
</code>```

Can someone help me to resolve the error, please?

I have Anaconda3 4.1.1, Python 3.5, and Visual Studio Express 2015 installed.

答:
Microsoft doesn't make any effort to make console development steps obvious anymore.  Visual Studio has long been packaged with some batch files to establish environment variables.  When the C++ CLI development options are selected in VS2015/2017, there are one or more shortcuts added to the start menu to execute these batch files.

For VS 2017 the various batch files all call:

```<code>C:\Program Files (x86)\Microsoft Visual Studio\Shared\14.0\VC\vcvarsall.bat
</code>```

with specific parameters.

Rather than setting a System or User Environment Variable, it would be better to call the specific batch file to meet your build needs.

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat
</code>```

or

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat
</code>```

One thing to bear in mind with Python/Ruby/etc, scripts will often need to elevate the execution shell to Administrator role in order to install packages.  If you execute the batch file in a non-Administrator shell, and the package installation requires elevation it will spawn a subshell which will not have the environment variables.  Therefore, you should run the batch file in an Administrator shell before calling the package manager or script.

ContentLicense: CC BY-SA 4.0

Body:
I was trying to compile a simple .pyx file using Cython.

print("hello")

Here's my setup.py:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize("hello.pyx")
)

Then I run the command.

python setup.py build_ext --inplace

The error is shown below. I've struggled on googling it but found nothing helpful.

    running build_ext
    building 'hello' extension
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD
-IC:\Users\Jackie\AppData\Local\Continuum\Anaconda3\include -IC:\Users\Jackie\AppData\Local\Continuum\Anaconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE"
"-IC:\Program Files (x86)\Windows Kits\10\include\wdf\ucrt"
"-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6\include\um"
"-IC:\Program Files (x86)\Windows Kits\8.1\include\shared"
"-IC:\Program Files (x86)\Windows Kits\8.1\include\um" "-IC:\Program
Files (x86)\Windows Kits\8.1\include\winrt" /Tchello.c
/Fobuild\temp.win32-3.5\Release\hello.obj
    hello.c
    c:\users\jackie\appdata\local\continuum\anaconda3\include\pyconfig.h(68):
fatal error C1083: Cannot open include file: 'io.h': No such file or
directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\cl.exe' failed with exit status 2

Can someone help me to resolve the error, please?

I have Anaconda3 4.1.1, Python 3.5, and Visual Studio Express 2015 installed.

Body:
Microsoft doesn't make any effort to make console development steps obvious anymore.  Visual Studio has long been packaged with some batch files to establish environment variables.  When the C++ CLI development options are selected in VS2015/2017, there are one or more shortcuts added to the start menu to execute these batch files.

For VS 2017 the various batch files all call:

C:\Program Files (x86)\Microsoft Visual Studio\Shared\14.0\VC\vcvarsall.bat

with specific parameters.

Rather than setting a System or User Environment Variable, it would be better to call the specific batch file to meet your build needs.

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat

or

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat

One thing to bear in mind with Python/Ruby/etc, scripts will often need to elevate the execution shell to Administrator role in order to install packages.  If you execute the batch file in a non-Administrator shell, and the package installation requires elevation it will spawn a subshell which will not have the environment variables.  Therefore, you should run the batch file in an Administrator shell before calling the package manager or script.


问:
URL to fill input fields
There is a website that I use regularly that has quite a few log in fields. I'm trying to formulate a link to pre-populate most of them.
The fields in question are formatted like this:

```<code><input id="frm:User" type="text" name="frm:User" autocomplete="off" style="width:80%" />
</code>```

I've tried using "http://website?frm:User=User&frmGroup=Group" to no avail. Any suggestions?

Thanks!

答:
There exists no standard way to fill in HTML inputs by passing values into the URL's query string. The URL including the query string parameters is sent to the server as a request, and the server generates the HTML as a response. It's completely up to the remote server how to interpret the incoming query parameters and how to generate the HTML.

What is the reason exactly you want the fields for this particular site to be auto filled? Maybe a password manager like lastpass could do the trick for you?

Title: URL to fill input fields

Body:
There is a website that I use regularly that has quite a few log in fields. I'm trying to formulate a link to pre-populate most of them.
The fields in question are formatted like this:

<input id="frm:User" type="text" name="frm:User" autocomplete="off" style="width:80%" />

I've tried using "http://website?frm:User=User&frmGroup=Group" to no avail. Any suggestions?

Thanks!


问:
Does the .prpt file (report template file) contain datasource information?
When I created a report using Pentaho Report Designer, it outputs a report file having .prpt extension. After that I found an example on internet where the following code was used to display the report in html format:

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     ResourceManager manager = new ResourceManager();
     manager.registerDefaults();
     String reportPath = "file:" +
     this.getServletContext().getRealPath("sampleReport.prpt");

     try {
         Resource res = manager.createDirectly(new URL(reportPath), MasterReport.class);
         MasterReport report = (MasterReport) res.getResource();
         HtmlReportUtil.createStreamHTML(report, response.getOutputStream());
     } catch (Exception e) {
         e.printStackTrace();
     }
 }
</code>```

And the report got printed successfully. So as we haven't specified any datasource information here, I think that the .prpt file contains that information in it.

If that's true, then Isn't Jasper is better Reporting tool than Pentaho because when we display Jasper reports, we have to provide datasource details also so in that way our report is flexible and is not bound to any particular database.

答:
The PRPT file usually contains all information that is needed to run the report. You can provide your own datasources by modifying the MasterReport object that you get back from the ResourceManager.

However, I yet have to see valid use cases where that kind of operation actually makes sense. To provide connection information for SQL datasources at runtime you usually use the JNDI subsystem of your web-application or J2EE server.

99.99% of all reports that run on the Pentaho BI-Server do NOT have a need to manually replace datasources to run. And the remaining 0.01% are legacy reports from ancient reporting engine versions.

Body:
When I created a report using Pentaho Report Designer, it outputs a report file having .prpt extension. After that I found an example on internet where the following code was used to display the report in html format:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     ResourceManager manager = new ResourceManager();
     manager.registerDefaults();
     String reportPath = "file:" +
     this.getServletContext().getRealPath("sampleReport.prpt");

     try {
         Resource res = manager.createDirectly(new URL(reportPath), MasterReport.class);
         MasterReport report = (MasterReport) res.getResource();
         HtmlReportUtil.createStreamHTML(report, response.getOutputStream());
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

And the report got printed successfully. So as we haven't specified any datasource information here, I think that the .prpt file contains that information in it.

If that's true, then Isn't Jasper is better Reporting tool than Pentaho because when we display Jasper reports, we have to provide datasource details also so in that way our report is flexible and is not bound to any particular database.

ContentLicense: CC BY-SA 2.5


问:
Conv1D on 2D input
Can someone explain to me what happens when a keras Conv1D layer is fed 2D input?
Such as:

```<code>model=Sequential()
model.add(Conv1D(input_shape=(9000,2),kernel_size=200,strides=1,filters=20))
</code>```

Varying the input size between (9000,1) and (9000,2) and calling model.summary(), I see that the output shape stays the same, but the number of parameters changes. So, does that mean that different filters are trained for each channel, but the output is summed/averaged across the 2nd dimension before outputting? Or what?

答:
Here is a visual illustration</p>

```<code>kernel_size = (2, )

-------------
| 1 1 1 1 1 |                <---- kernel dim = kernel_size X 5
| 2 2 2 2 2 |
-------------
  3 3 3 3 3

--------------------------
| 1 1 1 1 1 1 1 1 1 1 1 1 |  <---- kernel dim = kernel_length X 12
| 2 2 2 2 2 2 2 2 2 2 2 2 |        i.e more params! but after
--------------------------         you apply say MaxPool1D(pool_size=(2,2))
  3 3 3 3 3 3 3 3 3 3 3 3          in both cases, then layer shapes from here
                                   on out are the same, thus same outputs!
</code>```

Title: Conv1D on 2D input

Body:
Can someone explain to me what happens when a keras Conv1D layer is fed 2D input?
Such as:

model=Sequential()
model.add(Conv1D(input_shape=(9000,2),kernel_size=200,strides=1,filters=20))

Varying the input size between (9000,1) and (9000,2) and calling model.summary(), I see that the output shape stays the same, but the number of parameters changes. So, does that mean that different filters are trained for each channel, but the output is summed/averaged across the 2nd dimension before outputting? Or what?

Body:
Here is a visual illustration

kernel_size = (2, )

-------------
| 1 1 1 1 1 |                <---- kernel dim = kernel_size X 5
| 2 2 2 2 2 |
-------------
  3 3 3 3 3

--------------------------
| 1 1 1 1 1 1 1 1 1 1 1 1 |  <---- kernel dim = kernel_length X 12
| 2 2 2 2 2 2 2 2 2 2 2 2 |        i.e more params! but after
--------------------------         you apply say MaxPool1D(pool_size=(2,2))
  3 3 3 3 3 3 3 3 3 3 3 3          in both cases, then layer shapes from here
                                   on out are the same, thus same outputs!


答:
Please note that fscanf returns an integer which can indicate EOF when the End of File is reached. Please refer to the man pages for more detail.

Your code will have to modified like below:

```<code>char com[21];
int ret;
ret = fscanf(src,"%s",com);
while(ret!=EOF)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
    ret = fscanf(src,"%s",com);
}
</code>```

Title: How to read until end of file C, fscanf

Body:
Please note that fscanf returns an integer which can indicate EOF when the End of File is reached. Please refer to the man pages for more detail.

Your code will have to modified like below:

char com[21];
int ret;
ret = fscanf(src,"%s",com);
while(ret!=EOF)
{
    if(com[0]=='a')
        fprintf(dest,"%s 1",com);
     if(com[0]=='s')
        fprintf(dest,"%s 2",com);
    ret = fscanf(src,"%s",com);
}


问:
bash Shell - not exiting for if-elif conditions
Bash shell not exiting - for below code - although I don't get any errors.
Please help me with exit mechanism

When I press CTRL+D i get the output correctly for appropriate conditions

```<code>#!/bin/bash

read un < $HOME/un.txt

sqlplus $un @report.sql > Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls

mail_to="xxxx"

count=$(grep -c "no rows selected" $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls)

error=$(grep -c ERROR $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls)

if [ "$error" -gt 0 ]

then

    echo -e "Error occurred\n\nNOTE: In case of Schema/password change is done to HARP database, the private variables in the script needs modifications - SCM team Will take appropriate action" |mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  $mail_to

elif [ "$count" -gt 0 ]

then

    echo -e "Hi All\n\nNo Packages where migrated for `date -d "1 day ago" +"%b_%d_%Y"` \n\n\nThanks & Regards \nSCM team \n\n\n" |mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  $mail_to

else

    cat mail_content_2 | mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  -a $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls $mail_to

fi

exit 0
</code>```

答:
The issue was with username / password for database - As it was wrong - the control did not return from SQL and was waiting to re-enter password .

To fix this I have used Below one time logon option (-l flag) (it will not re-prompt for pwd) if password is wrong it will exit sql immediately :)

```<code>sqlplus -l $un @report.sql> Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls
</code>```

Body:
Bash shell not exiting - for below code - although I don't get any errors.
Please help me with exit mechanism

When I press CTRL+D i get the output correctly for appropriate conditions

#!/bin/bash

read un < $HOME/un.txt

sqlplus $un @report.sql > Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls

mail_to="xxxx"

count=$(grep -c "no rows selected" $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls)

error=$(grep -c ERROR $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls)

if [ "$error" -gt 0 ]

then

    echo -e "Error occurred\n\nNOTE: In case of Schema/password change is done to HARP database, the private variables in the script needs modifications - SCM team Will take appropriate action" |mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  $mail_to

elif [ "$count" -gt 0 ]

then

    echo -e "Hi All\n\nNo Packages where migrated for `date -d "1 day ago" +"%b_%d_%Y"` \n\n\nThanks & Regards \nSCM team \n\n\n" |mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  $mail_to

else

    cat mail_content_2 | mailx -s "Package Migration Report for `date -d "1 day ago" +"%b_%d_%Y"` "  -a $HOME/Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls $mail_to

fi

exit 0

Body:
The issue was with username / password for database - As it was wrong - the control did not return from SQL and was waiting to re-enter password .

To fix this I have used Below one time logon option (-l flag) (it will not re-prompt for pwd) if password is wrong it will exit sql immediately :)

sqlplus -l $un @report.sql> Package_migration_report.`date -d "1 day ago" +"%b_%d_%Y"`.xls


问:
ReactJS How to toggle elements to hide or show
I am very new to React and the ES6 syntax I have a chat widget that i want to toggle to show and hide as i click the header,and I have already implemented an onClick handler, but in terms of the logic I am having trouble finding a similar implementation online. this is my code:</p>

```<code>import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {

  handleClick(event) {
    console.log("Hide or unhide chat body")
  }

  render() {
    return (
      <div className={chat.container}>
        <div onClick={this.handleClick.bind(this)}
             className={chat.header}>
          <span className={chat.name}>Idol</span>
        </div>
        <div className={chat.body}>
          This is the Body of the chat
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);
</code>```

答:
Use a state variable that will store the current state, whether to show the body or not. On the basis of that variable render the body of the Chart, that is called conditional rendering.

Check this:

```<code>class ChatWidget extends Component {

    constructor(){
        super();
        this.state={isShowBody: true}
    }

    handleClick(event) {
        this.setState({isShowBody: !this.state.isShowBody})
    }

    render() {
        return (
            <div className={chat.container}>
                <div onClick={this.handleClick.bind(this)} className={chat.header}>
                  <span className={chat.name}>Idol</span>
                </div>
                {this.state.isShowBody ?
                    <div className={chat.body}>
                        This is the Body of the chat
                    </div>
                : null}
            </div>
        );
    }
}
</code>```

Body:
I am very new to React and the ES6 syntax I have a chat widget that i want to toggle to show and hide as i click the header,and I have already implemented an onClick handler, but in terms of the logic I am having trouble finding a similar implementation online. this is my code:

import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';

class ChatWidget extends Component {

  handleClick(event) {
    console.log("Hide or unhide chat body")
  }

  render() {
    return (

          Idol

          This is the Body of the chat

    );
  }
}

function mapStateToProps(state) {
  return {
    user: state.activeUser
  };
}

export default connect(mapStateToProps)(ChatWidget);

Body:
Use a state variable that will store the current state, whether to show the body or not. On the basis of that variable render the body of the Chart, that is called conditional rendering.

Check this:

class ChatWidget extends Component {

    constructor(){
        super();
        this.state={isShowBody: true}
    }

    handleClick(event) {
        this.setState({isShowBody: !this.state.isShowBody})
    }

    render() {
        return (
            <div className={chat.container}>
                <div onClick={this.handleClick.bind(this)} className={chat.header}>
                  <span className={chat.name}>Idol</span>
                </div>
                {this.state.isShowBody ?
                    <div className={chat.body}>
                        This is the Body of the chat
                    </div>
                : null}
            </div>
        );
    }
}


问:
Mansory not work after jQuery Ajax
I have a problem with Masonry plugin.

I try to load new content inside of a div container #myparts.

Ajax works but div containers .part overlapping each other and I dont know why.

I have tried many solutions from the Internet but they don't work. Masonry should reload .parts again after AJAX but it doesn't work.

Here is my Code:

```<code><body>
<!--

 data-user: is user-ID
 data-article: is article-ID

-->

<div id="wrapper">
<div id="myparts" data-user="1">
    <div class="part" data-article="1"></div>
    <div class="part" data-article="2"></div>
    <div class="part" data-article="3"></div>
    <div class="part" data-article="4"></div>
</div>
<div id="button"></div>
</div>
</body>
</code>```

My jQuery code:

```<code> // My Ajax
 $(document).on("click", "#wrapper > #button", function () {

 var $grid = $("#wrapper > #myparts").masonry({columnWidth: 22, itemSelector: '.part', isFitWidth: true}); // Masonry plugin

 var user_d = $("#wrapper > #myparts").data("bid");
 var article_id = $("#wrapper > #myparts > .part").last().data("article");

 $("#pleasewait").fadeIn(); // open progressbar.

 $.ajax({
  url: "ajax/new-content.php",
  method: "POST",
  data: {user: user_d, article: article_id},
  dataType: "html",
  cache: false,
  success: function (data) {
  if (data !== '') {
   $("#wrapper > #myparts").append(data); // Ajax work.
  } else {
    $("#wrapper > #myparts > #button").remove(); // Remove button if no more content in database
  $grid.masonry();
  }
 },
 complete: function () {
  $("#pleasewait").fadeOut(500); // close progressbar.
 }
 });
 });
</code>```

答:
Try initializing your masonry outside your button click function, this way it doesn't depend on that (unless is what you want to ).

And look for your user_d variable, who's supposed to be getting the data attribute from the #wrapper > #myparts element, but you're passing it the bid data attribute.

See this version using your code:

```<code><div id="wrapper">
    <div id="myparts" data-user="1">
        <div class="part" data-article="1">
          <img src="https://loremflickr.com/320/240" alt="">
        </div>
        <div class="part" data-article="2">
          <img src="https://loremflickr.com/320/240" alt="">
        </div>
        <div class="part" data-article="3">
          <img src="https://loremflickr.com/320/240" alt="">
        </div>
        <div class="part" data-article="4">
          <img src="https://loremflickr.com/320/240" alt="">
        </div>
    </div>
    <div id="button" style="margin-top: 250px; border: 1px solid black; width: 150px;">I'm a button</div>
  </div>
</code>```

I suppose you have certain elements inside every part div (the button is just styled to be down the content).

```<code><script>
    var $grid = $("#wrapper > #myparts").masonry({
      columnWidth: 320,
      itemSelector: '.part',
      isFitWidth: true
    }); // Masonry plugin

    $('#button').click(function () {
      let user_d = $("#wrapper > #myparts").data("user"),
          article_id = $("#wrapper > #myparts > .part").last().data("article");

      $("#pleasewait").fadeIn(); // open progressbar.

      $.ajax({
        url: "ajax/new-content.php",
        method: "POST",
        data: {
          user: user_d,
          article: article_id
        },
        dataType: "html",
        cache: false,
        success: function (data) {
          if (data !== '') {
            console.log(data);
            let $items = $(data);
            $grid.append( $items ).masonry( 'appended', $items );
          } else {
            // Remove button if no more content in database
            $("#wrapper > #myparts > #button").remove();
            $grid.masonry();
          }
        },
        complete: function () {
          $("#pleasewait").fadeOut(500); // close progressbar.
        }
      });
    });
  </script>
</code>```

In your script, initialize your grid masonry outside your click event, then make the AJAX request, passing the properly data:

```<code> let user_d = $("#wrapper > #myparts").data("user"),
      article_id = $("#wrapper > #myparts > .part").last().data("article");
</code>```

Then in your success callback do the append of the items, "converting" every of them to its jQuery version, this is:

```<code>if (data !== '') {
  console.log(data);
  let $items = $(data);
  $grid.append( $items ).masonry( 'appended', $items );
}
...
</code>```

My ajax/new-content.php file just checks if the data was sent, and return the div, to be appended:

```<code><?php

if (isset($_POST['user']) && isset($_POST['article'])) {
  echo '<div class="part" data-article="5"><img src="http://loremflickr.com/320/240" alt=""></div>';
}
</code>```

Here's a demo pen in Codepen.

Title: Mansory not work after jQuery Ajax

Body:
I have a problem with Masonry plugin.

I try to load new content inside of a div container #myparts.

Ajax works but div containers .part overlapping each other and I dont know why.

I have tried many solutions from the Internet but they don't work. Masonry should reload .parts again after AJAX but it doesn't work.

Here is my Code:

My jQuery code:

 // My Ajax
 $(document).on("click", "#wrapper > #button", function () {

 var $grid = $("#wrapper > #myparts").masonry({columnWidth: 22, itemSelector: '.part', isFitWidth: true}); // Masonry plugin

 var user_d = $("#wrapper > #myparts").data("bid");
 var article_id = $("#wrapper > #myparts > .part").last().data("article");

 $("#pleasewait").fadeIn(); // open progressbar.

 $.ajax({
  url: "ajax/new-content.php",
  method: "POST",
  data: {user: user_d, article: article_id},
  dataType: "html",
  cache: false,
  success: function (data) {
  if (data !== '') {
   $("#wrapper > #myparts").append(data); // Ajax work.
  } else {
    $("#wrapper > #myparts > #button").remove(); // Remove button if no more content in database
  $grid.masonry();
  }
 },
 complete: function () {
  $("#pleasewait").fadeOut(500); // close progressbar.
 }
 });
 });

Body:
Try initializing your masonry outside your button click function, this way it doesn't depend on that (unless is what you want to ).

And look for your user_d variable, who's supposed to be getting the data attribute from the #wrapper > #myparts element, but you're passing it the bid data attribute.

See this version using your code:

<div id="wrapper">
    <div id="myparts" data-user="1">
        <div class="part" data-article="1">
          <img src="https://loremflickr.com/320/240" alt="">
        </div>
        <div class="part" data-article="2">
          <img src="https://loremflickr.com/320/240" alt="">
        </div>
        <div class="part" data-article="3">
          <img src="https://loremflickr.com/320/240" alt="">
        </div>
        <div class="part" data-article="4">
          <img src="https://loremflickr.com/320/240" alt="">
        </div>
    </div>
    <div id="button" style="margin-top: 250px; border: 1px solid black; width: 150px;">I'm a button</div>
  </div>

I suppose you have certain elements inside every part div (the button is just styled to be down the content).

<script>
    var $grid = $("#wrapper > #myparts").masonry({
      columnWidth: 320,
      itemSelector: '.part',
      isFitWidth: true
    }); // Masonry plugin

    $('#button').click(function () {
      let user_d = $("#wrapper > #myparts").data("user"),
          article_id = $("#wrapper > #myparts > .part").last().data("article");

      $("#pleasewait").fadeIn(); // open progressbar.

      $.ajax({
        url: "ajax/new-content.php",
        method: "POST",
        data: {
          user: user_d,
          article: article_id
        },
        dataType: "html",
        cache: false,
        success: function (data) {
          if (data !== '') {
            console.log(data);
            let $items = $(data);
            $grid.append( $items ).masonry( 'appended', $items );
          } else {
            // Remove button if no more content in database
            $("#wrapper > #myparts > #button").remove();
            $grid.masonry();
          }
        },
        complete: function () {
          $("#pleasewait").fadeOut(500); // close progressbar.
        }
      });
    });
  </script>

In your script, initialize your grid masonry outside your click event, then make the AJAX request, passing the properly data:

 let user_d = $("#wrapper > #myparts").data("user"),
      article_id = $("#wrapper > #myparts > .part").last().data("article");

Then in your success callback do the append of the items, "converting" every of them to its jQuery version, this is:

if (data !== '') {
  console.log(data);
  let $items = $(data);
  $grid.append( $items ).masonry( 'appended', $items );
}
...

My ajax/new-content.php file just checks if the data was sent, and return the div, to be appended:

<?php

if (isset($_POST['user']) && isset($_POST['article'])) {
  echo '<div class="part" data-article="5"><img src="http://loremflickr.com/320/240" alt=""></div>';
}

Here's a demo pen in Codepen.


问:
chroot with SSH and SFTP
I'm stuck on something quite complicated it seems, but I'm pretty sure I'm not the first one to face this problem, still I can't seem to find someone having the same problem on any forum.

As said in the title I want to make a chroot for users that works with SSH and SFTP. I'm currently stuck with one or the other and that's not ok with me.

Following tutorials, I modified the sshd_config file and added this line as suggested:

```<code>ForceCommand internal-sftp
</code>```

That allows me to connect when using a linux terminal but it's a bit tricky for windows user using putty even if it seems you can use it with psftp. But you can't use all the commands you put inside the jail env.

Does anyone has already figure this one out?

As stated before my chroot is working, so it's not really a configuration issue.

答:
Finally I found a solution reading another tutorial.

If anyone is troubled with this another time, in sshd_config, most tutorial juste leave the subsystem line in the file by default.

To resolve my issue I just did this:

```<code>#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem       sftp    internal-sftp
</code>```

That did the work and I can now access my server in SSH and SFTP with the chrooted accounts.

It's always just after you post on a forum that you find a solution.

Have a good day everyone.

Title: chroot with SSH and SFTP

Body:
I'm stuck on something quite complicated it seems, but I'm pretty sure I'm not the first one to face this problem, still I can't seem to find someone having the same problem on any forum.

As said in the title I want to make a chroot for users that works with SSH and SFTP. I'm currently stuck with one or the other and that's not ok with me.

Following tutorials, I modified the sshd_config file and added this line as suggested:

ForceCommand internal-sftp

That allows me to connect when using a linux terminal but it's a bit tricky for windows user using putty even if it seems you can use it with psftp. But you can't use all the commands you put inside the jail env.

Does anyone has already figure this one out?

As stated before my chroot is working, so it's not really a configuration issue.

Body:
Finally I found a solution reading another tutorial.

If anyone is troubled with this another time, in sshd_config, most tutorial juste leave the subsystem line in the file by default.

To resolve my issue I just did this:

#Subsystem sftp /usr/lib/openssh/sftp-server
Subsystem       sftp    internal-sftp

That did the work and I can now access my server in SSH and SFTP with the chrooted accounts.

It's always just after you post on a forum that you find a solution.

Have a good day everyone.


问:
Trying to pass a background color through intentPutExtra
I am trying to set the background color with intentPutExtra but it doesn't seem to change, this is my intent from the MainActivity:

```<code>  @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {

                    Intent intent = new Intent(MainActivity.this, ktmList.class);
                   intent.putExtra("backgroundColor", getResources().getColor(R.color.colorOrange));
                    startActivity(intent);
}
</code>```

and this is how  I try to change the background color:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.models_list);

    Intent intent = new Intent();
    int backgroundColor = intent.getIntExtra("backgroundColor", -1);

    LinearLayout rootView = (LinearLayout)findViewById(R.id.models_rootView);
    rootView.setBackgroundColor(backgroundColor);
</code>```

and this is the models_list xml file:

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

<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/models_rootView"
    android:orientation="vertical">

<ListView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/models_list"
                android:padding="16dp"/>

</LinearLayout>
</code>```

答:
Use rootView.setBackgroundResource(backgroundColor); instead of rootView.setBackgroundColor(backgroundColor);

Also change

```<code>intent.putExtra("backgroundColor", getResources().getColor(R.color.colorOrange));
</code>```

to

```<code>intent.putExtra("backgroundColor", R.color.colorOrange);
</code>```

That worked for me

Body:
I am trying to set the background color with intentPutExtra but it doesn't seem to change, this is my intent from the MainActivity:

  @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {

                    Intent intent = new Intent(MainActivity.this, ktmList.class);
                   intent.putExtra("backgroundColor", getResources().getColor(R.color.colorOrange));
                    startActivity(intent);
}

and this is how  I try to change the background color:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.models_list);

    Intent intent = new Intent();
    int backgroundColor = intent.getIntExtra("backgroundColor", -1);

    LinearLayout rootView = (LinearLayout)findViewById(R.id.models_rootView);
    rootView.setBackgroundColor(backgroundColor);

and this is the models_list xml file:

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

<LinearLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/models_rootView"
    android:orientation="vertical">

<ListView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/models_list"
                android:padding="16dp"/>

</LinearLayout>

Body:
Use rootView.setBackgroundResource(backgroundColor); instead of rootView.setBackgroundColor(backgroundColor);

Also change

intent.putExtra("backgroundColor", getResources().getColor(R.color.colorOrange));

to

intent.putExtra("backgroundColor", R.color.colorOrange);

That worked for me


问:
Assignment, about 2d arrays
I would like some assistance with a problem.

I have this text file:

I input the contents of the text into a string 2d array and converted it to a integer 2d array. When i converted to the int array the nan's were replaced with a zero. I now proceeded to find the max and min of each line in the 2d array and find the average of both, which I successfully achieved. My problem is I want to assign the average value found for each line to the zero. I tried using two for loops but it replacing all the zero's with the average of the first line. Can anyone please assist me.

My code:

```<code>int min = 200;

int main() {

    fstream imagefile;
    imagefile.open("Text.txt");

    if (imagefile.fail()) { // checking for errors in file
        cerr << "Error opening file" << endl;
        exit(1);

    std::string data[3][11];
    int integer[3][11];
    for (int k = 0; k < 3; k++) {

        for (int i = 0; i < 11; i++) {
            imagefile >> data[k][i]; // read from file

        }
    }

    cin.get();

    for (int k = 0; k < 3; k++) {

        for (int i = 0; i < 11; i++)
        {
            integer[k][i] = atoi(data[k][i].c_str()); // converts string to int
        }
    }
    cin.get();

    for (int k = 0; k < 3; k++) { //k is the row  and i is the column

        for (int i = 0; i < 11; i++) {
            cout << integer[k][i] << "  ";

        }
        cout << endl;
    }

    int row, col;
    for (row = 0; row < 3; row++) { //k is the row  and i is the column

        max = integer[row][0];
        min = integer[row][0];

        for (col = 0; col < 11; col++) {
            if (integer[row][col] > max) { max = integer[row][col]; }
            if ((integer[row][col] < min) && (integer[row][col] != 0)) { min = integer[row][col]; }
            //if (integer[row][col] == 0) { avg == integer[row][col]; }

            sum = max + min;
            avg = sum / 2;
        }
            for (int k = 0; k < integer[k][i]; k++) {  //k is the row  and i is the column
                for (int i = 0; i < 11; i++) {
                    if (integer[k][i] == 0) {

                        integer[k][i] = avg;

                    }
                    cout << integer[k][i] << "  ";

                }
                cout << endl;
            }

        cout << max << " ";
        cout << min << " ";
        cout << avg << " " << endl;
    }

    imagefile.close();
    system("pause");
    return 0;
}
</code>```

答:
There are multiple problems with the code you've presented. This line:

```<code>    imagefile >> data[k][i];
</code>```

Error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

and:

```<code>    for (int k = 0; k < integer[k][i]; k++)
</code>```

Error C2065: 'i' : undeclared identifier (78)

Try posting the actual code.

Title: Assignment, about 2d arrays

Body:
I would like some assistance with a problem.

I have this text file:

I input the contents of the text into a string 2d array and converted it to a integer 2d array. When i converted to the int array the nan's were replaced with a zero. I now proceeded to find the max and min of each line in the 2d array and find the average of both, which I successfully achieved. My problem is I want to assign the average value found for each line to the zero. I tried using two for loops but it replacing all the zero's with the average of the first line. Can anyone please assist me.

My code:

int min = 200;

int main() {

    fstream imagefile;
    imagefile.open("Text.txt");

    if (imagefile.fail()) { // checking for errors in file
        cerr << "Error opening file" << endl;
        exit(1);

    std::string data[3][11];
    int integer[3][11];
    for (int k = 0; k < 3; k++) {

        for (int i = 0; i < 11; i++) {
            imagefile >> data[k][i]; // read from file

        }
    }

    cin.get();

    for (int k = 0; k < 3; k++) {

        for (int i = 0; i < 11; i++)
        {
            integer[k][i] = atoi(data[k][i].c_str()); // converts string to int
        }
    }
    cin.get();

    for (int k = 0; k < 3; k++) { //k is the row  and i is the column

        for (int i = 0; i < 11; i++) {
            cout << integer[k][i] << "  ";

        }
        cout << endl;
    }

    int row, col;
    for (row = 0; row < 3; row++) { //k is the row  and i is the column

        max = integer[row][0];
        min = integer[row][0];

        for (col = 0; col < 11; col++) {
            if (integer[row][col] > max) { max = integer[row][col]; }
            if ((integer[row][col] < min) && (integer[row][col] != 0)) { min = integer[row][col]; }
            //if (integer[row][col] == 0) { avg == integer[row][col]; }

            sum = max + min;
            avg = sum / 2;
        }
            for (int k = 0; k < integer[k][i]; k++) {  //k is the row  and i is the column
                for (int i = 0; i < 11; i++) {
                    if (integer[k][i] == 0) {

                        integer[k][i] = avg;

                    }
                    cout << integer[k][i] << "  ";

                }
                cout << endl;
            }

        cout << max << " ";
        cout << min << " ";
        cout << avg << " " << endl;
    }

    imagefile.close();
    system("pause");
    return 0;
}

Body:
There are multiple problems with the code you've presented. This line:

    imagefile >> data[k][i];

Error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

and:

    for (int k = 0; k < integer[k][i]; k++)

Error C2065: 'i' : undeclared identifier (78)

Try posting the actual code.


问:
how to print all text in a specific tag using xpath in python?
I am new to python and xpath. And I am trying to print the text inside the tag 'p' from an html file.
I have this portion of code:

```<code><section>
    <p>Hello <br>nnn</br> <a href="google.com"> dfgdfg </a> World!</p>
</section>
</code>```

I want to print: Hello nnn World! and The code I am using is:

```<code>for el in html.xpath('//section/p'):
    print (el.text)
</code>```

But the printed text is only: Hello
Can any one help me solve this?

答:
Try to use XPath '//section/p/text()' as below to get Hello nnn World!:

```<code>for el in html.xpath('//section/p/text()'):
    print (el, end='')
</code>```

Body:
I am new to python and xpath. And I am trying to print the text inside the tag 'p' from an html file.
I have this portion of code:

Hello
nnn
  dfgdfg  World!

I want to print: Hello nnn World! and The code I am using is:

for el in html.xpath('//section/p'):
    print (el.text)

But the printed text is only: Hello
Can any one help me solve this?

Body:
Try to use XPath '//section/p/text()' as below to get Hello nnn World!:

for el in html.xpath('//section/p/text()'):
    print (el, end='')


答:
What you can do is create a css class

```<code>.hidden {
  display: none;
}
</code>```

And dynamically toggle that class on your <div class={chat.body}.

So add an id to the div so it's easier to grab.

```<code><div class={chat.body} id='chat-body'>
  ...
</div>
</code>```

And inside your handleClick method

```<code>handleClick(event) {
  let chat = document.getElementById("chat-body");

  chat-body.classList.toggle('hidden')
}
</code>```

Title: ReactJS How to toggle elements to hide or show

Body:
What you can do is create a css class

.hidden {
  display: none;
}

And dynamically toggle that class on your <div class={chat.body}.

So add an id to the div so it's easier to grab.

<div class={chat.body} id='chat-body'>
  ...
</div>

And inside your handleClick method

handleClick(event) {
  let chat = document.getElementById("chat-body");

  chat-body.classList.toggle('hidden')
}


问:
Trying to segment characters and save it in order to image files. But contours are being drawn in a different order?
This is the image input.

Using python opencv. I did some pre-processing and found contours using

```<code>contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
</code>```

then i did the following to save each character

```<code>img1 = cv2.imread("test26.png")
nu = 1
fin = "final"
for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    img2 = img1[y:y+h, x:x+w]
    img3 = Image.fromarray(img2)
    filename = fin + str(nu) + ".png"
    nu = nu + 1
    img3.save(filename)
</code>```

But characters are saved in a tree like order. I don't understand the order.

my intention is to get character by character and ocr it in order and save as text.

答:
This code sorts the bounding boxes and achieves what was probably intended, does it?</p>

```<code>import cv2
strFormula="1!((x+1)*(x+2))" # '!' means a character is not allowed in file name
img = cv2.imread("test26.png")
imgGray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
ret, imgThresh = cv2.threshold(imgGray, 127, 255, 0)

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if int(major_ver)  < 3 :
    contours , hierarchy  = cv2.findContours(imgThresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
else :
    image, contours , _   = cv2.findContours(imgThresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
#:if

lstBoundingBoxes = []
for cnt in contours:  lstBoundingBoxes.append(cv2.boundingRect(cnt))
lstBoundingBoxes.sort()

charNo=0
for item in lstBoundingBoxes[1:]: # skip first element ('bounding box' == entire image)
    charNo += 1
    fName = "charAtPosNo-" + str(charNo).zfill(2) + "_is_[ " + strFormula[charNo-1] + " ]"+ ".png";
    x,y,w,h = item
    cv2.imwrite(fName, img[y:y+h, x:x+w])
</code>```

Body:
This is the image input.

Using python opencv. I did some pre-processing and found contours using

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

then i did the following to save each character

img1 = cv2.imread("test26.png")
nu = 1
fin = "final"
for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    img2 = img1[y:y+h, x:x+w]
    img3 = Image.fromarray(img2)
    filename = fin + str(nu) + ".png"
    nu = nu + 1
    img3.save(filename)

But characters are saved in a tree like order. I don't understand the order.

my intention is to get character by character and ocr it in order and save as text.

Body:
This code sorts the bounding boxes and achieves what was probably intended, does it?

import cv2
strFormula="1!((x+1)*(x+2))" # '!' means a character is not allowed in file name
img = cv2.imread("test26.png")
imgGray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
ret, imgThresh = cv2.threshold(imgGray, 127, 255, 0)

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if int(major_ver)  < 3 :
    contours , hierarchy  = cv2.findContours(imgThresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
else :
    image, contours , _   = cv2.findContours(imgThresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
#:if

lstBoundingBoxes = []
for cnt in contours:  lstBoundingBoxes.append(cv2.boundingRect(cnt))
lstBoundingBoxes.sort()

charNo=0
for item in lstBoundingBoxes[1:]: # skip first element ('bounding box' == entire image)
    charNo += 1
    fName = "charAtPosNo-" + str(charNo).zfill(2) + "_is_[ " + strFormula[charNo-1] + " ]"+ ".png";
    x,y,w,h = item
    cv2.imwrite(fName, img[y:y+h, x:x+w])


问:
circle with gradient background border and changing colors with js
I need to make a circular border something like this code snippet / fiddle:

.box {
  width: 250px;
  height: 250px;
  position: relative;
  margin: auto;
  margin: 30px;
  border-radius: 50%;
  background: #fff;
}
.box:after {
  content: '';
  position: absolute;
  top: -15px;
  bottom: -15px;
  right: -15px;
  left: -15px;
  background-image: linear-gradient(to bottom left, #7B73A4 0%, #150E5E 100%);
  z-index: -1;
  border-radius: inherit;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

except the inner space needs to be transparent and there needs to be a way of changing the border's gradient color.

I can use anything with js/jquery/css/html

Is it possible? If yes, how? Thanks

答:
It is possible using a <canvas> element (which is supported in all browsers except for IE 8 and older).

Here are some useful links:

Canvas tutorial - MDN

Canvas API - MDN

Canvas Cheat Sheet

You could also use an SVG element, but that makes the animation much more difficult.

Body:
I need to make a circular border something like this code snippet / fiddle:

.box {
  width: 250px;
  height: 250px;
  position: relative;
  margin: auto;
  margin: 30px;
  border-radius: 50%;
  background: #fff;
}
.box:after {
  content: '';
  position: absolute;
  top: -15px;
  bottom: -15px;
  right: -15px;
  left: -15px;
  background-image: linear-gradient(to bottom left, #7B73A4 0%, #150E5E 100%);
  z-index: -1;
  border-radius: inherit;
}

except the inner space needs to be transparent and there needs to be a way of changing the border's gradient color.

I can use anything with js/jquery/css/html

Is it possible? If yes, how? Thanks


问:
CRT detected that the application wrote to memory after end of heap buffer (new/delete) classes
I am receiving the "Debug error" CRT detected that the application wrote to memory after end of heap. But I don't understand why and can't find any similar examples.

The full code is...
Although I think it may just be a problem with main.

```<code>#include <iostream>
#include <cmath>
#include <array>

using namespace std;
// Declare global consts
const double pi = 3.1415926583;

// Base class Shape
class Shape{
protected:
    double *sides;
public:
    Shape(const int n){ //parameterized for n dimensional shape
    sides = new double[n];
}
// need virtual destructor
virtual ~Shape(){
    delete[] sides;
}
virtual double area() const = 0; // pure virtual function for area
virtual double volume() const = 0; // pure virtual function for volume
};

//////////////////////////////////////////////////////////
//Derived classes for 2D and 3D Shapes
class Shape2D : public Shape{ // inherit shape
protected:
    int n = 2; //n denotes the number of dimensions
public:
    // default constructor
    Shape2D() :Shape(n){}
    // param constructor
    Shape2D(const double side1, const double side2) :Shape(n){
        sides[0] = side1; sides[1] = side2;
    }
    virtual ~Shape2D(){} //virtual destructor
    double volume() const { cout << "trying to calculate volume of 2d   shape..." << endl; return 0; };
};

/////////////////////////////////////////////////////////////////////
//2D shapes
class Rectangle : public Shape2D{
public:
    // constructors
    Rectangle() :Shape2D() {}
    Rectangle(const double side1, const double side2) :Shape2D(side1, side2){}
    ~Rectangle(){}
    double area() const { return (sides[0] * sides[1]); }
};

int main(){
    Shape **ShapePointer = new Shape*[2];
    ShapePointer[0] = new Rectangle(2, 5);
    ShapePointer[1] = new Rectangle(1, 3);
    // clean up
    delete ShapePointer[0];
    delete ShapePointer[1];
    delete[] ShapePointer;
    system("pause");
    return 0;
}
</code>```

答:
Danger!!!

```<code>protected:
    int n = 2; //n denotes the number of dimensions
public:
    // default constructor
    Shape2D() :Shape(n){}
</code>```

n is undefined when you initialize Shape(n)

Same problem with

```<code>Shape2D(const double side1, const double side2) :Shape(n)
</code>```

If you can, define n as static const (or static constexpr, because you tagged C++11)

```<code> protected:
    static constexpr int n = 2; //n denotes the number of dimensions
</code>```

Otherwise you should define a static const/constexpr variable (say nDef), with value 2, and initialize both n and Shape() with this constant.

Anyway, take in count that, now, Shape (a base class for Shape2D) is initialized before n, that is a member of the class.

Body:
I am receiving the "Debug error" CRT detected that the application wrote to memory after end of heap. But I don't understand why and can't find any similar examples.

The full code is...
Although I think it may just be a problem with main.

#include <iostream>
#include <cmath>
#include <array>

using namespace std;
// Declare global consts
const double pi = 3.1415926583;

// Base class Shape
class Shape{
protected:
    double *sides;
public:
    Shape(const int n){ //parameterized for n dimensional shape
    sides = new double[n];
}
// need virtual destructor
virtual ~Shape(){
    delete[] sides;
}
virtual double area() const = 0; // pure virtual function for area
virtual double volume() const = 0; // pure virtual function for volume
};

//////////////////////////////////////////////////////////
//Derived classes for 2D and 3D Shapes
class Shape2D : public Shape{ // inherit shape
protected:
    int n = 2; //n denotes the number of dimensions
public:
    // default constructor
    Shape2D() :Shape(n){}
    // param constructor
    Shape2D(const double side1, const double side2) :Shape(n){
        sides[0] = side1; sides[1] = side2;
    }
    virtual ~Shape2D(){} //virtual destructor
    double volume() const { cout << "trying to calculate volume of 2d   shape..." << endl; return 0; };
};

/////////////////////////////////////////////////////////////////////
//2D shapes
class Rectangle : public Shape2D{
public:
    // constructors
    Rectangle() :Shape2D() {}
    Rectangle(const double side1, const double side2) :Shape2D(side1, side2){}
    ~Rectangle(){}
    double area() const { return (sides[0] * sides[1]); }
};

int main(){
    Shape **ShapePointer = new Shape*[2];
    ShapePointer[0] = new Rectangle(2, 5);
    ShapePointer[1] = new Rectangle(1, 3);
    // clean up
    delete ShapePointer[0];
    delete ShapePointer[1];
    delete[] ShapePointer;
    system("pause");
    return 0;
}

Body:
Danger!!!

protected:
    int n = 2; //n denotes the number of dimensions
public:
    // default constructor
    Shape2D() :Shape(n){}

n is undefined when you initialize Shape(n)

Same problem with

Shape2D(const double side1, const double side2) :Shape(n)

If you can, define n as static const (or static constexpr, because you tagged C++11)

 protected:
    static constexpr int n = 2; //n denotes the number of dimensions

Otherwise you should define a static const/constexpr variable (say nDef), with value 2, and initialize both n and Shape() with this constant.

Anyway, take in count that, now, Shape (a base class for Shape2D) is initialized before n, that is a member of the class.


问:
php delete sql query not working
```<code><?php
    include('session.php');
?>

<?php
    $conn = new mysqli("127.0.0.1","root","","foo");
    if ($conn->connect_errno) {
        echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " .         $conn->connect_error;
    }
    $sew = $_SESSION['login_user'];
    $a = $_GET["en"];
    $l = 1;
    $d = -1;

    if($a == 1)
    {
        $sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;

        if ($conn->query($sqlw) === FALSE)
        {
            echo "you have already disliked the song";
        }
        else
        {
        //query1
            $sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";

        //query2
            $sql = "UPDATE liking
            SET count = count - 1 ";

            if ($conn->query($sql) === TRUE) {
                echo "you disliked the song";
            }
            else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
</code>```

In this php code snippet, query1 is not working whereas query 2 is fine.

I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.

答:
You need to execute query1, before reuse your $sql variable.</p>

```<code> //query1
   $sql  = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
   $conn->query($sql);

 //query2
       $sql = "UPDATE liking
       SET count = count - 1 ";

       if ($conn->query($sql) === TRUE) {
</code>```

Title: php delete sql query not working

Body:
<?php
    include('session.php');
?>

<?php
    $conn = new mysqli("127.0.0.1","root","","foo");
    if ($conn->connect_errno) {
        echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " .         $conn->connect_error;
    }
    $sew = $_SESSION['login_user'];
    $a = $_GET["en"];
    $l = 1;
    $d = -1;

    if($a == 1)
    {
        $sqlw = " INSERT into dlkeuser VALUES('$a','$sew')" ;

        if ($conn->query($sqlw) === FALSE)
        {
            echo "you have already disliked the song";
        }
        else
        {
        //query1
            $sql = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' ";

        //query2
            $sql = "UPDATE liking
            SET count = count - 1 ";

            if ($conn->query($sql) === TRUE) {
                echo "you disliked the song";
            }
            else {
                echo "Error: " . $sql . "
" . $conn->error;
            }
        }

In this php code snippet, query1 is not working whereas query 2 is fine.

I am trying to insert (songid, userid) in dlkeuser(dislike) table against user i/p($_GET["en"]) and delete the record(songid,userid) from lkeuser(like) table if it exists. (songid,userid) pair is the composite primary key here. count is the net like/dislike of a song.

Body:
You need to execute query1, before reuse your $sql variable.

 //query1
   $sql  = " DELETE FROM lkeuser WHERE userid = '$sew' AND songid = '$a' " ;
   $conn->query($sql);

 //query2
       $sql = "UPDATE liking
       SET count = count - 1 ";

       if ($conn->query($sql) === TRUE) {


问:
How can I simplify this conversion from underscore to camelcase in Python?
I have written the function below that converts underscore to camelcase with first word in lowercase, i.e. "get_this_value" -> "getThisValue". Also I have requirement to preserve leading and trailing underscores and also double (triple etc.) underscores, if any, i.e.

```<code>"_get__this_value_" -> "_get_ThisValue_".
</code>```

The code:

```<code>def underscore_to_camelcase(value):
    output = ""
    first_word_passed = False
    for word in value.split("_"):
        if not word:
            output += "_"
            continue
        if first_word_passed:
            output += word.capitalize()
        else:
            output += word.lower()
        first_word_passed = True
    return output
</code>```

I am feeling the code above as written in non-Pythonic style, though it works as expected, so looking how to simplify the code and write it using list comprehensions etc.

答:
A slightly modified version:</p>

```<code>import re

def underscore_to_camelcase(value):
    first = True
    res = []

    for u,w in re.findall('([_]*)([^_]*)',value):
        if first:
            res.append(u+w)
            first = False
        elif len(w)==0:    # trailing underscores
            res.append(u)
        else:   # trim an underscore and capitalize
            res.append(u[:-1] + w.title())

    return ''.join(res)
</code>```

Body:
I have written the function below that converts underscore to camelcase with first word in lowercase, i.e. "get_this_value" -> "getThisValue". Also I have requirement to preserve leading and trailing underscores and also double (triple etc.) underscores, if any, i.e.

"_get__this_value_" -> "_get_ThisValue_".

The code:

def underscore_to_camelcase(value):
    output = ""
    first_word_passed = False
    for word in value.split("_"):
        if not word:
            output += "_"
            continue
        if first_word_passed:
            output += word.capitalize()
        else:
            output += word.lower()
        first_word_passed = True
    return output

I am feeling the code above as written in non-Pythonic style, though it works as expected, so looking how to simplify the code and write it using list comprehensions etc.

Body:
A slightly modified version:

import re

def underscore_to_camelcase(value):
    first = True
    res = []

    for u,w in re.findall('([_]*)([^_]*)',value):
        if first:
            res.append(u+w)
            first = False
        elif len(w)==0:    # trailing underscores
            res.append(u)
        else:   # trim an underscore and capitalize
            res.append(u[:-1] + w.title())

    return ''.join(res)