问:
Sylius Resource and Doctrine Filter
I'm new in Sylius and trying to extend it for my business. I'm currently facing an issue on admin part that I don't know how to solve.

I've an Basket entity which is One-To-One related with the Sylius Product entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="app_basket")
 */
class Basket implements ResourceInterface, BasketInterface
{
    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Product\Product", inversedBy="basket", cascade={"persist", "remove"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $product;
}
```

<p>I created this relation to be able to deal with Order Management of Sylius much easier. I don't want to mix Basket and Product objects in my business, so I created a Doctrine filter to exclude Basket items from Products:</p>

<pre class="lang-php prettyprint-override"><code><?php

namespace App\Doctrine\Filter;

use App\Entity\Product\Product;
use Doctrine\ORM\Mapping\ClassMetadata;
use \Doctrine\ORM\Query\Filter\SQLFilter;

class ProductFilter extends SQLFilter
{

    /**
     * @inheritDoc
     */
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
    {
        if($targetEntity->getName() !== Product::class) {
            return '';
        }

        return "$targetTableAlias.id not in (select product_id from app_basket)";
    }

}
</code>```

On the admin products page, everything is great, I don't have the baskets. But, if I go the the Basket admin index page, I have the following error:

An exception has been thrown during the rendering of a template
  ("Entity of type 'App\Entity\Product\Product' for IDs id(4) was not
  found").

This is because of the grid I use. I want to display the name of the product included in the basket:

```<code>sylius_grid:
    grids:
        app_admin_basket:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Basket\Basket
            fields:
                id:
                    type: string
                    label: sylius.ui.id
                product.name:
                    type: string
                    label: sylius.ui.name
</code>```

To retrieve the basket.product.name, the generated query is querying directly to the product table instead of the basket one:

```<code>SELECT t0.code AS code_1, t0.created_at AS created_at_2, t0.updated_at AS updated_at_3, t0.enabled AS enabled_4, t0.id AS id_5, t0.variant_selection_method AS variant_selection_method_6, t0.average_rating AS average_rating_7, t0.main_taxon_id AS main_taxon_id_8, t9.id AS id_10, t9.product_id AS product_id_11
--problem here
FROM sylius_product t0
LEFT JOIN app_basket t9 ON t9.product_id = t0.id
WHERE t0.id = 4
--Doctrine SQL FIlter
AND ((t0.id not in (select product_id from app_basket)));
</code>```

I've also the same behavior if a get this in a twig template :

```<code>{{ basket.product.name }}
</code>```

With a fetch="EAGER" annotation I don't have the error but the targeted entity still not reflect what I want.

Is there a way to force Sylius Resource to pass through basket entity first and not directly to the embedded entity?

答:
Your filter will always prevent fetching the basket's product.
You can try to disable it at least for this request: https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/filters.html#disabling-enabling-filters-and-setting-parameters</p>

Title: Sylius Resource and Doctrine Filter

Body:
I'm new in Sylius and trying to extend it for my business. I'm currently facing an issue on admin part that I don't know how to solve.

I've an Basket entity which is One-To-One related with the Sylius Product entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="app_basket")
 */
class Basket implements ResourceInterface, BasketInterface
{
    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Product\Product", inversedBy="basket", cascade={"persist", "remove"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $product;
}

I created this relation to be able to deal with Order Management of Sylius much easier. I don't want to mix Basket and Product objects in my business, so I created a Doctrine filter to exclude Basket items from Products:

<?php

namespace App\Doctrine\Filter;

use App\Entity\Product\Product;
use Doctrine\ORM\Mapping\ClassMetadata;
use \Doctrine\ORM\Query\Filter\SQLFilter;

class ProductFilter extends SQLFilter
{

    /**
     * @inheritDoc
     */
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
    {
        if($targetEntity->getName() !== Product::class) {
            return '';
        }

        return "$targetTableAlias.id not in (select product_id from app_basket)";
    }

}

On the admin products page, everything is great, I don't have the baskets. But, if I go the the Basket admin index page, I have the following error:

An exception has been thrown during the rendering of a template
  ("Entity of type 'App\Entity\Product\Product' for IDs id(4) was not
  found").

This is because of the grid I use. I want to display the name of the product included in the basket:

sylius_grid:
    grids:
        app_admin_basket:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Basket\Basket
            fields:
                id:
                    type: string
                    label: sylius.ui.id
                product.name:
                    type: string
                    label: sylius.ui.name

To retrieve the basket.product.name, the generated query is querying directly to the product table instead of the basket one:

SELECT t0.code AS code_1, t0.created_at AS created_at_2, t0.updated_at AS updated_at_3, t0.enabled AS enabled_4, t0.id AS id_5, t0.variant_selection_method AS variant_selection_method_6, t0.average_rating AS average_rating_7, t0.main_taxon_id AS main_taxon_id_8, t9.id AS id_10, t9.product_id AS product_id_11
--problem here
FROM sylius_product t0
LEFT JOIN app_basket t9 ON t9.product_id = t0.id
WHERE t0.id = 4
--Doctrine SQL FIlter
AND ((t0.id not in (select product_id from app_basket)));

I've also the same behavior if a get this in a twig template :

{{ basket.product.name }}

With a fetch="EAGER" annotation I don't have the error but the targeted entity still not reflect what I want.

Is there a way to force Sylius Resource to pass through basket entity first and not directly to the embedded entity?


来源: stackexchange

问:
Writing the right inequality in python?
Would python intrepet this:

```<code>if hour < 7 and hour > 0 or hour > 20 and hour < 23:
</code>```

the same as

```<code>if  7 > hour > 0 or 23 > hour > 20 (this one is just the usual mathematical inequality)
</code>```

if not then what should I write to tell python this inequality?

答:
You can always use parentheses to be sure:</p>

```<code>if (hour < 7 and hour > 0) or (hour > 20 and hour < 23):
</code>```

ContentLicense: CC BY-SA 4.0

Title: Writing the right inequality in python?

Body:
Would python intrepet this:

if hour < 7 and hour > 0 or hour > 20 and hour < 23:

the same as

if  7 > hour > 0 or 23 > hour > 20 (this one is just the usual mathematical inequality)

if not then what should I write to tell python this inequality?

Body:
You can always use parentheses to be sure:

if (hour < 7 and hour > 0) or (hour > 20 and hour < 23):


问:
Hugo: How can I display an image in my post list
I am trying to display an image in my post list.

In order to achieve that I added some tags in my post.md:

```<code>---
title: "Hello"
header_image: /images/blog/2019/water.jpg
images: /images/blog/2019/water.jpg
resources:
  src:  /images/blog/2019/water.jpg
  title: "The image I want"

---
</code>```

Then I edited list.html and tried different things:

```<code>{{ define "main" }}
<div class="archive animated fadeInDown">
    <ul class="list-with-title">
      <div class="listing-title">{{.Title}}</div>
      {{ range .Pages }}
      <ul class="listing">
        <div class="listing-item">
            <div class="listing-post"><a href="{{ .Permalink }}" title="{{ .Title }}">{{ .Title }}</a>
              {{ with .Resources.ByType "image" }}
                <div class="Image">
                {{ range . }}
                    <img src="{{ .RelPermalink }}">
                {{ end }}
                </div>
              {{ end }}
{{ $.Param "header_image" }}
                --  {{ range .Page.Resources }}
                  THERE IS ONE ITEM => NOT WORKING
                    {{ end }} <<
              <div class="post-time"><span class="date">{{.Date.Format "Jan 2" }}</span></div>
            </div>
          </div>
    </ul>
    {{ end }}
  </div>
{{ end }}
</code>```

But when I try to display Resources, I always get [] (nothing)

Any idea what I am doing wrong?

答:
I don't think your {{ $.Param "header_image" }} is working, either.

The way to access your custom, non-standard variables on pages, as well as sites, is through the .Params object, e.g. .Params.header_image. Note the small letter at the beginning, as opposed to capital letters for built-in params.

Page-level params on the Hugo Docs

Custom page params

To access

---
header_image: /images/blog/2019/water.jpg
---
```

<p>you can use this in your page template.</p>

```{{ .Params.header_image }}
```

<h2>Resources</h2>

<p>Page resources on Hugo Docs</p>

<p>It seems that <code>resources</code> is actually an array of objects, and with <code>yaml</code>, you should actually have something like this (note the dash):</p>

```resources:
- src:  /images/blog/2019/water.jpg
  title: "The image I want"
```

Also mind that this feature seems to only be available only for page bundles

Debugging

You can use {{ printf "%#v" .Resources }} for debugging.

Body:
I am trying to display an image in my post list.

In order to achieve that I added some tags in my post.md:

---
title: "Hello"
header_image: /images/blog/2019/water.jpg
images: /images/blog/2019/water.jpg
resources:
  src:  /images/blog/2019/water.jpg
  title: "The image I want"

---

Then I edited list.html and tried different things:

{{ define "main" }}

{{.Title}}

      {{ range .Pages }}

{{ .Title }}
              {{ with .Resources.ByType "image" }}

                {{ range . }}

                {{ end }}

              {{ end }}
{{ $.Param "header_image" }}
                --  {{ range .Page.Resources }}
                  THERE IS ONE ITEM => NOT WORKING
                    {{ end }} <<

{{.Date.Format "Jan 2" }}

    {{ end }}

{{ end }}

But when I try to display Resources, I always get [] (nothing)

Any idea what I am doing wrong?

Body:
I don't think your {{ $.Param "header_image" }} is working, either.

The way to access your custom, non-standard variables on pages, as well as sites, is through the .Params object, e.g. .Params.header_image. Note the small letter at the beginning, as opposed to capital letters for built-in params.

Page-level params on the Hugo Docs

Custom page params

To access

---
header_image: /images/blog/2019/water.jpg
---

you can use this in your page template.

{{ .Params.header_image }}

Resources

Page resources on Hugo Docs

It seems that resources is actually an array of objects, and with yaml, you should actually have something like this (note the dash):

resources:
- src:  /images/blog/2019/water.jpg
  title: "The image I want"

Also mind that this feature seems to only be available only for page bundles

Debugging

You can use {{ printf "%#v" .Resources }} for debugging.


问:
How to count records in given interval?
I have a table with created column. I need to check if there at least one record that was created less then a minute ago, from last record with same user_id. E.g.

```<code>|            created|user_id|
|2020-01-01T22:22:22|      1|
|2020-01-01T22:22:44|      1|
</code>```

^ Matches my clause. Created in one minute interval.

```<code>|            created|user_id|
|2020-01-01T22:22:22|      1|
|2020-01-01T22:24:44|      1|
</code>```

^ Not matches, created in more than one minute interval.

答:
You can use distinct on and window functions:

```<code>select distinct on (user_id)
    user_id,
    created_at
        <= lag(created_at) over(partition by user_id order by created_at) + interval '1' minute as flag
from mytable
order by user_id, created_at desc
</code>```

This gives you one record per user_id, with a boolean column called flag that indicates whether the last but one created_at is one minute older or less than the latest created_at.

Demo on DB Fiddle.

Sample data:

```
created_at          | user_id
:------------------ | ------:
2020-01-01 22:22:22 |       1
2020-01-01 22:22:44 |       1
2020-01-01 22:22:22 |       2
2020-01-01 22:24:44 |       2
```

Results:

```
user_id | flag
------: | :---
      1 | t
      2 | f
```

Title: How to count records in given interval?

Body:
I have a table with created column. I need to check if there at least one record that was created less then a minute ago, from last record with same user_id. E.g.

|            created|user_id|
|2020-01-01T22:22:22|      1|
|2020-01-01T22:22:44|      1|

^ Matches my clause. Created in one minute interval.

|            created|user_id|
|2020-01-01T22:22:22|      1|
|2020-01-01T22:24:44|      1|

^ Not matches, created in more than one minute interval.

Body:
You can use distinct on and window functions:

select distinct on (user_id)
    user_id,
    created_at
        <= lag(created_at) over(partition by user_id order by created_at) + interval '1' minute as flag
from mytable
order by user_id, created_at desc

This gives you one record per user_id, with a boolean column called flag that indicates whether the last but one created_at is one minute older or less than the latest created_at.

Demo on DB Fiddle.

Sample data:

created_at          | user_id
:------------------ | ------:
2020-01-01 22:22:22 |       1
2020-01-01 22:22:44 |       1
2020-01-01 22:22:22 |       2
2020-01-01 22:24:44 |       2

Results:

user_id | flag
------: | :---
      1 | t
      2 | f


问:
Spring Boot Redis store a list of POJOs as values
I am using Redis with Spring boot. I am using String as Key and the value against it as a List of complex POJO. Below is my config:

```<code>@Configuration
@EnableCaching
@Slf4j
public class RedisCacheConfig extends CachingConfigurerSupport {

private static final long DEFAULT_CACHE_EXPIRES = 60;

@Bean
public RedisTemplate<String, Object> redisTemplate(final RedisConnectionFactory redisConnectionFactory) {
    final RedisTemplate<String, Object> template = new RedisTemplate<>();
    setRedisTemplateConfigValues(redisConnectionFactory, template);
    return template;
}

@Bean
public CacheManager cacheManager(final RedisConnectionFactory redisConnectionFactory) {
    Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

    return RedisCacheManager
            .builder(redisConnectionFactory)
            .cacheDefaults(createCacheConfiguration())
            .withInitialCacheConfigurations(cacheConfigurations).build();
}

private static RedisCacheConfiguration createCacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(DEFAULT_CACHE_EXPIRES));
}

private <T> void setRedisTemplateConfigValues(final RedisConnectionFactory redisConnectionFactory,
                                              final RedisTemplate<String, T> template) {

    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
}
}
</code>```

The cahcing is working fine and serialization/deserialization via my app also seems to work. But when i use redis-cli, I see the below when i use the command
    KEYS *

```<code>1) "schools::ABC"
</code>```

Now the value against ABC key should be a list of complex objects. But when I do
     GET "schools::ABC"

I get the value with strange characters as below:

\xac\xed\x00\x05sr\x00\x13java.util.ArrayListx\x81\xd2\x1d\x99\xc7a\x9d\x03\x00\x01I\x00\x04sizexp\x00\x00\x00\x01w\x04\x00\x00\x00\x01sr\x00(com.example.  and so on....

Why is it so?

Also, I tried updating GenericJackson2JsonRedisSerializer in the config for valueSerializer to Jackson2JsonRedisSerializer. The result was no different.

Also, I tried to get the TYPE of the key, I get the result as 'String', so the list is getting stored as String.

答:
You could try setting the serializer in the cachemanager bean as below

```<code>@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisSerializationContext.SerializationPair<Object> jsonSerializer = RedisSerializationContext.SerializationPair
            .fromSerializer(new GenericJackson2JsonRedisSerializer());

    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .serializeValuesWith(jsonSerializer);

    return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory)
            .cacheDefaults(config).build();
}
</code>```

This worked for me .I can also see the value in the redis gui as a json

Body:
I am using Redis with Spring boot. I am using String as Key and the value against it as a List of complex POJO. Below is my config:

@Configuration
@EnableCaching
@Slf4j
public class RedisCacheConfig extends CachingConfigurerSupport {

private static final long DEFAULT_CACHE_EXPIRES = 60;

@Bean
public RedisTemplate<String, Object> redisTemplate(final RedisConnectionFactory redisConnectionFactory) {
    final RedisTemplate<String, Object> template = new RedisTemplate<>();
    setRedisTemplateConfigValues(redisConnectionFactory, template);
    return template;
}

@Bean
public CacheManager cacheManager(final RedisConnectionFactory redisConnectionFactory) {
    Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

    return RedisCacheManager
            .builder(redisConnectionFactory)
            .cacheDefaults(createCacheConfiguration())
            .withInitialCacheConfigurations(cacheConfigurations).build();
}

private static RedisCacheConfiguration createCacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(DEFAULT_CACHE_EXPIRES));
}

private <T> void setRedisTemplateConfigValues(final RedisConnectionFactory redisConnectionFactory,
                                              final RedisTemplate<String, T> template) {

    template.setConnectionFactory(redisConnectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
}
}

The cahcing is working fine and serialization/deserialization via my app also seems to work. But when i use redis-cli, I see the below when i use the command
    KEYS *

1) "schools::ABC"

Now the value against ABC key should be a list of complex objects. But when I do
     GET "schools::ABC"

I get the value with strange characters as below:

\xac\xed\x00\x05sr\x00\x13java.util.ArrayListx\x81\xd2\x1d\x99\xc7a\x9d\x03\x00\x01I\x00\x04sizexp\x00\x00\x00\x01w\x04\x00\x00\x00\x01sr\x00(com.example.  and so on....

Why is it so?

Also, I tried updating GenericJackson2JsonRedisSerializer in the config for valueSerializer to Jackson2JsonRedisSerializer. The result was no different.

Also, I tried to get the TYPE of the key, I get the result as 'String', so the list is getting stored as String.

Body:
You could try setting the serializer in the cachemanager bean as below

@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisSerializationContext.SerializationPair<Object> jsonSerializer = RedisSerializationContext.SerializationPair
            .fromSerializer(new GenericJackson2JsonRedisSerializer());

    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .serializeValuesWith(jsonSerializer);

    return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory)
            .cacheDefaults(config).build();
}

This worked for me .I can also see the value in the redis gui as a json


问:
how to get max time from a report
i want to filter my report and only show that row which has maximum time
 first i use

enddate = fr.First().EndDate

but it given me first value occured not the maximum time
i try to use

endDate = fr.Max().EndDate

but failed.

答:
If you want data row with latest date, then:

```<code>var reqData = (from o in fr
               orderby o.EndDate descending
               select o).FirstOrDefault();
</code>```

If you want latest date, then:

```<code>var latestDate = fr.Max(d => d.EndDate);
</code>```

Title: how to get max time from a report

Body:
If you want data row with latest date, then:

var reqData = (from o in fr
               orderby o.EndDate descending
               select o).FirstOrDefault();

If you want latest date, then:

var latestDate = fr.Max(d => d.EndDate);


问:
Delete a cell array column
Placed simple values into the cell array for testing.

```<code>model{1,1}=1;model{1,2}=2;model{1,3}=3;
model{2,1}=4;model{2,2}=5;model{2,3}=6;
i=2;//I want to remove the second column

temp={  model{:,1:i-1} model{:,i+1:size(model,2)}  }
</code>```

I wanted a result like this:

temp =

```<code>[1]    [3]
[4]    [6]
</code>```

But I'm getting this:

temp =

```<code>[1]    [4]    [3]    [6]
</code>```

How can I get this right?

p.s: for anyone working on Cell Arrays, there's a nice technique for appending here.

答:
You have to transpose the two pieces, and change some parentheses:</p>

```<code>temp= [{ model{:,1:i-1}}' {model{:,i+1:size(model,2)}}']
</code>```

ContentLicense: CC BY-SA 3.0

Title: Delete a cell array column

Body:
Placed simple values into the cell array for testing.

model{1,1}=1;model{1,2}=2;model{1,3}=3;
model{2,1}=4;model{2,2}=5;model{2,3}=6;
i=2;//I want to remove the second column

temp={  model{:,1:i-1} model{:,i+1:size(model,2)}  }

I wanted a result like this:

temp =

[1]    [3]
[4]    [6]

But I'm getting this:

temp =

[1]    [4]    [3]    [6]

How can I get this right?

p.s: for anyone working on Cell Arrays, there's a nice technique for appending here.

Body:
You have to transpose the two pieces, and change some parentheses:

temp= [{ model{:,1:i-1}}' {model{:,i+1:size(model,2)}}']


问:
how to align left and right in border
```<code>Positioned(
                    left: 16,
                    right: 16,
                    child: CircleAvatar(
                      radius: 66,
                    child: response.users.photo != null
                        ? Image.network(Modal.url + response.users.photo, width: 120, height: 140,)
                        : Image.asset(
                            'assets/user-icon.png',
                          ),
                    ),
</code>```

i have a problem, i want image align right and left in the border, please help me!

答:
You need to add fit cover is in Image.

This is example:

ClipOval(
      child: Image.asset(
        path_image,
        fit: BoxFit.cover,
      ))

```

<p>OR</p>

<p>or</p>

<pre class="lang-dart prettyprint-override"><code>CircleAvatar(
                radius: 30.0,
                backgroundImage:
                    NetworkImage('your_img_url'),
                backgroundColor: Colors.grey, // placeholder color
              )

``

I hope this helps
</code>```

Title: how to align left and right in border

Body:
Positioned(
                    left: 16,
                    right: 16,
                    child: CircleAvatar(
                      radius: 66,
                    child: response.users.photo != null
                        ? Image.network(Modal.url + response.users.photo, width: 120, height: 140,)
                        : Image.asset(
                            'assets/user-icon.png',
                          ),
                    ),

i have a problem, i want image align right and left in the border, please help me!

Body:
You need to add fit cover is in Image.

This is example:

ClipOval(
      child: Image.asset(
        path_image,
        fit: BoxFit.cover,
      ))

OR

or

CircleAvatar(
                radius: 30.0,
                backgroundImage:
                    NetworkImage('your_img_url'),
                backgroundColor: Colors.grey, // placeholder color
              )

``

I hope this helps


问:
Java: Override a method from grandparent
I have an abstract class A, and an abstract class B inheriting A.
Then, I have a class C(not abstract) that inherits B.

I need to override some methods declared abstract in A, and not implemented in B to be implemented in C.

But when I try to do this, and add an Override annotation on top of my method, it says its not valid as that method does not exist in the parent.

How can I do this?

Code with signatures:

```<code>public abstract class A {

abstract protected EntityType getEntityType();
abstract protected ActionResponse doProcessing();
}

public abstract class B extends A {
   @Override
   EntityType getEntityType() {
     ....
    ...
    }
}

public class C extends B {
     @Override
     ActionResponse doProcessing() {
     ...
     ..
    }
}
</code>```

答: If you could access the grandparent directly you would create a dependency on the implementation of the father, and this would violate encapsulation.</p>

Body:
I have an abstract class A, and an abstract class B inheriting A.
Then, I have a class C(not abstract) that inherits B.

I need to override some methods declared abstract in A, and not implemented in B to be implemented in C.

But when I try to do this, and add an Override annotation on top of my method, it says its not valid as that method does not exist in the parent.

How can I do this?

Code with signatures:

public abstract class A {

abstract protected EntityType getEntityType();
abstract protected ActionResponse doProcessing();
}

public abstract class B extends A {
   @Override
   EntityType getEntityType() {
     ....
    ...
    }
}

public class C extends B {
     @Override
     ActionResponse doProcessing() {
     ...
     ..
    }
}


问:
Cant add numbers with jquery
I couldn't add 3 numbers from inputs together. instead of adding them, it displays the numbers. Ex: 1+2+3= it becomes 123 instead of 6. It works well for the Earning but the deduction is causing the problem. any suggestion?

This is my script:

```<code><script>
    function getTotal() {
        //total earnings
        var morning_rate = document.salaries.morning_rate.value;
        var morning_day = document.salaries.morning_day.value;
        var night_rate = document.salaries.night_rate.value;
        var night_day = document.salaries.night_day.value;
        var earning = ((morning_rate * morning_day) + (night_rate * night_day));
        //DEDUCTION
        var uniform = document.salaries.uniform.value;
        var damage = document.salaries.damage.value;
        var othe = document.salaries.others.value;
        var totalDec = (uniform + damage + other);
        //NET SALARY
        var net_salary = (earning - totalDec);
        //RESULT
        document.getElementById('total_earning').value = earning
        document.getElementById('total_dec').value = totalDec
        document.getElementById('net_salary').value = net_salary
    }
    </script>
</code>```

答:
Your written code is almost okay. I have modified so. I hope it will work fine..

```<code> //total earnings
    var morning_rate=parseFloat(document.salaries.morning_rate.value);
    var morning_day=parseInt(document.salaries.morning_day.value);
    var night_rate=parseFloat(document.salaries.night_rate.value);
    var night_day=parseInt(document.salaries.night_day.value;

    var earning=((morning_rate*morning_day) +(night_rate*night_day));

    //DEDUCTION

    var uniform=parseFloat(document.salaries.uniform.value);
    var damage=parseFloat(document.salaries.damage.value);
    var othe=parseFloat(document.salaries.others.value);

    var totalDec=(uniform+damage+other);

    //NET SALARY
    var net_salary=(earning-totalDec);

   //RESULT
    document.getElementById('total_earning').value=earning.toFixed(2);
    document.getElementById('total_dec').value=totalDec.toFixed(2);
    document.getElementById('net_salary').value=net_salary.toFixed(2);
</code>```

Cheers...

Title: Cant add numbers with jquery

Body:
Your written code is almost okay. I have modified so. I hope it will work fine..

 //total earnings
    var morning_rate=parseFloat(document.salaries.morning_rate.value);
    var morning_day=parseInt(document.salaries.morning_day.value);
    var night_rate=parseFloat(document.salaries.night_rate.value);
    var night_day=parseInt(document.salaries.night_day.value;

    var earning=((morning_rate*morning_day) +(night_rate*night_day));

    //DEDUCTION

    var uniform=parseFloat(document.salaries.uniform.value);
    var damage=parseFloat(document.salaries.damage.value);
    var othe=parseFloat(document.salaries.others.value);

    var totalDec=(uniform+damage+other);

    //NET SALARY
    var net_salary=(earning-totalDec);

   //RESULT
    document.getElementById('total_earning').value=earning.toFixed(2);
    document.getElementById('total_dec').value=totalDec.toFixed(2);
    document.getElementById('net_salary').value=net_salary.toFixed(2);

Cheers...


问:
IF statement being ignored. Function not supposed to execute when IF is not fulfilled, but still does
I'm not sure why my IF statement is being ignored. The function is not supposed to execute if the IF statement is not being met. Here's the code:</p>

```<code>function myFormSubmit(e) {
  var timestamp = e.values[0];
  var type = e.values[2];
  var taxNumber = e.values[3];
  var title = e.values[15];
  var surname = e.values[16];
  var fullNames = e.values[17];
  var ID = e.values[18];

  var file = DriveApp.getFileById("1pWe4TBF3_mlqglfoIrTO8d6O2fSra27lPt0Iy9Tjwjw");

  var folder = DriveApp.getFolderById("17F678vzKcE7AaVqef0k-f96uHCOJeotv");

  var copy = file.makeCopy(surname + ',' + fullNames, folder);

  var doc = DocumentApp.openById(copy.getId());

  var body = doc.getBody();

  if (type = "Personal Financial Services") {

  body.replaceText("{{FullNames}}", fullNames);
  body.replaceText("{{Surname}}", surname);
  body.replaceText("{{ID}}", ID);
  body.replaceText("{{IncomeTaxNumber}}", taxNumber);
  body.replaceText("{{Title}}", title)

  doc.saveAndClose();
  }
}
</code>```

答:
Your are missing one equal sign in your if condition. For comparisons you need two or three ("==" or "===") where "===" is for strict comparison.

Replace your if condition with this line:

```<code>if (type == "Personal Financial Services") {...}
</code>```

References:

MDN comparison operators

Body:
I'm not sure why my IF statement is being ignored. The function is not supposed to execute if the IF statement is not being met. Here's the code:

function myFormSubmit(e) {
  var timestamp = e.values[0];
  var type = e.values[2];
  var taxNumber = e.values[3];
  var title = e.values[15];
  var surname = e.values[16];
  var fullNames = e.values[17];
  var ID = e.values[18];

  var file = DriveApp.getFileById("1pWe4TBF3_mlqglfoIrTO8d6O2fSra27lPt0Iy9Tjwjw");

  var folder = DriveApp.getFolderById("17F678vzKcE7AaVqef0k-f96uHCOJeotv");

  var copy = file.makeCopy(surname + ',' + fullNames, folder);

  var doc = DocumentApp.openById(copy.getId());

  var body = doc.getBody();

  if (type = "Personal Financial Services") {

  body.replaceText("{{FullNames}}", fullNames);
  body.replaceText("{{Surname}}", surname);
  body.replaceText("{{ID}}", ID);
  body.replaceText("{{IncomeTaxNumber}}", taxNumber);
  body.replaceText("{{Title}}", title)

  doc.saveAndClose();
  }
}

Body:
Your are missing one equal sign in your if condition. For comparisons you need two or three ("==" or "===") where "===" is for strict comparison.

Replace your if condition with this line:

if (type == "Personal Financial Services") {...}

References:

MDN comparison operators


问:
Attribute Error : module 'rasa_nlu.utils' has no attribute 'list_files'
I'm using version 0.11.5 of RASA NLU and I get the Attribute error " module 'rasa_nlu.utils' has no attribute 'list_files' " in this line :

```<code>training_data = load_data("./training_data.json")
</code>```

What should I do now ? Should I install a different version of RASA ?
I'm using the Anaconda Spyder platform.

答: Rasa Open Source has drastically improved since Rasa NLU 0.11.5. I would recommend checking out the latest version, which uses the DIET classifier</p>

Body:
I'm using version 0.11.5 of RASA NLU and I get the Attribute error " module 'rasa_nlu.utils' has no attribute 'list_files' " in this line :

training_data = load_data("./training_data.json")

What should I do now ? Should I install a different version of RASA ?
I'm using the Anaconda Spyder platform.


问:
Angular & kendo ui, width and height kendo window
I want the height and width of the kendo window to be dynamically set for the content of the kendo grid
this is my kendo-window

```<code> <div kendo-window="Operation.OperCustWind"
         k-width="800"
         k-height="700"
         id="operCustWindow"
         k-visible="false"
         modal="true"
         k-on-close="Operation.closeOperCustWindindow()">
        <div ng-show="Operation.IsOpers.isOpenCurrencyGrid">
            <div kendo-grid="Operation.currencyGrid" k-options="Operation.CurrencyGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOpenDecisionGrid">
            <div kendo-grid="Operation.decisionGrid" k-options="Operation.DecisionGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOpenCodeA">
            <div kendo-grid="Operation.CodeAGrid" k-options="Operation.CodeAGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOpenCodeB">
            <div kendo-grid="Operation.CodeBGrid" k-options="Operation.CodeBGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOpenCodeC">
            <div kendo-grid="Operation.CodeCGrid" k-options="Operation.CodeCGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOpenCodeD">
            <div kendo-grid="Operation.CodeDGrid" k-options="Operation.CodeDGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOpenCodeE">
            <div kendo-grid="Operation.CodeEGrid" k-options="Operation.CodeEGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOpenCodeVid">
            <div kendo-grid="Operation.CodeVidGrid" k-options="Operation.CodeVidGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOprOZN">
            <div kendo-grid="Operation.OprOznGrid" k-options="Operation.OprOznGridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOprVid2">
            <div kendo-grid="Operation.OprVid2Grid" k-options="Operation.OprVid2GridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOprVid3">
            <div kendo-grid="Operation.OprVid3Grid" k-options="Operation.OprVid3GridOptions"></div>
        </div>
        <div ng-show="Operation.IsOpers.isOprRiVid">
            <div kendo-grid="Operation.OprRiVidGrid" k-options="Operation.OprRiVidGridOptions"></div>
        </div>
    </div>
</code>```

here is a call function "Operation.OprOznGrid"

```<code>vm.getOperOzn = function () {
        vm.IsOpers.isOprOZN = true;
        vm.OperCustWind.setOptions({
            title: "Довідник K_DFM10"
        });
        vm.OperCustWind.open().center();
        vm.OprOznGrid.dataSource.read();
    }
</code>```

i get this

I want the height and width of the kendo window to be dynamically set for the content of the kendo grid

Please help me, I will be very grateful !!!
sorry for my english ))

答:
Step 1:
You can add cell css class </p>

```<code>.cell {
   white-space: normal;
}
</code>```

<p>Step 2:
You can also check here?
Auto Resize Grid </p>

Body:
I want the height and width of the kendo window to be dynamically set for the content of the kendo grid
this is my kendo-window

here is a call function "Operation.OprOznGrid"

vm.getOperOzn = function () {
        vm.IsOpers.isOprOZN = true;
        vm.OperCustWind.setOptions({
            title: "Довідник K_DFM10"
        });
        vm.OperCustWind.open().center();
        vm.OprOznGrid.dataSource.read();
    }

i get this

I want the height and width of the kendo window to be dynamically set for the content of the kendo grid

Please help me, I will be very grateful !!!
sorry for my english ))

Body:
Step 1:
You can add cell css class

.cell {
   white-space: normal;
}

Step 2:
You can also check here?
Auto Resize Grid


问:
How to create full year entry in mongodb
I want to create a table where complete 365 days entry (or leap year) will be stored on utc format which further read as Indian Time stamp i.e + 5:30

So lets say I have to create the entry of 2020, then start entry will like

```<code>2019-12-31T18:30:000  --> On indian time stamp it will be sharp 00 1 JAN 2020
2020-12-31T18:29:59:999  --> 23:59 31 DEC 2020

So suppose these entry is stored, now When any request comes then check the query through {$gte: new Date()}
</code>```

I will create the system cron which call this function on 1jan 00:00 so that every year I have the Correct entry.
This is my approach to fetch the Data. Now I don't understand that how to create the entry because this will be not meaningfull if I miss any date entry.

I take the moment help but not getting success on that. Is there anyone who can guide me for that.

答:
It would probably be simpler to generate that list on the client send and send a bulk insert.  If you really want to create it on the server, you could use aggregation, run this against a collection with at least one document in it:</p>

```<code>db.collection.aggregate([
  {$limit: 1},
  {$project: {
      dateFrom: ISODate("2020-01-01T00:00:00.000+05:30"),
      dateTo: ISODate("2021-01-01T00:00:00+05:30")
  }},
  {$addFields: {
      date: {$range: [0, 366]}
  }},
  {$unwind: "$date"},
  {$addFields: {
      date: {
        $add: [
          "$dateFrom",
          {$multiply: [ "$date",86400000 ]}
        ]
      }
  }},
  {$match: {
      $expr: {
        $lt: ["$date", "$dateTo"]
      }
  }},
  {$project: { date: 1 }},
  {$out: "NewCollectionForDates"}
])
</code>```

Body:
I want to create a table where complete 365 days entry (or leap year) will be stored on utc format which further read as Indian Time stamp i.e + 5:30

So lets say I have to create the entry of 2020, then start entry will like

2019-12-31T18:30:000  --> On indian time stamp it will be sharp 00 1 JAN 2020
2020-12-31T18:29:59:999  --> 23:59 31 DEC 2020

So suppose these entry is stored, now When any request comes then check the query through {$gte: new Date()}

I will create the system cron which call this function on 1jan 00:00 so that every year I have the Correct entry.
This is my approach to fetch the Data. Now I don't understand that how to create the entry because this will be not meaningfull if I miss any date entry.

I take the moment help but not getting success on that. Is there anyone who can guide me for that.

Body:
It would probably be simpler to generate that list on the client send and send a bulk insert.  If you really want to create it on the server, you could use aggregation, run this against a collection with at least one document in it:

db.collection.aggregate([
  {$limit: 1},
  {$project: {
      dateFrom: ISODate("2020-01-01T00:00:00.000+05:30"),
      dateTo: ISODate("2021-01-01T00:00:00+05:30")
  }},
  {$addFields: {
      date: {$range: [0, 366]}
  }},
  {$unwind: "$date"},
  {$addFields: {
      date: {
        $add: [
          "$dateFrom",
          {$multiply: [ "$date",86400000 ]}
        ]
      }
  }},
  {$match: {
      $expr: {
        $lt: ["$date", "$dateTo"]
      }
  }},
  {$project: { date: 1 }},
  {$out: "NewCollectionForDates"}
])


问:
How to handle IE download pop up with selenium webdriver without using autoIt and robot class
I have to run a script to download a specific file to the desired folder in Internet Explorer without using AutoIt and robot. Is there any other way than this. I am new to automation.
enter image description here
enter image description here</p>

答:
I was using the following code, it works well on my side, please check it:

```<code>package seleniumtest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.IOException;

public class testsample {

    //@SuppressWarnings("deprecation")
    public static void main(String[] args) {

        //add the IE web driver path here..
        System.setProperty("webdriver.ie.driver","E:\\webdriver\\IEDriverServer_x64_3.14.0\\IEDriverServer.exe");

        WebDriver browser = new InternetExplorerDriver();

        //replace the URL of the web page here..
        browser.get("<website url>");
        WebDriverWait wait = new WebDriverWait(browser, 5);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("btnDowloadReport")));

        WebElement element = browser.findElement(By.id("btnDowloadReport"));
        String downloadurl = element.getAttribute("href");
        System.out.println(downloadurl);

        String command = "cmd /c E:\\\\Temp\\\\wget.exe -P E:\\\\Temp\\\\output\\\\ --no-check-certificate " + downloadurl;

        try {
            Process process = Runtime.getRuntime().exec(command);

            process.getErrorStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

Note: please remember to change the web driver path, website url and the download folder to your owns.

The website html resource:

```<code> <a id="btnDowloadReport" href="https://github.com//sakinala/AutomationTesting/raw/master/samplefile.pdf" >Download</a>
</code>```

The result (it will download the file to the desired folder):

Body:
I was using the following code, it works well on my side, please check it:

package seleniumtest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.IOException;

public class testsample {

    //@SuppressWarnings("deprecation")
    public static void main(String[] args) {

        //add the IE web driver path here..
        System.setProperty("webdriver.ie.driver","E:\\webdriver\\IEDriverServer_x64_3.14.0\\IEDriverServer.exe");

        WebDriver browser = new InternetExplorerDriver();

        //replace the URL of the web page here..
        browser.get("<website url>");
        WebDriverWait wait = new WebDriverWait(browser, 5);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("btnDowloadReport")));

        WebElement element = browser.findElement(By.id("btnDowloadReport"));
        String downloadurl = element.getAttribute("href");
        System.out.println(downloadurl);

        String command = "cmd /c E:\\\\Temp\\\\wget.exe -P E:\\\\Temp\\\\output\\\\ --no-check-certificate " + downloadurl;

        try {
            Process process = Runtime.getRuntime().exec(command);

            process.getErrorStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Note: please remember to change the web driver path, website url and the download folder to your owns.

The website html resource:

 <a id="btnDowloadReport" href="https://github.com//sakinala/AutomationTesting/raw/master/samplefile.pdf" >Download</a>

The result (it will download the file to the desired folder):


问:
Copy entire directory contents to another directory?
Method to copy entire directory contents to another directory in java or groovy?</p>

答:
With Groovy, you can leverage Ant to do:

```<code>new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
  fileset( dir:'/path/to/src/folder' )
}
</code>```

AntBuilder is part of the distribution and the automatic imports list which means it is directly available for any groovy code.

Body:
With Groovy, you can leverage Ant to do:

new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
  fileset( dir:'/path/to/src/folder' )
}

AntBuilder is part of the distribution and the automatic imports list which means it is directly available for any groovy code.


问:
Multiple Column Duplicate in SQL
I have a table with fields (id , gid, uid)
For some rows (gid, uid) are same. There is duplicate.

Example 1:(repeated)

```<code>id      gid     uid

5802    1032    1247

5806    1032    1247

5807    1032    1247

5808    1032    1247
</code>```

Example 2: (occurs once)

```<code>id      gid     uid

5103    1132    1290
</code>```

In my case I want to pass uid and gid and check if there are duplicates
- Return True if (gid,uid) doesnot occur in the table
- Otherwise it return false.( for Example 1 and Example 2 )

I tried this query to return true or false.

```<code>SELECT  CASE WHEN EXISTS  (SELECT A.*
FROM table1 A
INNER JOIN (SELECT gid, uid
            FROM table1
            GROUP BY gid, uid
            HAVING COUNT(*) = 0)
ON A.gid = '1011' AND A.uid = '1086') THEN 'TRUE' ELSE 'FALSE' END from dual;
</code>```

But it always returns True ; Please help in solving the same

答:
```<code>select
    gid
    ,uid
,case when [count]>1 then 'False' else 'True' end Result
from (
    select
    gid
    ,uid
    ,count(*) [count]
    from Table1
    group by
    gid
    ,uid
) temp
</code>```

Title: Multiple Column Duplicate in SQL

Body:
I have a table with fields (id , gid, uid)
For some rows (gid, uid) are same. There is duplicate.

Example 1:(repeated)

id      gid     uid

5802    1032    1247

5806    1032    1247

5807    1032    1247

5808    1032    1247

Example 2: (occurs once)

id      gid     uid

5103    1132    1290

In my case I want to pass uid and gid and check if there are duplicates
- Return True if (gid,uid) doesnot occur in the table
- Otherwise it return false.( for Example 1 and Example 2 )

I tried this query to return true or false.

SELECT  CASE WHEN EXISTS  (SELECT A.*
FROM table1 A
INNER JOIN (SELECT gid, uid
            FROM table1
            GROUP BY gid, uid
            HAVING COUNT(*) = 0)
ON A.gid = '1011' AND A.uid = '1086') THEN 'TRUE' ELSE 'FALSE' END from dual;

But it always returns True ; Please help in solving the same


问:
Is there a way to ADD/COPY both directory and file in a single ADD/COPY command (dockerfile)?
In my dockerfile I am trying to ADD/COPY a file and a directory into destinationFolder. Expected output is:

```<code>destinationFolder/test.txt
destinationFolder/test_dir/*
</code>```

However, in the ADD command (as mentioned in note), the directory itself is not copied, just its contents.

```<code>ADD test.txt test_dir /destinationFolder/
</code>```

Is there a way to achieve the desired output using a single ADD/COPY command?

答:
2 solutions depending on the exact contents of your current project directory. The base line is the same though: have all your contents in the same dir and push the content of that directory directly to a target dir inside your image.

Moreover, as described in Docker best practice, I suggest you use COPY instead of ADD if you don't need any special functionalities from the latest.

Move your contents to a separate folder

All contents you want to push to your destination folder can be placed in a dedicated folder you push at once:

In your project dir you can

mkdir imageContents
mv test.text test_dir imageContents
```

<p>And you modify your Dockerfile with:</p>

```COPY imageContents destinationFolder/
```

<h1>Replicate the exact structure from your project root</h1>

<p>The idea is the same except you push the root or your project directly to your image. This will also work for any other folder you put there and that is not ignored. Note that you can use this for existing folder structures to simply add some files (like in the <code>/etc/</code> structure).</p>

<p>Create a <code>.dockerignore</code> file to make sure you only copy the relevant contents:</p>

```.dockerignore
Dockerfile
.git
# Add any other files that should be out of context
# Dummy examples below
.yamllint
mysecretfiles
```

<p>Recreate the exact file structure you want to push to your image, in your case:</p>

```mkdir destinationFolder
mv test.txt test_dir destinationFolder
```

<p>Eventually add some other files you want to push to your image</p>

```mkdir -p etc/myapp
echo "config1=myvalue" > etc/myapp/myapp.conf
```

<p>And modify your Docker file as:</p>

```COPY . /
```

Make your own method

You can easily mix the two methods above to fit your exact needs to whatever destination in your image file.

Body:
In my dockerfile I am trying to ADD/COPY a file and a directory into destinationFolder. Expected output is:

destinationFolder/test.txt
destinationFolder/test_dir/*

However, in the ADD command (as mentioned in note), the directory itself is not copied, just its contents.

ADD test.txt test_dir /destinationFolder/

Is there a way to achieve the desired output using a single ADD/COPY command?

Body:
2 solutions depending on the exact contents of your current project directory. The base line is the same though: have all your contents in the same dir and push the content of that directory directly to a target dir inside your image.

Moreover, as described in Docker best practice, I suggest you use COPY instead of ADD if you don't need any special functionalities from the latest.

Move your contents to a separate folder

All contents you want to push to your destination folder can be placed in a dedicated folder you push at once:

In your project dir you can

mkdir imageContents
mv test.text test_dir imageContents

And you modify your Dockerfile with:

COPY imageContents destinationFolder/

Replicate the exact structure from your project root

The idea is the same except you push the root or your project directly to your image. This will also work for any other folder you put there and that is not ignored. Note that you can use this for existing folder structures to simply add some files (like in the /etc/ structure).

Create a .dockerignore file to make sure you only copy the relevant contents:

.dockerignore
Dockerfile
.git
# Add any other files that should be out of context
# Dummy examples below
.yamllint
mysecretfiles

Recreate the exact file structure you want to push to your image, in your case:

mkdir destinationFolder
mv test.txt test_dir destinationFolder

Eventually add some other files you want to push to your image

mkdir -p etc/myapp
echo "config1=myvalue" > etc/myapp/myapp.conf

And modify your Docker file as:

COPY . /

Make your own method

You can easily mix the two methods above to fit your exact needs to whatever destination in your image file.


问:
set focus on input and change li background color
This function allows me to create new li elements and append it to my current todo list.

var newListElement =
  "
" +
  '<input type="checkbox"/>' +
  "" +
  '<input [type="text"] placeholder="Insert your new task here"/>' +
  "" +
  '

' +
  "
";

$("ul.todo-list").append(newListElement);```
</div>
</div>
</p>

<p>In this function I want to set the cursor to my input text field and want to change the background of the li element to grey when it is newly created. But whenever I am creating a new li element the color of the li element is not going to change nor can't i set the cursor automatically to the input field. Only if I am clicking manually with my mouse in the newly created input field on the li element the background of the li element is changing.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
//change last added list element to grey
$('input:text').focus(function () {
   setEditModeItem($(this).closest('ul.todo-list > li'));
});</code>```

My question is there a way to set the focus dynamically to a input field and check if it has focus?

答:
You can trigger focus in jQuery by calling .focus() method on the selected element, I added CSS background red to highlight the input on focus, note that you can use Template literals to concatenate string, here is a working snippet:

var newListElement = `

  <input type="checkbox"/>

  <input [type="text"] placeholder="Insert your new task here"/>

`;

$("ul.todo-list").append(newListElement);
// this is how to trigger focus on input:
$("ul.todo-list li:last-child").find("input").focus();
//change last added list element to grey
$("input:text").focus(function () {
  //setEditModeItem($(this).closest('ul.todo-list > li'));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul.todo-list input:focus {
  background-color: red;
}</code>```

```

Body:
This function allows me to create new li elements and append it to my current todo list.

var newListElement =
  "
" +
  '<input type="checkbox"/>' +
  "" +
  '<input [type="text"] placeholder="Insert your new task here"/>' +
  "" +
  '

' +
  "
";

$("ul.todo-list").append(newListElement);

In this function I want to set the cursor to my input text field and want to change the background of the li element to grey when it is newly created. But whenever I am creating a new li element the color of the li element is not going to change nor can't i set the cursor automatically to the input field. Only if I am clicking manually with my mouse in the newly created input field on the li element the background of the li element is changing.

//change last added list element to grey
$('input:text').focus(function () {
   setEditModeItem($(this).closest('ul.todo-list > li'));
});

My question is there a way to set the focus dynamically to a input field and check if it has focus?

Body:
You can trigger focus in jQuery by calling .focus() method on the selected element, I added CSS background red to highlight the input on focus, note that you can use Template literals to concatenate string, here is a working snippet:

var newListElement = `<li>
  <input type="checkbox"/>
  <label>
  <input [type="text"] placeholder="Insert your new task here"/>
  </label>
  <div class="arrow-btn"></div>
  </li>`;

$("ul.todo-list").append(newListElement);
// this is how to trigger focus on input:
$("ul.todo-list li:last-child").find("input").focus();
//change last added list element to grey
$("input:text").focus(function () {
  //setEditModeItem($(this).closest('ul.todo-list > li'));
});

ul.todo-list input:focus {
  background-color: red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="todo-list"></ul>


问:
Executing 100K Promises in Javascript in small 50 Chunks
I have a function that makes a REST call to a service and returns a promise. lets call that function Execute(). The function takes an ID and sends the ID as a GET parameter to a REST end point which persists the ID in a mongoDB db with some additional info.

In the client, I will need to run "Execute" 100k times from IDs (0 to 100k) and show the status of each (Whether succeeded or failed).

I did the obvious and I created a loop from 0 to 100k and run execute passing "i. That caused my Chrome to eventually freeze running out of memory (insufficient resources). It also caused network congestion from all the rest calls going at the back end.

So I wanted to "chop" those 100k into manageable amount like 50 promises call each. And when those 50 are all done (whether failed or succeeded) I want to use Promise.all([]).then execute the next 50 until all the 100k are done. This way I control the network congestion and memory at the same time. However I can't seem to know how to shake this down. Here is my code.

```<code>let promises = []
for (let i = 0; i < 100000, i++)
    {
       promises.push(execute(i))
       if (i % 50 === 0)
       {
          Promise.all(promises)
          .then  (a => updateStatus (a, true))
          .catch (a => updateStatus (a, false))

       }

    }
</code>```

The asynchronous nature of Javascript will keep executing the rest of the loop and executing. I really don't want to put a timer to hold the loop every 50 iterations because this will block the UI and kind of turned my app synchronous. Any suggestions as to how I tackle this?

Thank You Very Much.

New to Javascript.

答:
You can wrap promise by function and push it an array.

After splitting the array in chunks and process with reduce.

Npm package.

https://www.npmjs.com/package/concurrency-promise

Body:
I have a function that makes a REST call to a service and returns a promise. lets call that function Execute(). The function takes an ID and sends the ID as a GET parameter to a REST end point which persists the ID in a mongoDB db with some additional info.

In the client, I will need to run "Execute" 100k times from IDs (0 to 100k) and show the status of each (Whether succeeded or failed).

I did the obvious and I created a loop from 0 to 100k and run execute passing "i. That caused my Chrome to eventually freeze running out of memory (insufficient resources). It also caused network congestion from all the rest calls going at the back end.

So I wanted to "chop" those 100k into manageable amount like 50 promises call each. And when those 50 are all done (whether failed or succeeded) I want to use Promise.all([]).then execute the next 50 until all the 100k are done. This way I control the network congestion and memory at the same time. However I can't seem to know how to shake this down. Here is my code.

let promises = []
for (let i = 0; i < 100000, i++)
    {
       promises.push(execute(i))
       if (i % 50 === 0)
       {
          Promise.all(promises)
          .then  (a => updateStatus (a, true))
          .catch (a => updateStatus (a, false))

       }

    }

The asynchronous nature of Javascript will keep executing the rest of the loop and executing. I really don't want to put a timer to hold the loop every 50 iterations because this will block the UI and kind of turned my app synchronous. Any suggestions as to how I tackle this?

Thank You Very Much.

New to Javascript.


问:
Why LSTM uses sigmoid function to mimic the gate mechanism instead of binary value(0/1)?
In LSTM, we usually use sigmoid function to mimic the gates mechanism (soft), but the problem is in a lot of cases, such function gives a value around 0.5, which does not mean anything in terms of gates. Why don't use binary value (0/1) in LSTM, what is the basic idea and intuition using sigmoid function in LSTM and GRU?</p>

答: A sigmoid gate outputs a value between 0 and 1. It describes how much information should be passed. The value of 0 indicates that "Nothing should get through", and a value of 1 means "Let everything get through". For further informations, I advise you to take a look on colah's blog. </p>


问:
how to joint four single byte data to four byte data entire
I want to combine four single bytes of data to one datum of four bytes.

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

int main(int argc, char *argv[]) {

    unsigned long int sdata = 0x12*(16^6) + 0x34*(16^4) + 0x56*(16^2) + 0x78;
    printf("%x %d", sdata, sizeof(sdata));
    return 0;
}
```

<p>The screen prints:</p>

<pre class="lang-none prettyprint-override"><code>c20 4
</code>```

I want to get:

sdata = 0x12345678
```

The type unsigned long int is a 4 byte data type, so why can't it save the data? Why is the output wrong?

答:
You must use binary operations. More precisely left shifts (<<) and binary or (|).

```<code>unsigned int sdata = 0x12<<24 | 0x34<<16 | 0x56<<8  | 0x78;
printf("%x %zu\n", sdata, sizeof(sdata));
</code>```

This yields

12345678  4

Body:
I want to combine four single bytes of data to one datum of four bytes.

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

int main(int argc, char *argv[]) {

    unsigned long int sdata = 0x12*(16^6) + 0x34*(16^4) + 0x56*(16^2) + 0x78;
    printf("%x %d", sdata, sizeof(sdata));
    return 0;
}

The screen prints:

c20 4

I want to get:

sdata = 0x12345678

The type unsigned long int is a 4 byte data type, so why can't it save the data? Why is the output wrong?

Body:
You must use binary operations. More precisely left shifts (<<) and binary or (|).

unsigned int sdata = 0x12<<24 | 0x34<<16 | 0x56<<8  | 0x78;
printf("%x %zu\n", sdata, sizeof(sdata));

This yields

12345678  4


问:
Writing the right inequality in python?
Would python intrepet this:

```<code>if hour < 7 and hour > 0 or hour > 20 and hour < 23:
</code>```

the same as

```<code>if  7 > hour > 0 or 23 > hour > 20 (this one is just the usual mathematical inequality)
</code>```

if not then what should I write to tell python this inequality?

答:
You can use comparison chaining.

```<code>if (0 < hour < 7) or (20 < hour < 23):
    # do stuff
</code>```

(Parenthesis for emphasis.)

Title: Writing the right inequality in python?

Body:
Would python intrepet this:

if hour < 7 and hour > 0 or hour > 20 and hour < 23:

the same as

if  7 > hour > 0 or 23 > hour > 20 (this one is just the usual mathematical inequality)

if not then what should I write to tell python this inequality?

Body:
You can use comparison chaining.

if (0 < hour < 7) or (20 < hour < 23):
    # do stuff

(Parenthesis for emphasis.)


问:
Importing sceneform asset does not generate .sfa and .sfb files
When i'm trying to import sceneform assets and press finish on the window that pops up,nothing happens.No .sfa, .sfb files are generated.Nothing is generated in the build.gradle file also.I have to mention that i imported sceneform assets in the same project before and everything worked fine,but now (after a while) when i'm trying to do it again it doesn't work.</p>

答:
Sceneform 1.16 and 1.17 only supports gltf:

```<code>As part of the 1.16.0 release, support for SFA and SFB assets was removed in favor of adding glTF support
</code>```

There is also a bug in Android Studio 3.6 and Sceneform Tools which makes Android Studio to crash (downgrading AS to 3.5 will help).
If you want to use .fbx, you should downgrade to Sceneform 1.15 or you can use Sceneform 1.17 and gltf format

Body:
Sceneform 1.16 and 1.17 only supports gltf:

As part of the 1.16.0 release, support for SFA and SFB assets was removed in favor of adding glTF support

There is also a bug in Android Studio 3.6 and Sceneform Tools which makes Android Studio to crash (downgrading AS to 3.5 will help).
If you want to use .fbx, you should downgrade to Sceneform 1.15 or you can use Sceneform 1.17 and gltf format


问:
Why does .NET Core DI container not inject ILogger?
I am trying to get logging up and running in my C# console app based on .NET Core 2.1.

I added the following code to my DI declaration:

```<code>var sc = new ServiceCollection();

sc.AddLogging(builder =>
{
    builder.AddFilter("Microsoft", LogLevel.Warning);
    builder.AddFilter("System", LogLevel.Warning);
    builder.AddFilter("Program", LogLevel.Warning);
    builder.AddConsole();
    builder.AddEventLog();
});
</code>```

I am trying to inject the service by using the Interface Microsoft.Extensions.Logging.ILogger in the constructor of the services, but I am getting the following error:

Unhandled Exception: System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyService'.

```<code>    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
    at Program.Main(String[] args) in Program.cs:line 27
</code>```

Did I misunderstand something here? Shouldn't the AddLogging method be enough to expose the Service in the DI Container?

答:
The dependency injection system doesn't register ILogger. Instead it registers ILogger<T>. If you need an instance of a logger, you will need to accept ILogger<MyService>.

The reason behind this is that the generic argument is used to build the logger's category name--something which all loggers require. With a non-generic logger there's not necessarily a good default name. If you really want a non-generic ILogger, you can register one like this (change the name as you please):

```<code>services.AddSingleton(sp => sp.GetRequiredService<ILoggerFactory>().CreateLogger("DefaultLogger"));
</code>```

Alternatively, you can accept an ILoggerFactory in your constructor and then create your own logger on the fly.

Body:
I am trying to get logging up and running in my C# console app based on .NET Core 2.1.

I added the following code to my DI declaration:

var sc = new ServiceCollection();

sc.AddLogging(builder =>
{
    builder.AddFilter("Microsoft", LogLevel.Warning);
    builder.AddFilter("System", LogLevel.Warning);
    builder.AddFilter("Program", LogLevel.Warning);
    builder.AddConsole();
    builder.AddEventLog();
});

I am trying to inject the service by using the Interface Microsoft.Extensions.Logging.ILogger in the constructor of the services, but I am getting the following error:

Unhandled Exception: System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyService'.

    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)
    at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
    at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
    at Program.Main(String[] args) in Program.cs:line 27

Did I misunderstand something here? Shouldn't the AddLogging method be enough to expose the Service in the DI Container?

Body:
The dependency injection system doesn't register ILogger. Instead it registers ILogger<T>. If you need an instance of a logger, you will need to accept ILogger<MyService>.

The reason behind this is that the generic argument is used to build the logger's category name--something which all loggers require. With a non-generic logger there's not necessarily a good default name. If you really want a non-generic ILogger, you can register one like this (change the name as you please):

services.AddSingleton(sp => sp.GetRequiredService<ILoggerFactory>().CreateLogger("DefaultLogger"));

Alternatively, you can accept an ILoggerFactory in your constructor and then create your own logger on the fly.


问:
MySQL Text formatting
Hej guys,

I wrote a little php script which access a database and simply displays the rows which where found for a given query. It echos a table with them but it seems there are some typeset errors resulting in questionsmarks. Any hint what I could do to solve this? Here's a screenshot:  Text Formatting">

Here's the code I'm using to fetch and display the data

```<code>$result = mysql_query($sql);
        if(mysql_num_rows($result)>0){
            echo "<div style='float:top;clear:both;'>";
            echo "<table border='1'>";
            echo "<th>id</th><th>project</th><th>publisher</th><th>country</th><th>contact</th><th>mail</th><th>agent</th><th>report</th><th>todo</th><th>by who</th><th>done(date,text)</th><th>priority</th>";
            while($row = mysql_fetch_array($result)){
                echo "<tr>";
                echo "<td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td><td>".$row[3]."</td><td>".$row[4]."</td><td>".$row[5]."</td><td>".$row[6]."</td><td>".$row[7]."</td><td>".$row[8]."</td><td>".$row[9]."</td><td>".$row[10]."</td><td>".$row[11]."</td>";
                echo "<td><form method='POST' action='insert.php'><input type='submit' name='edit' value='edit'/><input type='hidden' name='hiddenID' value='".$row[0]."' /><input type='hidden' name='hiddenDB' value='".$_POST['db']."' /><input type='hidden' name='hiddenProject' value='".$row[1]."' /><input type='hidden' name='hiddenPublisher' value='".$row[2]."' /><input type='hidden' name='hiddenCountry' value='".$row[3]."' /><input type='hidden' name='hiddenContact' value='".$row[4]."' /><input type='hidden' name='hiddenMail' value='".$row[5]."' /><input type='hidden' name='hiddenAgent' value='".$row[6]."' /><input type='hidden' name='hiddenReport' value='".$row[7]."' /><input type='hidden' name='hiddenTodo' value='".$row[8]."' /><input type='hidden' name='hiddenBywho' value='".$row[9]."' /><input type='hidden' name='hiddenDone' value='".$row[10]."' /><input type='hidden' name='hiddenPriority' value='".$row[11]."' /></form></td>";
                echo "</tr>";
            }
            echo "</table>";
            echo "</div>";
</code>```

p.s.: It seems special chars like the german "ß" also aren¿t getting inserted properly into the database when I inspect the datasets using phpmyadmin

答:
I suggest you to use UTF-8 charset.

You should make your table/colunmn charset to utf8_general_ci

And then in your PHP script launch as first query

```<code>SET NAMES 'utf-8'
</code>```

Title: MySQL Text formatting

Body:
Hej guys,

I wrote a little php script which access a database and simply displays the rows which where found for a given query. It echos a table with them but it seems there are some typeset errors resulting in questionsmarks. Any hint what I could do to solve this? Here's a screenshot:  Text Formatting">

Here's the code I'm using to fetch and display the data

$result = mysql_query($sql);
        if(mysql_num_rows($result)>0){
            echo "
";
            echo "
";
            echo "id	project	publisher	country	contact	mail	agent	report	todo	by who	done(date,text)	priority	";
            while($row = mysql_fetch_array($result)){
                echo "
";
                echo "".$row[0]."	".$row[1]."	".$row[2]."	".$row[3]."	".$row[4]."	".$row[5]."	".$row[6]."	".$row[7]."	".$row[8]."	".$row[9]."	".$row[10]."	".$row[11]."	";
                echo "<form method='POST' action='insert.php'><input type='submit' name='edit' value='edit'/><input type='hidden' name='hiddenID' value='".$row[0]."' /><input type='hidden' name='hiddenDB' value='".$_POST['db']."' /><input type='hidden' name='hiddenProject' value='".$row[1]."' /><input type='hidden' name='hiddenPublisher' value='".$row[2]."' /><input type='hidden' name='hiddenCountry' value='".$row[3]."' /><input type='hidden' name='hiddenContact' value='".$row[4]."' /><input type='hidden' name='hiddenMail' value='".$row[5]."' /><input type='hidden' name='hiddenAgent' value='".$row[6]."' /><input type='hidden' name='hiddenReport' value='".$row[7]."' /><input type='hidden' name='hiddenTodo' value='".$row[8]."' /><input type='hidden' name='hiddenBywho' value='".$row[9]."' /><input type='hidden' name='hiddenDone' value='".$row[10]."' /><input type='hidden' name='hiddenPriority' value='".$row[11]."' /></form>	";
                echo "
";
            }
            echo "
";
            echo "
";

p.s.: It seems special chars like the german "ß" also aren¿t getting inserted properly into the database when I inspect the datasets using phpmyadmin

Body:
I suggest you to use UTF-8 charset.

You should make your table/colunmn charset to utf8_general_ci

And then in your PHP script launch as first query

SET NAMES 'utf-8'


问:
Saving permanently user input for later use and expanding your program
EDITED QUESTION

I made a small sequential program in Java which can calculate my daily bonus for my job. It's not the most beautiful or optimized bit of code but hey it works!

Now it would be cool to have this actually save my input for that day somehow and even when I terminate the program the next time I open it should still have stored that end value somewhere. Maybe even go back to that specific day and check my PPH (productive hours) and maybe even calculate the whole month (which is actually the end goal and track my performance).

Any suggestions?

答:
***** Answers I found ******

This is the first one i found but is not super useful if you would like that your colleagues also use your application. For single use and store a file locally it would work. https://attacomsian.com/blog/gson-read-write-json#

Using an SQL data base: https://www.ntu.edu.sg/home/ehchua/programming/java/JDBC_Basic.html


问:
Mapping through items in static query not showing any results
Fairly new to Gatsby and React. It seems to be going fine so far, but for some reason I can't seem to map through items using the static query method in class based component.

My code is added below.

The strange thing is that the {this.props.site.siteMetadata.title} works ok, even the totalCount or primaryMenu returns data fine but the mapping through the primaryMenu just doesn't return anything.

Am i doing something wrong?

```<code>import React from 'react';
import { Link, StaticQuery, graphql } from "gatsby"

class Navigation extends React.Component {

    render() {

        return (
            <div>
                {this.props.site.siteMetadata.title}

                {/* {this.props.primaryMenu.totalCount} */}
                {this.props.primaryMenu.edges.map((item, i) => (
                    <li key={i}>
                        <Link to={item.url} activeClassName="overlayActive">
                            {item.title}
                        </Link>
                    </li>
                ))}

            </div>

        )
    }
}

export default () => (
    <StaticQuery
        query={graphql`
        query {
          site {
            siteMetadata {
              title
            }
          }
          primaryMenu: allWordpressWpApiMenusMenusItems(filter: {wordpress_id: {eq: 2}}) {
            totalCount
            edges {
              node {
                count
                items {
                  title
                  url
                }
              }
            }
          }

        }
      `}
        render={(data) => (
            <Navigation site={data.site} primaryMenu={data.primaryMenu}  />
        )}
    />
)
</code>```

I get the following data from my graphql query so the data is there, just not pulling through

```<code>
{
  "data": {
    "site": {
      "siteMetadata": {
        "title": "Site title"
      }
    },
    "primaryMenu": {
      "totalCount": 1,
      "edges": [
        {
          "node": {
            "count": 6,
            "items": [
              {
                "title": "About",
                "url": "/about/"
              },
              {
                "title": "Programs",
                "url": "/programs/"
              },
              {
                "title": "Locations",
                "url": "/locations/"
              },
              {
                "title": "Alumni",
                "url": "/alumni/"
              },
              {
                "title": "Admission",
                "url": "/admission/"
              },
              {
                "title": "Blog",
                "url": "/blog/"
              }
            ]
          }
        }
      ]
    }
}
</code>```

答:
Your data has node and then items under edges which have URL and title. I have corrected the code please check.</p>

```<code>import React from 'react';
import { Link, StaticQuery, graphql } from "gatsby"

class Navigation extends React.Component {

    render() {

        return (
            <div>
                {this.props.site.siteMetadata.title}

                {/* {this.props.primaryMenu.totalCount} */}
                {this.props.primaryMenu.edges[0].node.items.map((item, i) => (
                    <li key={i}>
                        <Link to={item.url} activeClassName="overlayActive">
                            {item.title}
                        </Link>
                    </li>
                ))}

            </div>

        )
    }
}

export default () => (
    <StaticQuery
        query={graphql`
        query {
          site {
            siteMetadata {
              title
            }
          }
          primaryMenu: allWordpressWpApiMenusMenusItems(filter: {wordpress_id: {eq: 2}}) {
            totalCount
            edges {
              node {
                count
                items {
                  title
                  url
                }
              }
            }
          }

        }
      `}
        render={(data) => (
            <Navigation site={data.site} primaryMenu={data.primaryMenu}  />
        )}
    />
)
</code>```

Body:
Fairly new to Gatsby and React. It seems to be going fine so far, but for some reason I can't seem to map through items using the static query method in class based component.

My code is added below.

The strange thing is that the {this.props.site.siteMetadata.title} works ok, even the totalCount or primaryMenu returns data fine but the mapping through the primaryMenu just doesn't return anything.

Am i doing something wrong?

import React from 'react';
import { Link, StaticQuery, graphql } from "gatsby"

class Navigation extends React.Component {

    render() {

        return (

                {this.props.site.siteMetadata.title}

                {/* {this.props.primaryMenu.totalCount} */}
                {this.props.primaryMenu.edges.map((item, i) => (

                        <Link to={item.url} activeClassName="overlayActive">
                            {item.title}
                        </Link>

                ))}

        )
    }
}

export default () => (
    <StaticQuery
        query={graphql`
        query {
          site {
            siteMetadata {
              title
            }
          }
          primaryMenu: allWordpressWpApiMenusMenusItems(filter: {wordpress_id: {eq: 2}}) {
            totalCount
            edges {
              node {
                count
                items {
                  title
                  url
                }
              }
            }
          }

        }
      `}
        render={(data) => (
            <Navigation site={data.site} primaryMenu={data.primaryMenu}  />
        )}
    />
)

I get the following data from my graphql query so the data is there, just not pulling through

{
  "data": {
    "site": {
      "siteMetadata": {
        "title": "Site title"
      }
    },
    "primaryMenu": {
      "totalCount": 1,
      "edges": [
        {
          "node": {
            "count": 6,
            "items": [
              {
                "title": "About",
                "url": "/about/"
              },
              {
                "title": "Programs",
                "url": "/programs/"
              },
              {
                "title": "Locations",
                "url": "/locations/"
              },
              {
                "title": "Alumni",
                "url": "/alumni/"
              },
              {
                "title": "Admission",
                "url": "/admission/"
              },
              {
                "title": "Blog",
                "url": "/blog/"
              }
            ]
          }
        }
      ]
    }
}

Body:
Your data has node and then items under edges which have URL and title. I have corrected the code please check.

import React from 'react';
import { Link, StaticQuery, graphql } from "gatsby"

class Navigation extends React.Component {

    render() {

        return (
            <div>
                {this.props.site.siteMetadata.title}

                {/* {this.props.primaryMenu.totalCount} */}
                {this.props.primaryMenu.edges[0].node.items.map((item, i) => (
                    <li key={i}>
                        <Link to={item.url} activeClassName="overlayActive">
                            {item.title}
                        </Link>
                    </li>
                ))}

            </div>

        )
    }
}

export default () => (
    <StaticQuery
        query={graphql`
        query {
          site {
            siteMetadata {
              title
            }
          }
          primaryMenu: allWordpressWpApiMenusMenusItems(filter: {wordpress_id: {eq: 2}}) {
            totalCount
            edges {
              node {
                count
                items {
                  title
                  url
                }
              }
            }
          }

        }
      `}
        render={(data) => (
            <Navigation site={data.site} primaryMenu={data.primaryMenu}  />
        )}
    />
)


问:
value of a textarea element
I want to use value of a textarea element, but I am not able to get it

function postComment(element) {
  const content = element.previousSibling.value;
  console.log(content);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="" class="comment-editor">
  <div class="form-group">
    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>
  </div>
</form></code>```

It gives undefined as output

答:
Can you try the below code

function postComment(element) {
  const content = element.parentNode.firstElementChild.value
  console.log(content);
  return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="" class="comment-editor">
  <div class="form-group">
    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="return postComment(this)">Comment</button>
  </div>
</form></code>```

Title: value of a textarea element

Body:
I want to use value of a textarea element, but I am not able to get it

function postComment(element) {
  const content = element.previousSibling.value;
  console.log(content);
}

<form action="" class="comment-editor">

    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>

</form>

It gives undefined as output

Body:
Can you try the below code

function postComment(element) {
  const content = element.parentNode.firstElementChild.value
  console.log(content);
  return false;
}

<form action="" class="comment-editor">
  <div class="form-group">
    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="return postComment(this)">Comment</button>
  </div>
</form>


问:
The access values of the value_counts() method
I used the value_counts to see how many times an id occurs in my DataFrame. Is it also possible to access the values of these counts for a certain column with the same ids. For example:

```<code>   colA    colB  colC
1. banana, 50,   60
2. apple, 30,   70
2. apple, 20,   80
2. lemon, 30,   90
2. banana, 25,   10
2. lemon, 50,   15
2. apple, 5,   85

banana['colB']: [50, 25]
apple['colB']: [30, 20, 5]
etc...
</code>```

I don't know what the ids are in colA so they have to be variable...
I managed to do it in a loop using the df.loc but this is very time consuming as the dataframe is very large.

答:
I think in python it is possible only ugly ways, best is use another strucures like Series or DataFrames or dictionaries, link.

Close, what you need is convert column to index and then select by index nad columns labels by DataFrame.loc:

```<code>df1 = df.set_index('colA')
</code>```

And then:

```<code>a = df1.loc['banana','colB'].tolist()

b = df1.loc['apple','colB'].tolist()
</code>```

For all values is possible create Series of lists :

```<code>s = df.groupby('colA')['colB'].agg(list)
</code>```

And then:

```<code>a = s['banana']
</code>```

Or for dictionary of lists use:

```<code>d = df.groupby('colA')['colB'].agg(list).to_dict()

a = d['banana']
</code>```

Body:
I used the value_counts to see how many times an id occurs in my DataFrame. Is it also possible to access the values of these counts for a certain column with the same ids. For example:

   colA    colB  colC
1. banana, 50,   60
2. apple, 30,   70
2. apple, 20,   80
2. lemon, 30,   90
2. banana, 25,   10
2. lemon, 50,   15
2. apple, 5,   85

banana['colB']: [50, 25]
apple['colB']: [30, 20, 5]
etc...

I don't know what the ids are in colA so they have to be variable...
I managed to do it in a loop using the df.loc but this is very time consuming as the dataframe is very large.

Body:
I think in python it is possible only ugly ways, best is use another strucures like Series or DataFrames or dictionaries, link.

Close, what you need is convert column to index and then select by index nad columns labels by DataFrame.loc:

df1 = df.set_index('colA')

And then:

a = df1.loc['banana','colB'].tolist()

b = df1.loc['apple','colB'].tolist()

For all values is possible create Series of lists :

s = df.groupby('colA')['colB'].agg(list)

And then:

a = s['banana']

Or for dictionary of lists use:

d = df.groupby('colA')['colB'].agg(list).to_dict()

a = d['banana']


问:
pyspark: Auto filling in implicit missing values
I have a dataframe

```<code>user day amount
a 2 10
a 1 14
a 4 5
b 1 4
</code>```

You see that, the maximum value of day is 4, and the minimum value is 1. I want to fill 0 for amount column in all missing days of all users, so the above data frame will become.

```<code>user day amount
    a 2 10
    a 1 14
    a 4 5
    a 3 0
    b 1 4
    b 2 0
    b 3 0
    b 4 0
</code>```

How could I do that in PySpark? Many thanks.

答:
Here is one approach. You can get the min and max values first , then group on user column and pivot, then fill in missing columns and fill all nulls as 0, then stack them back:

```<code>min_max = df.agg(F.min("day"),F.max("day")).collect()[0]
df1 = df.groupBy("user").pivot("day").agg(F.first("amount").alias("amount")).na.fill(0)

missing_cols = [F.lit(0).alias(str(i)) for i in range(min_max[0],min_max[1]+1)
                                                if str(i) not in df1.columns ]
df1 = df1.select("*",*missing_cols)

#+----+---+---+---+---+
#|user|  1|  2|  4|  3|
#+----+---+---+---+---+
#|   b|  4|  0|  0|  0|
#|   a| 14| 10|  5|  0|
#+----+---+---+---+---+

#the next step is inspired from https://stackoverflow.com/a/37865645/9840637
arr = F.explode(F.array([F.struct(F.lit(c).alias("day"), F.col(c).alias("amount"))
                                           for c in df1.columns[1:]])).alias("kvs")
(df1.select(["user"] + [arr])
    .select(["user"]+ ["kvs.day", "kvs.amount"]).orderBy("user")).show()
</code>```

```<code>+----+---+------+
|user|day|amount|
+----+---+------+
|   a|  1|    14|
|   a|  2|    10|
|   a|  4|     5|
|   a|  3|     0|
|   b|  1|     4|
|   b|  2|     0|
|   b|  4|     0|
|   b|  3|     0|
+----+---+------+
</code>```

Note, since column day was pivotted , the dtype might have changed so you may have to cast them back to the original dtype

Body:
I have a dataframe

user day amount
a 2 10
a 1 14
a 4 5
b 1 4

You see that, the maximum value of day is 4, and the minimum value is 1. I want to fill 0 for amount column in all missing days of all users, so the above data frame will become.

user day amount
    a 2 10
    a 1 14
    a 4 5
    a 3 0
    b 1 4
    b 2 0
    b 3 0
    b 4 0

How could I do that in PySpark? Many thanks.

Body:
Here is one approach. You can get the min and max values first , then group on user column and pivot, then fill in missing columns and fill all nulls as 0, then stack them back:

min_max = df.agg(F.min("day"),F.max("day")).collect()[0]
df1 = df.groupBy("user").pivot("day").agg(F.first("amount").alias("amount")).na.fill(0)

missing_cols = [F.lit(0).alias(str(i)) for i in range(min_max[0],min_max[1]+1)
                                                if str(i) not in df1.columns ]
df1 = df1.select("*",*missing_cols)

#+----+---+---+---+---+
#|user|  1|  2|  4|  3|
#+----+---+---+---+---+
#|   b|  4|  0|  0|  0|
#|   a| 14| 10|  5|  0|
#+----+---+---+---+---+

#the next step is inspired from https://stackoverflow.com/a/37865645/9840637
arr = F.explode(F.array([F.struct(F.lit(c).alias("day"), F.col(c).alias("amount"))
                                           for c in df1.columns[1:]])).alias("kvs")
(df1.select(["user"] + [arr])
    .select(["user"]+ ["kvs.day", "kvs.amount"]).orderBy("user")).show()

+----+---+------+
|user|day|amount|
+----+---+------+
|   a|  1|    14|
|   a|  2|    10|
|   a|  4|     5|
|   a|  3|     0|
|   b|  1|     4|
|   b|  2|     0|
|   b|  4|     0|
|   b|  3|     0|
+----+---+------+

Note, since column day was pivotted , the dtype might have changed so you may have to cast them back to the original dtype


问:
Cant add numbers with jquery
I couldn't add 3 numbers from inputs together. instead of adding them, it displays the numbers. Ex: 1+2+3= it becomes 123 instead of 6. It works well for the Earning but the deduction is causing the problem. any suggestion?

This is my script:

```<code><script>
    function getTotal() {
        //total earnings
        var morning_rate = document.salaries.morning_rate.value;
        var morning_day = document.salaries.morning_day.value;
        var night_rate = document.salaries.night_rate.value;
        var night_day = document.salaries.night_day.value;
        var earning = ((morning_rate * morning_day) + (night_rate * night_day));
        //DEDUCTION
        var uniform = document.salaries.uniform.value;
        var damage = document.salaries.damage.value;
        var othe = document.salaries.others.value;
        var totalDec = (uniform + damage + other);
        //NET SALARY
        var net_salary = (earning - totalDec);
        //RESULT
        document.getElementById('total_earning').value = earning
        document.getElementById('total_dec').value = totalDec
        document.getElementById('net_salary').value = net_salary
    }
    </script>
</code>```

答:
The value of an input field, by default, is a string, and + concatenates a string to the end of the other string. To treat these strings as integers, you have to use parseInt() function, which takes a string, float, or a boolean as an argument and returns an integer.
For example, you should use:

```<code>var damage = parseInt(document.salaries.damage.value);
</code>```

Instead of

```<code>var damage=document.salaries.damage.value;
</code>```

Title: Cant add numbers with jquery

Body:
The value of an input field, by default, is a string, and + concatenates a string to the end of the other string. To treat these strings as integers, you have to use parseInt() function, which takes a string, float, or a boolean as an argument and returns an integer.
For example, you should use:

var damage = parseInt(document.salaries.damage.value);

Instead of

var damage=document.salaries.damage.value;