问:
Parse Complex JSON -- Map
I need to parse the complex JSON (below) IN SCALA to get the values of "expression" and "value" in "measure" key i.e I need List (COUNT, COUNT_DISTINCT ...) and List (1,tbl1.USER_ID ...).

I tried multiple options, but it is not working. Any help is appreciated

```<code>{
  "uuid": "uuidddd",
  "last_modified": 1559080222953,
  "version": "2.6.1.0",
  "name": "FULL_DAY_2_mand_date",
  "is_draft": false,
  "model_name": "FULL_DAY_1_may05",
  "description": "",
  "null_string": null,
  "dimensions": [
    {
      "name": "PLATFORM",
      "table": "tbl1",
      "column": "PLATFORM",
      "derived": null
    },
    {
      "name": "OS_VERSION",
      "table": "tbl1",
      "column": "OS_VERSION",
      "derived": null
    }
  ],
  "measures": [
    {
      "name": "_COUNT_",
      "function": {
        "expression": "COUNT",
        "parameter": {
          "type": "constant",
          "value": "1"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "UU",
      "function": {
        "expression": "COUNT_DISTINCT",
        "parameter": {
          "type": "column",
          "value": "tbl1.USER_ID"
        },
        "returntype": "hllc(12)"
      }
    },
    {
      "name": "CONT_SIZE",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.SIZE"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "CONT_COUNT",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.COUNT"
        },
        "returntype": "bigint"
      }
    }
  ],
  "dictionaries": [],
  "rowkey": {
    "rowkey_columns": [
      {
        "column": "tbl1.OS_VERSION",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.PLATFORM",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.DEVICE_FAMILY",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      }
    ]
  },
  "hbase_mapping": {
    "column_family": [
      {
        "name": "F1",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "_COUNT_",
              "CONT_SIZE",
              "CONT_COUNT"
            ]
          }
        ]
      },
      {
        "name": "F2",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "UU"
            ]
          }
        ]
      }
    ]
  },
  "aggregation_groups": [
    {
      "includes": [
        "tbl1.PLATFORM",
        "tbl1.OS_VERSION"
      ],
      "select_rule": {
        "hierarchy_dims": [],
        "mandatory_dims": [
          "tbl1.DATE_HR"
        ],
        "joint_dims": []
      }
    }
  ],
  "signature": "ttrrs==",
  "notify_list": [],
  "status_need_notify": [
    "ERROR",
    "DISCARDED",
    "SUCCEED"
  ],
  "partition_date_start": 0,
  "partition_date_end": 3153600000000,
  "auto_merge_time_ranges": [
    604800000,
    2419200000
  ],
  "volatile_range": 0,
  "retention_range": 0,
  "engine_type": 4,
  "storage_type": 2,
  "override_kylin_properties": {
    "job.queuename": "root.production.P0",
    "is-mandatory-only-valid": "true"
  },
  "cuboid_black_list": [],
  "parent_forward": 3,
  "mandatory_dimension_set_list": [],
  "snapshot_table_desc_list": []
}
</code>```

This is a snippet of the code I tried, and it is giving a null list

```<code>import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = org.json4s.DefaultFormats

case class Function (
                      expression: String,
                      parameter: Parameter,
                      returntype: String
                    )

case class Parameter (
                       `type`: String,
                       value: String
                     )

case class Measures (
                      name: String,
                      function: Function
                    )

case class AllMeasuresData(uuid: String, measure: List[Measures])

val data = parse(tmp).extract[AllMeasuresData]
val names = data.measure.map(_.name)

println(names)

case class AllMeasuresData(uuid: String, measure: List[Measures])

val data = parse(tmp).extract[AllMeasuresData]
val names = data.measure.map(_.name)

println(names)
</code>```

答:
There are couple typos in your ADT:

Here is what you need:

  case class Function (
                        expression: String,
                        parameter: Parameter,
                        returntype: String
                      )

  case class Parameter (
                         `type`: String,
                         value: String
                       )

  case class Measures (
                        name: String,
                        function: Function
                      )

  case class AllMeasuresData(uuid: String, measures: List[Measures])
```

<p>There is also an extra comma int the json, here is the correct:</p>

```  {
   "uuid":"uuidddd",
   "last_modified":1559080222953,
   "version":"2.6.1.0",
   "name":"FULL_DAY_2_mand_date",
   "is_draft":false,
   "model_name":"FULL_DAY_1_may05",
   "description":"",
   "null_string":null,
   "dimensions":[
      {
         "name":"PLATFORM",
         "table":"tbl1",
         "column":"PLATFORM",
         "derived":null
      },
      {
         "name":"OS_VERSION",
         "table":"tbl1",
         "column":"OS_VERSION",
         "derived":null
      } // There was an extra trailing comma here
   ],
   "measures":[
      {
         "name":"_COUNT_",
         "function":{
            "expression":"COUNT",
            "parameter":{
               "type":"constant",
               "value":"1"
            },
            "returntype":"bigint"
         }
      },
      {
         "name":"UU",
         "function":{
            "expression":"COUNT_DISTINCT",
            "parameter":{
               "type":"column",
               "value":"tbl1.USER_ID"
            },
            "returntype":"hllc(12)"
         }
      },
      {
         "name":"CONT_SIZE",
         "function":{
            "expression":"SUM",
            "parameter":{
               "type":"column",
               "value":"tbl1.SIZE"
            },
            "returntype":"bigint"
         }
      },
      {
         "name":"CONT_COUNT",
         "function":{
            "expression":"SUM",
            "parameter":{
               "type":"column",
               "value":"tbl1.COUNT"
            },
            "returntype":"bigint"
         }
      }
   ],
   "dictionaries":[

   ],
   "rowkey":{
      "rowkey_columns":[
         {
            "column":"tbl1.OS_VERSION",
            "encoding":"dict",
            "encoding_version":1,
            "isShardBy":false
         },
         {
            "column":"tbl1.PLATFORM",
            "encoding":"dict",
            "encoding_version":1,
            "isShardBy":false
         },
         {
            "column":"tbl1.DEVICE_FAMILY",
            "encoding":"dict",
            "encoding_version":1,
            "isShardBy":false
         }
      ]
   },
   "hbase_mapping":{
      "column_family":[
         {
            "name":"F1",
            "columns":[
               {
                  "qualifier":"M",
                  "measure_refs":[
                     "_COUNT_",
                     "CONT_SIZE",
                     "CONT_COUNT"
                  ]
               }
            ]
         },
         {
            "name":"F2",
            "columns":[
               {
                  "qualifier":"M",
                  "measure_refs":[
                     "UU"
                  ]
               }
            ]
         }
      ]
   },
   "aggregation_groups":[
      {
         "includes":[
            "tbl1.PLATFORM",
            "tbl1.OS_VERSION"
         ],
         "select_rule":{
            "hierarchy_dims":[

            ],
            "mandatory_dims":[
               "tbl1.DATE_HR"
            ],
            "joint_dims":[

            ]
         }
      }
   ],
   "signature":"ttrrs==",
   "notify_list":[

   ],
   "status_need_notify":[
      "ERROR",
      "DISCARDED",
      "SUCCEED"
   ],
   "partition_date_start":0,
   "partition_date_end":3153600000000,
   "auto_merge_time_ranges":[
      604800000,
      2419200000
   ],
   "volatile_range":0,
   "retention_range":0,
   "engine_type":4,
   "storage_type":2,
   "override_kylin_properties":{
      "job.queuename":"root.production.P0",
      "is-mandatory-only-valid":"true"
   },
   "cuboid_black_list":[

   ],
   "parent_forward":3,
   "mandatory_dimension_set_list":[

   ],
   "snapshot_table_desc_list":[

   ]
}

```

<p>Now you can run:</p>

```  val data = parse(tmp).extract[AllMeasuresData]
  val names = data.measures.map(_.name)

  println(names)
// Displays
// List(_COUNT_, UU, CONT_SIZE, CONT_COUNT)
```

Title: Parse Complex JSON -- Map

Body:
I need to parse the complex JSON (below) IN SCALA to get the values of "expression" and "value" in "measure" key i.e I need List (COUNT, COUNT_DISTINCT ...) and List (1,tbl1.USER_ID ...).

I tried multiple options, but it is not working. Any help is appreciated

{
  "uuid": "uuidddd",
  "last_modified": 1559080222953,
  "version": "2.6.1.0",
  "name": "FULL_DAY_2_mand_date",
  "is_draft": false,
  "model_name": "FULL_DAY_1_may05",
  "description": "",
  "null_string": null,
  "dimensions": [
    {
      "name": "PLATFORM",
      "table": "tbl1",
      "column": "PLATFORM",
      "derived": null
    },
    {
      "name": "OS_VERSION",
      "table": "tbl1",
      "column": "OS_VERSION",
      "derived": null
    }
  ],
  "measures": [
    {
      "name": "_COUNT_",
      "function": {
        "expression": "COUNT",
        "parameter": {
          "type": "constant",
          "value": "1"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "UU",
      "function": {
        "expression": "COUNT_DISTINCT",
        "parameter": {
          "type": "column",
          "value": "tbl1.USER_ID"
        },
        "returntype": "hllc(12)"
      }
    },
    {
      "name": "CONT_SIZE",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.SIZE"
        },
        "returntype": "bigint"
      }
    },
    {
      "name": "CONT_COUNT",
      "function": {
        "expression": "SUM",
        "parameter": {
          "type": "column",
          "value": "tbl1.COUNT"
        },
        "returntype": "bigint"
      }
    }
  ],
  "dictionaries": [],
  "rowkey": {
    "rowkey_columns": [
      {
        "column": "tbl1.OS_VERSION",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.PLATFORM",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      },
      {
        "column": "tbl1.DEVICE_FAMILY",
        "encoding": "dict",
        "encoding_version": 1,
        "isShardBy": false
      }
    ]
  },
  "hbase_mapping": {
    "column_family": [
      {
        "name": "F1",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "_COUNT_",
              "CONT_SIZE",
              "CONT_COUNT"
            ]
          }
        ]
      },
      {
        "name": "F2",
        "columns": [
          {
            "qualifier": "M",
            "measure_refs": [
              "UU"
            ]
          }
        ]
      }
    ]
  },
  "aggregation_groups": [
    {
      "includes": [
        "tbl1.PLATFORM",
        "tbl1.OS_VERSION"
      ],
      "select_rule": {
        "hierarchy_dims": [],
        "mandatory_dims": [
          "tbl1.DATE_HR"
        ],
        "joint_dims": []
      }
    }
  ],
  "signature": "ttrrs==",
  "notify_list": [],
  "status_need_notify": [
    "ERROR",
    "DISCARDED",
    "SUCCEED"
  ],
  "partition_date_start": 0,
  "partition_date_end": 3153600000000,
  "auto_merge_time_ranges": [
    604800000,
    2419200000
  ],
  "volatile_range": 0,
  "retention_range": 0,
  "engine_type": 4,
  "storage_type": 2,
  "override_kylin_properties": {
    "job.queuename": "root.production.P0",
    "is-mandatory-only-valid": "true"
  },
  "cuboid_black_list": [],
  "parent_forward": 3,
  "mandatory_dimension_set_list": [],
  "snapshot_table_desc_list": []
}

This is a snippet of the code I tried, and it is giving a null list

import org.json4s._
import org.json4s.jackson.JsonMethods._

implicit val formats = org.json4s.DefaultFormats

case class Function (
                      expression: String,
                      parameter: Parameter,
                      returntype: String
                    )

case class Parameter (
                       `type`: String,
                       value: String
                     )

case class Measures (
                      name: String,
                      function: Function
                    )

case class AllMeasuresData(uuid: String, measure: List[Measures])

val data = parse(tmp).extract[AllMeasuresData]
val names = data.measure.map(_.name)

println(names)

case class AllMeasuresData(uuid: String, measure: List[Measures])

val data = parse(tmp).extract[AllMeasuresData]
val names = data.measure.map(_.name)

println(names)

Body:
There are couple typos in your ADT:

Here is what you need:

  case class Function (
                        expression: String,
                        parameter: Parameter,
                        returntype: String
                      )

  case class Parameter (
                         `type`: String,
                         value: String
                       )

  case class Measures (
                        name: String,
                        function: Function
                      )

  case class AllMeasuresData(uuid: String, measures: List[Measures])

There is also an extra comma int the json, here is the correct:

  {
   "uuid":"uuidddd",
   "last_modified":1559080222953,
   "version":"2.6.1.0",
   "name":"FULL_DAY_2_mand_date",
   "is_draft":false,
   "model_name":"FULL_DAY_1_may05",
   "description":"",
   "null_string":null,
   "dimensions":[
      {
         "name":"PLATFORM",
         "table":"tbl1",
         "column":"PLATFORM",
         "derived":null
      },
      {
         "name":"OS_VERSION",
         "table":"tbl1",
         "column":"OS_VERSION",
         "derived":null
      } // There was an extra trailing comma here
   ],
   "measures":[
      {
         "name":"_COUNT_",
         "function":{
            "expression":"COUNT",
            "parameter":{
               "type":"constant",
               "value":"1"
            },
            "returntype":"bigint"
         }
      },
      {
         "name":"UU",
         "function":{
            "expression":"COUNT_DISTINCT",
            "parameter":{
               "type":"column",
               "value":"tbl1.USER_ID"
            },
            "returntype":"hllc(12)"
         }
      },
      {
         "name":"CONT_SIZE",
         "function":{
            "expression":"SUM",
            "parameter":{
               "type":"column",
               "value":"tbl1.SIZE"
            },
            "returntype":"bigint"
         }
      },
      {
         "name":"CONT_COUNT",
         "function":{
            "expression":"SUM",
            "parameter":{
               "type":"column",
               "value":"tbl1.COUNT"
            },
            "returntype":"bigint"
         }
      }
   ],
   "dictionaries":[

   ],
   "rowkey":{
      "rowkey_columns":[
         {
            "column":"tbl1.OS_VERSION",
            "encoding":"dict",
            "encoding_version":1,
            "isShardBy":false
         },
         {
            "column":"tbl1.PLATFORM",
            "encoding":"dict",
            "encoding_version":1,
            "isShardBy":false
         },
         {
            "column":"tbl1.DEVICE_FAMILY",
            "encoding":"dict",
            "encoding_version":1,
            "isShardBy":false
         }
      ]
   },
   "hbase_mapping":{
      "column_family":[
         {
            "name":"F1",
            "columns":[
               {
                  "qualifier":"M",
                  "measure_refs":[
                     "_COUNT_",
                     "CONT_SIZE",
                     "CONT_COUNT"
                  ]
               }
            ]
         },
         {
            "name":"F2",
            "columns":[
               {
                  "qualifier":"M",
                  "measure_refs":[
                     "UU"
                  ]
               }
            ]
         }
      ]
   },
   "aggregation_groups":[
      {
         "includes":[
            "tbl1.PLATFORM",
            "tbl1.OS_VERSION"
         ],
         "select_rule":{
            "hierarchy_dims":[

            ],
            "mandatory_dims":[
               "tbl1.DATE_HR"
            ],
            "joint_dims":[

            ]
         }
      }
   ],
   "signature":"ttrrs==",
   "notify_list":[

   ],
   "status_need_notify":[
      "ERROR",
      "DISCARDED",
      "SUCCEED"
   ],
   "partition_date_start":0,
   "partition_date_end":3153600000000,
   "auto_merge_time_ranges":[
      604800000,
      2419200000
   ],
   "volatile_range":0,
   "retention_range":0,
   "engine_type":4,
   "storage_type":2,
   "override_kylin_properties":{
      "job.queuename":"root.production.P0",
      "is-mandatory-only-valid":"true"
   },
   "cuboid_black_list":[

   ],
   "parent_forward":3,
   "mandatory_dimension_set_list":[

   ],
   "snapshot_table_desc_list":[

   ]
}

Now you can run:

  val data = parse(tmp).extract[AllMeasuresData]
  val names = data.measures.map(_.name)

  println(names)
// Displays
// List(_COUNT_, UU, CONT_SIZE, CONT_COUNT)


来源: stackexchange

问:
Why does the assignment statement does not work when using "$?" at second time in bash scripts
I run my scripts by bash. I found that my statement does not work when using second "RESULT=$?" command. Why?

The first varible equal "0", but why the second one is NULL ?

```<code>sudo pip --version
RESULT_SUDO=$?

pip --version
RESULTP_USER=$?

echo "${RESULT_SUDO}--------------"
echo "${RESULT_USER}=============="
</code>```

答:
Because you have a typo. Try to change

```<code>RESULTP_USER=$?
</code>```

to

```<code>RESULT_USER=$?
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I run my scripts by bash. I found that my statement does not work when using second "RESULT=$?" command. Why?

The first varible equal "0", but why the second one is NULL ?

sudo pip --version
RESULT_SUDO=$?

pip --version
RESULTP_USER=$?

echo "${RESULT_SUDO}--------------"
echo "${RESULT_USER}=============="

Body:
Because you have a typo. Try to change

RESULTP_USER=$?

to

RESULT_USER=$?


问:
getting exception:org.springframework.data.redis.connection.RedisConnection.getConfig(Ljava/lang/String;)Ljava/util/List;
I am trying to use Redis in spring boot application for the session by adding dependencies like:

```<code><dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
   <version>1.5.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session</artifactId>
    <version>1.3.3.RELEASE</version>
</dependency>
</code>```

And the code for Redis is like:

```<code>package com.dci.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import
org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;

@Configuration
@ComponentScan("com.dci")
@EnableRedisHttpSession
public class RedisConfig extends AbstractHttpSessionApplicationInitializer {

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();

        return factory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory());

        template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
        return template;
    }
}
</code>```

答:
JedisConnectionFactory and RedisTemplate beans are not needed with Spring boot, but in your file "Spring Security Config" add:

```<code>     @Bean
     public HttpSessionStrategy httpSessionStrategy() {
         return new HeaderHttpSessionStrategy();
     }
</code>```

In the pom add the following dependencies:

```<code><! - Spring Session ->
<Dependency>
  <GroupId> org.springframework.session </ groupId>
  <ArtifactId> spring-session </ artifactId>
  <Version> 1.3.5.RELEASE </ version>
</ Dependency>

<! - redis server ->
<Dependency>
  <GroupId> org.springframework.data </ groupId>
  <ArtifactId> spring-data-redis </ artifactId>
  </ Dependency>
<Dependency>
  <GroupId> redis.clients </ groupId>
  <ArtifactId> Jedis </ artifactId>
</ Dependency>
</code>```

In your configuration file (es. application.properties) add:
spring.session.store-type = none

Spring Boot will do everything else.

Body:
I am trying to use Redis in spring boot application for the session by adding dependencies like:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
   <version>1.5.9.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session</artifactId>
    <version>1.3.3.RELEASE</version>
</dependency>

And the code for Redis is like:

package com.dci.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import
org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;

@Configuration
@ComponentScan("com.dci")
@EnableRedisHttpSession
public class RedisConfig extends AbstractHttpSessionApplicationInitializer {

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();

        return factory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        final RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory());

        template.setValueSerializer(new GenericToStringSerializer<Object>(Object.class));
        return template;
    }
}

Body:
JedisConnectionFactory and RedisTemplate beans are not needed with Spring boot, but in your file "Spring Security Config" add:

     @Bean
     public HttpSessionStrategy httpSessionStrategy() {
         return new HeaderHttpSessionStrategy();
     }

In the pom add the following dependencies:

<! - Spring Session ->
<Dependency>
  <GroupId> org.springframework.session </ groupId>
  <ArtifactId> spring-session </ artifactId>
  <Version> 1.3.5.RELEASE </ version>
</ Dependency>

<! - redis server ->
<Dependency>
  <GroupId> org.springframework.data </ groupId>
  <ArtifactId> spring-data-redis </ artifactId>
  </ Dependency>
<Dependency>
  <GroupId> redis.clients </ groupId>
  <ArtifactId> Jedis </ artifactId>
</ Dependency>

In your configuration file (es. application.properties) add:
spring.session.store-type = none

Spring Boot will do everything else.


问:
Divide Number Array into chunk of 3 using Reduce
There can be multiple approach to solve this but I am not sure why this one specifically is not working as expected.

```<code>[1,2,3,4,5,6,7,8].reduce((a, d, i, c) => [...a, c.splice(0, 3)], [])
</code>```

Result - [[1,2,3], [4,5,6]]

Expected Result - [[1,2,3], [4,5,6], [7,8]]

Please do not change the approach as I want to know why this one is not working as expected.

答:
This happens because you're mutating the array while iterating. In particular, the problem is that when reduce reaches the third element, there are only two elements.

[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, d, i, c) => {
  console.log("current result", a)
  console.log("current element", d)
  console.log("index", i)
  console.log("array", c)
  return [...a, c.splice(0, 3)]
}, [])```

So, when you get to the third iteration where i should be 2, the content of the array (c) is [7, 8]. Since that cannot work, there is no third iteration.

Body:
There can be multiple approach to solve this but I am not sure why this one specifically is not working as expected.

[1,2,3,4,5,6,7,8].reduce((a, d, i, c) => [...a, c.splice(0, 3)], [])

Result - [[1,2,3], [4,5,6]]

Expected Result - [[1,2,3], [4,5,6], [7,8]]

Please do not change the approach as I want to know why this one is not working as expected.

Body:
This happens because you're mutating the array while iterating. In particular, the problem is that when reduce reaches the third element, there are only two elements.

[1, 2, 3, 4, 5, 6, 7, 8].reduce((a, d, i, c) => {
  console.log("current result", a)
  console.log("current element", d)
  console.log("index", i)
  console.log("array", c)
  return [...a, c.splice(0, 3)]
}, [])

So, when you get to the third iteration where i should be 2, the content of the array (c) is [7, 8]. Since that cannot work, there is no third iteration.


问:
Docker compose is not finding network from swarm host
I have one server where I create an overlay network with the following command:

```<code>docker network create --driver=overlay --attachable caja_gestiones
</code>```

In server two I want to use my docker compose to deploy all my containers and one of them use the gestiones network and the default network, this is my docker-compose.yml:

```<code>version: '3.3'
services:
  msgestiones:
    image: msgestiones:latest
    hostname: msgestiones
    container_name: msgestiones
    environment:
      - perfil=desarrollo
      - JAVA_OPTS=-Xmx512M -Xms512M
      - TZ=America/Mexico_City
    networks:
      - marcador
      - caja_gestiones
  msmovimientos:
    image: msmovimientos:latest
    hostname: msmovimientos
    container_name: msmovimientos
    environment:
      - perfil=desarrollo
      - JAVA_OPTS=-Xmx512M -Xms512M
      - TZ=America/Mexico_City
    networks:
      - marcador
networks:
  marcador:
    driver: bridge
  caja_gestiones:
    external:
      name: caja_gestiones
</code>```

When I ran the docker compose it throws an error saying that the network does not exists, but if I run a dummy container using that network, the network appear and the compose works, how can I make the compose use the overlay network without run a dummy container before?

答: Did you try to deploy it as a stack instead of a compose? You can use the same compose file, but deploy it with docker stack deploy -c composefile.yaml yourstackname?

Body:
I have one server where I create an overlay network with the following command:

docker network create --driver=overlay --attachable caja_gestiones

In server two I want to use my docker compose to deploy all my containers and one of them use the gestiones network and the default network, this is my docker-compose.yml:

version: '3.3'
services:
  msgestiones:
    image: msgestiones:latest
    hostname: msgestiones
    container_name: msgestiones
    environment:
      - perfil=desarrollo
      - JAVA_OPTS=-Xmx512M -Xms512M
      - TZ=America/Mexico_City
    networks:
      - marcador
      - caja_gestiones
  msmovimientos:
    image: msmovimientos:latest
    hostname: msmovimientos
    container_name: msmovimientos
    environment:
      - perfil=desarrollo
      - JAVA_OPTS=-Xmx512M -Xms512M
      - TZ=America/Mexico_City
    networks:
      - marcador
networks:
  marcador:
    driver: bridge
  caja_gestiones:
    external:
      name: caja_gestiones

When I ran the docker compose it throws an error saying that the network does not exists, but if I run a dummy container using that network, the network appear and the compose works, how can I make the compose use the overlay network without run a dummy container before?


问:
what is Device Registration ID for firebase fcm and where I can extract them?
```<code>from pyfcm import FCMNotification

push_service = FCMNotification(api_key="<api-key>")

registration_id = "<device registration_id>"
message_title = "Uber update"
message_body = "Hi john, your customized news for today is ready"
result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)

print result
</code>```

I am working on Pyfcm for push notification, for which i want to get the device registration id.

答:
You can get token(=device registration_id)

In my code:

```<code>String newToken= instanceIdResult.getToken();
</code>```

Maybe in your code:

```<code>String newToken = FirebaseInstanceId.getInstance().getToken();
</code>```

so newToken = device registration_id

Body:
from pyfcm import FCMNotification

push_service = FCMNotification(api_key="<api-key>")

registration_id = "<device registration_id>"
message_title = "Uber update"
message_body = "Hi john, your customized news for today is ready"
result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)

print result

I am working on Pyfcm for push notification, for which i want to get the device registration id.

Body:
You can get token(=device registration_id)

In my code:

String newToken= instanceIdResult.getToken();

Maybe in your code:

String newToken = FirebaseInstanceId.getInstance().getToken();

so newToken = device registration_id


问:
Text size in dropdown list of suggestions differs from its AutoCompleteTextView
I set a smaller text size than the default in my AutoCompleteTextView, expecting the dropdown list of suggestions to have identical text size and font. However, clearly it is different. The suggestions list text size stayed the same while the EditBox (AutoCompleteTextView) text size was changed when I set it in the activity_main.xml with android:textSize="15dp". Here is the result.

I searched for a property that might control suggestions' text size but could not find it. What is the way to ensure that all text is the same size, suggestion and editbox.

Here is the code in case it is needed.

```<code>public class MainActivity extends AppCompatActivity {
    private static String [] countries = new String[] {"Vatican", "Brazil",
            "Switzerland", "Angola", "Haiti", "Puerto Rico", "Germany", "Mexico",
            "France", "Ireland", "India", "Australia", "Zimbabwe", "South Africa",
            "Canada", "Thailand", "Japan", "Chile", "Botswana", "El Salvador", "Cuba",
            "Vietnam", "Mongolia", "Morocco", "Italy", "Portugal", "Ukrain"
    };

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

        // Set up autocomplete widget
        AutoCompleteTextView countryTV = (AutoCompleteTextView) findViewById(R.id.autoCompleteQuery);

        ArrayAdapter<String> countriesList = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, countries);
        countryTV.setAdapter(countriesList);
}
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    tools:context=".MainActivity">

    <AutoCompleteTextView
        android:id="@+id/autoCompleteQuery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="375dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:background="@android:color/white"
        android:hint="Select Country"
        android:padding="10dp"
        android:textSize="15dp"
        android:singleLine="true"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Thanks

答:
Use custom layout for item of ArrayAdapter like below:

item_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="15dp"
        android:singleLine="true"
        android:textColor="@android:color/black"
        android:background="@android:color/white"/>
</LinearLayout>
</code>```

Set layout in Array Adapter

```<code>ArrayAdapter<String> countriesList = new ArrayAdapter<>(this,
               R.layout.item_layout, countries);
countryTV.setAdapter(countriesList);
</code>```

I hope its work for you.

Body:
I set a smaller text size than the default in my AutoCompleteTextView, expecting the dropdown list of suggestions to have identical text size and font. However, clearly it is different. The suggestions list text size stayed the same while the EditBox (AutoCompleteTextView) text size was changed when I set it in the activity_main.xml with android:textSize="15dp". Here is the result.

I searched for a property that might control suggestions' text size but could not find it. What is the way to ensure that all text is the same size, suggestion and editbox.

Here is the code in case it is needed.

public class MainActivity extends AppCompatActivity {
    private static String [] countries = new String[] {"Vatican", "Brazil",
            "Switzerland", "Angola", "Haiti", "Puerto Rico", "Germany", "Mexico",
            "France", "Ireland", "India", "Australia", "Zimbabwe", "South Africa",
            "Canada", "Thailand", "Japan", "Chile", "Botswana", "El Salvador", "Cuba",
            "Vietnam", "Mongolia", "Morocco", "Italy", "Portugal", "Ukrain"
    };

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

        // Set up autocomplete widget
        AutoCompleteTextView countryTV = (AutoCompleteTextView) findViewById(R.id.autoCompleteQuery);

        ArrayAdapter<String> countriesList = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, countries);
        countryTV.setAdapter(countriesList);
}

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    tools:context=".MainActivity">

    <AutoCompleteTextView
        android:id="@+id/autoCompleteQuery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="375dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:background="@android:color/white"
        android:hint="Select Country"
        android:padding="10dp"
        android:textSize="15dp"
        android:singleLine="true"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Thanks

Body:
Use custom layout for item of ArrayAdapter like below:

item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textSize="15dp"
        android:singleLine="true"
        android:textColor="@android:color/black"
        android:background="@android:color/white"/>
</LinearLayout>

Set layout in Array Adapter

ArrayAdapter<String> countriesList = new ArrayAdapter<>(this,
               R.layout.item_layout, countries);
countryTV.setAdapter(countriesList);

I hope its work for you.


问:
SQLiteDatabase vs File storage
I want to store structure type data (i.e. information of call logs like name, number, type of number, date, time, duration). Which is the best way and which is faster? SQLiteDatabase (make table and insert, delete logs in it) or use file storage (means make one class for all parameters and write their objects in file using input/output Stream and serializable) or the another way i heard about it is XML parser but i don't know this.

Please help me. Thanks in advance.

答: Personally, given you know the basics of Databases I would use a sqlite database. It's pretty straight forward in Android. In terms of speed I don't know which is faster, but if you don't have millions of datasets it won't matter.</p>

ContentLicense: CC BY-SA 3.0

Title: SQLiteDatabase vs File storage


问:
How to show mobile view in mobile device?
I have problem with wordpress theme , when I open my website in mobile the theme is exactly desktop view but when I change the view to mobile view in inspect element it's work true .

https://www.pdfcar.com

答:
I'm not sure if I understood your question, but try to add the following line to the -tag of your HTML-file:

```<code><meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0" name="viewport">
</code>```

Body:
I'm not sure if I understood your question, but try to add the following line to the <head>-tag of your HTML-file:

<meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0" name="viewport">


问:
Order list based on another list index
I am with no math background so struggling in a simple thing.

```<code>from dataclasses import dataclass

@dataclass
class Country:
    cc:str
    name:str

countries_info = [
    ('DE', 'Germany'),
    ('EP', 'Europe'),
    ('US', 'United States'),
    ('IN', 'India')
]
countries = [Country(cc, name)
                for cc, name in countries_info]

# sort based on a particular order
order = ['US', 'IN']
sorted(countries, key=lambda x: order.index(x.cc) if x.cc in order else -1)
</code>```

Out put:

```<code>[Country(cc='DE', name='Germany'),
 Country(cc='EP', name='Europe'),
 Country(cc='US', name='United States'),
 Country(cc='IN', name='India')]
</code>```

What I want is

```<code>[Country(cc='US', name='United States'),
 Country(cc='IN', name='India'),
 Country(cc='DE', name='Germany'),
 Country(cc='EP', name='Europe')]
</code>```

Means only sort the countries based on order and make them appear first. do not touch the order of rest

In case of conflict like the same cc, this is desirable.

```<code>[Country(cc='US', name='United States'),
 Country(cc='US', name='United States of America')
 Country(cc='IN', name='Bharat'),
 Country(cc='IN', name='India'),
 Country(cc='DE', name='Germany'),
 Country(cc='EP', name='Europe')]
</code>```

Means It doesn't matter which comes first in case of conflict.

答:
The return of the key function is used to sort the list. By returning -1 for those not in order, you inadvertently pushed them to the front instead. The following code should work:

```<code>sorted(countries, key=lambda x: order.index(x.cc) if x.cc in order else len(order))
</code>```

I returned len(order) for others, because index will always be less than it. sorted ensures a stable sort, meaning for equal values the original order is not changed.

Edit: This would also apply to duplicated cc values inside order, because index would return the first occurrence for each of them. So their relative order would also remain unchanged. If you want a specific order, you can simply replace order.index(x.cc) with another suitable value.

Title: Order list based on another list index

Body:
I am with no math background so struggling in a simple thing.

from dataclasses import dataclass

@dataclass
class Country:
    cc:str
    name:str

countries_info = [
    ('DE', 'Germany'),
    ('EP', 'Europe'),
    ('US', 'United States'),
    ('IN', 'India')
]
countries = [Country(cc, name)
                for cc, name in countries_info]

# sort based on a particular order
order = ['US', 'IN']
sorted(countries, key=lambda x: order.index(x.cc) if x.cc in order else -1)

Out put:

[Country(cc='DE', name='Germany'),
 Country(cc='EP', name='Europe'),
 Country(cc='US', name='United States'),
 Country(cc='IN', name='India')]

What I want is

[Country(cc='US', name='United States'),
 Country(cc='IN', name='India'),
 Country(cc='DE', name='Germany'),
 Country(cc='EP', name='Europe')]

Means only sort the countries based on order and make them appear first. do not touch the order of rest

In case of conflict like the same cc, this is desirable.

[Country(cc='US', name='United States'),
 Country(cc='US', name='United States of America')
 Country(cc='IN', name='Bharat'),
 Country(cc='IN', name='India'),
 Country(cc='DE', name='Germany'),
 Country(cc='EP', name='Europe')]

Means It doesn't matter which comes first in case of conflict.

Body:
The return of the key function is used to sort the list. By returning -1 for those not in order, you inadvertently pushed them to the front instead. The following code should work:

sorted(countries, key=lambda x: order.index(x.cc) if x.cc in order else len(order))

I returned len(order) for others, because index will always be less than it. sorted ensures a stable sort, meaning for equal values the original order is not changed.

Edit: This would also apply to duplicated cc values inside order, because index would return the first occurrence for each of them. So their relative order would also remain unchanged. If you want a specific order, you can simply replace order.index(x.cc) with another suitable value.


问:
What does left arrow <- mean outside a do block?
I came across with the following code recently and it bothers me a lot

```<code>lowerSafeForeignCall dflags block
| (entry, middle, CmmForeignCall { .. }) <- blockSplit block
= do
 -- do block stuffs
 -- Block doesn't end in a safe foreign call:
| otherwise = return block
</code>```

This piece of code is from
https://phabricator.haskell.org/rGHCb0534f78a73f972e279eed4447a5687bd6a8308e

in file compiler/cmm/CmmLayoutStack.hs

line 983

I really would like to konw what is this <- in the second line.
I believe lowerSafeForeignCall is a function and the | and 'otherwise' indicate this function uses guards. So

```<code>(entry, middle, CmmForeignCall { .. }) <- blockSplit block
</code>```

must be of type Bool. But the <- is outside any do block.
I did some search online but still not a single clue about this usage.

答:
This is a pattern guard [Haskell-wiki]. Since Haskell'10 a guard is a list of qualifiers. A qualifier can be a condition (like in the old guards), and pattern guards.

Haskell will thus (lazily) evaluate the expression on the right side of the arrow <- and aim to match it with the pattern on the left of the arrow. If that succeeds, than the guard (well that part of the guard) is successful. If all the parts of the guard are successful, then the rule "fires".

In this specific case the only part of the pattern that might fail is the fact that the third item of the 3-tuple is not a CmmForeignCall data constructor. Furthermore by using this pattern guard, we can of course use entry, middle in the body of the expression.

Body:
I came across with the following code recently and it bothers me a lot

lowerSafeForeignCall dflags block
| (entry, middle, CmmForeignCall { .. }) <- blockSplit block
= do
 -- do block stuffs
 -- Block doesn't end in a safe foreign call:
| otherwise = return block

This piece of code is from
https://phabricator.haskell.org/rGHCb0534f78a73f972e279eed4447a5687bd6a8308e

in file compiler/cmm/CmmLayoutStack.hs

line 983

I really would like to konw what is this <- in the second line.
I believe lowerSafeForeignCall is a function and the | and 'otherwise' indicate this function uses guards. So

(entry, middle, CmmForeignCall { .. }) <- blockSplit block

must be of type Bool. But the <- is outside any do block.
I did some search online but still not a single clue about this usage.


问:
How to import a json file with _id (string) as _id (objectId) in mongodb?
I have an array which has multiple objects and objects have _id (string) already set. While I import the file, i want all _id (string) to get imported into _id (objectId).

I have tried manually using "$oid" but it is not a dynamic solution to my problem.

my import statement

```<code>mongoimport --db delivera --collection restaurants --drop --file list.json --jsonArray
</code>```

my example object

```<code>{
"_id":"5a6900fff467be65019a9001",
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}
</code>```

答:
Try importing to a temporary collection & inserting it from there,

in your case,

```<code>mongoimport --db myApp --collection tempCollection --drop --file list.json --jsonArray
</code>```

From mongo shell

```<code>db.tempCollection.find().forEach(function (doc) {
    doc._id = doc._id + ''
    db.restaurants.insert(doc)
});
</code>```

Note: The answer was seen somewhere before, wasn't able to find in stackoverflow, may be some forums.

Body:
I have an array which has multiple objects and objects have _id (string) already set. While I import the file, i want all _id (string) to get imported into _id (objectId).

I have tried manually using "$oid" but it is not a dynamic solution to my problem.

my import statement

mongoimport --db delivera --collection restaurants --drop --file list.json --jsonArray

my example object

{
"_id":"5a6900fff467be65019a9001",
"date":"2018-01-24T21:56:15.353Z",
"title":"Italian pasta",
"restaurant": "coffee bean",
"__v":0
}

Body:
Try importing to a temporary collection & inserting it from there,

in your case,

mongoimport --db myApp --collection tempCollection --drop --file list.json --jsonArray

From mongo shell

db.tempCollection.find().forEach(function (doc) {
    doc._id = doc._id + ''
    db.restaurants.insert(doc)
});

Note: The answer was seen somewhere before, wasn't able to find in stackoverflow, may be some forums.


问:
Flutter - Create list and 'addAll' in same instruction
I'm trying to search a element in the  array. When get  it i need to append some element of the end of the array.

I try similar to this.

```<code>List dataModelo = allMakers //THIS IS THE MAIN ARRRAY
                                    .where((modelo) =>
                                        modelo["fabricante"] ==
                                        fabricante["fabricante"])
                                    .toList()
                                    .addAll([
                                  {
                                    "id": 0,
                                    "fabricante":
                                        'Test,
                                    "modelo":
                                        'Test'
                                  }
                                ]);
</code>```

But return

The expression here has a type of 'void', and therefore cannot be
  used.

So anybody know how can i do that?

SOLUTION:

```<code> dataModelo = allMakers
                                .where((modelo) =>
                                    modelo["fabricante"] ==
                                    fabricante["fabricante"])
                                .followedBy([
                              {
                                "id": 0,
                                "fabricante":
                                   'TEXT',
                                "modelo":
                                    'TEXT'
                              }
                            ]).toList();
</code>```

答:
Use cascade notation after the .where(/**/).toList() part.

e.g.

final arr = [1, 2, 3];
print(arr.where((a) => a > 2).toList()
         ..addAll([ 4, 5 ])); // returns [3, 4, 5]
```

In other words, adding another . to your .addAll part should do the trick.

Body:
I'm trying to search a element in the  array. When get  it i need to append some element of the end of the array.

I try similar to this.

List dataModelo = allMakers //THIS IS THE MAIN ARRRAY
                                    .where((modelo) =>
                                        modelo["fabricante"] ==
                                        fabricante["fabricante"])
                                    .toList()
                                    .addAll([
                                  {
                                    "id": 0,
                                    "fabricante":
                                        'Test,
                                    "modelo":
                                        'Test'
                                  }
                                ]);

But return

The expression here has a type of 'void', and therefore cannot be
  used.

So anybody know how can i do that?

SOLUTION:

 dataModelo = allMakers
                                .where((modelo) =>
                                    modelo["fabricante"] ==
                                    fabricante["fabricante"])
                                .followedBy([
                              {
                                "id": 0,
                                "fabricante":
                                   'TEXT',
                                "modelo":
                                    'TEXT'
                              }
                            ]).toList();

Body:
Use cascade notation after the .where(/**/).toList() part.

e.g.

final arr = [1, 2, 3];
print(arr.where((a) => a > 2).toList()
         ..addAll([ 4, 5 ])); // returns [3, 4, 5]

In other words, adding another . to your .addAll part should do the trick.


问:
How to use OpenGL 2.0 rather than a later version?
The goal is to make a game which will be compatible with many Graphics cards, and cross-platform. I decided to go with OpenGL 2.0 and Glut.

I quickly came to realize however, that there are no specific DLL for version OpenGL version 1.0, 2.0, 2.1... This lead me to wonder, how exactly do you choose which OpenGL version you need?

Also, I am aware that Windows Visual Studio only comes with OpenGL version 1.1. That is why I decided to use Glut, so that I could use functions from a later version of OpenGL such as 2.0.

The question remains, how do I use a certain version of OpenGL?

答: In OpenGL 2.x and earlier you just create a context.  That context must be backwards compatible with any version of OpenGL you care to use.  In OpenGL 3.0 and latter where strict API backwards compatibility was done away with there is a new method of context creation that allows you to specify the OpenGL version as attributes.</p>


答:
That's a pattern guard:

guard       →   pat <- infixexp         (pattern guard)

[...]

A guard has one of the following forms:

pattern guards are of the form p <- e, where p is a pattern (see Section 3.17) of type t and e is an expression type t. They succeed if the expression e matches the pattern p, and introduce the bindings of the pattern to the environment.

Where normal guards are limited to a boolean check, pattern guards can match against an arbitrary pattern and define local variables. (In your case entry, middle, and the contents of CmmForeignCall will be directly available in the function body.)

You can think of boolean guards as equivalent to pattern guards with a pattern of True:

```<code>| expr
</code>```

works like

```<code>| True <- expr
</code>```

Title: What does left arrow <- mean outside a do block?

Body:
That's a pattern guard:

guard       →   pat <- infixexp         (pattern guard)

[...]

A guard has one of the following forms:

pattern guards are of the form p <- e, where p is a pattern (see Section 3.17) of type t and e is an expression type t. They succeed if the expression e matches the pattern p, and introduce the bindings of the pattern to the environment.

Where normal guards are limited to a boolean check, pattern guards can match against an arbitrary pattern and define local variables. (In your case entry, middle, and the contents of CmmForeignCall will be directly available in the function body.)

You can think of boolean guards as equivalent to pattern guards with a pattern of True:

| expr

works like

| True <- expr


问:
subtract two different sum of column from two different table in select query
I have two tables with the name of add_sell and add_expense.
I have inserted some of value into the tables. I wanted to get the total profit result. I did it myself but the result is showing 0 . Now how can I do that. I also give the total profit formula. Is anyone here to help me? Here is the code given below

```<code>function totalSell(){
    global $conn;
    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        if(mysqli_num_rows($result) > 0){

        while($fetch = mysqli_fetch_array($result)){
        echo "SR ".$fetch['Sumearning'];
       }
    }
}

function totalExpense(){
    global $conn;
    $ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
    $run_ex = $conn->query($ex);
    if (mysqli_num_rows($run_ex) > 0) {
        while ($tex = mysqli_fetch_array($run_ex)) {
        echo "SR ".$tex['Sumexpense'];
        }
    }
}
</code>```

function totalProfit(){

```<code>    global $conn;

    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        while($fetch = mysqli_fetch_array($result)){
            $fetch['Sumearning'];
            echo "Total Earning : ".$totalEarning = "SR ".$fetch['Sumearning'];
       }

$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
        $run_ex = $conn->query($ex);

        while ($tex = mysqli_fetch_array($run_ex)) {
            $tex['Sumexpense'];
            echo "Total Expense : ".$totlaExpenss = "SR ".$tex['Sumexpense'];
        }
        echo "Your totla Profit is : ".$totalprofit = $totalEarning - $totlaExpenss;
}
</code>```

答:
Do you mean getting the difference between the Sum earnings and the Sum expenses?
Because you can do it like this?

$Total = $tex['Sumexpense'] - $fetch['Sumearning'];

Echo $total;

Body:
I have two tables with the name of add_sell and add_expense.
I have inserted some of value into the tables. I wanted to get the total profit result. I did it myself but the result is showing 0 . Now how can I do that. I also give the total profit formula. Is anyone here to help me? Here is the code given below

function totalSell(){
    global $conn;
    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        if(mysqli_num_rows($result) > 0){

        while($fetch = mysqli_fetch_array($result)){
        echo "SR ".$fetch['Sumearning'];
       }
    }
}

function totalExpense(){
    global $conn;
    $ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
    $run_ex = $conn->query($ex);
    if (mysqli_num_rows($run_ex) > 0) {
        while ($tex = mysqli_fetch_array($run_ex)) {
        echo "SR ".$tex['Sumexpense'];
        }
    }
}

function totalProfit(){

    global $conn;

    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        while($fetch = mysqli_fetch_array($result)){
            $fetch['Sumearning'];
            echo "Total Earning : ".$totalEarning = "SR ".$fetch['Sumearning'];
       }

$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
        $run_ex = $conn->query($ex);

        while ($tex = mysqli_fetch_array($run_ex)) {
            $tex['Sumexpense'];
            echo "Total Expense : ".$totlaExpenss = "SR ".$tex['Sumexpense'];
        }
        echo "Your totla Profit is : ".$totalprofit = $totalEarning - $totlaExpenss;
}


问:
IBM Integration bus, parsing json
Hello I have a problem to parse any JSON in IIB Toolkit. The exception thrown by java compute node is: java.lang.NoClassDefFoundError: org.json.JSONObject

I am parsing incoming JSON messages in UTF-8. I already tried to get them in JSON, but accepting them as BLOB and converting to JSON UTF-8 works for me.

```<code>String messageText = new String(outMessage.getRootElement().getLastChild().getLastChild().getValueAsString());
messageText = new String(DatatypeConverter.parseHexBinary(messageText),"UTF-8");
JSONObject json = new JSONObject("{}");
</code>```

I would love to create JSON object from JSON string in UTF-8

Many thanks in advance!

答:
So what you are trying to do is a bit of a no-no. You're trying to use the Java class JSONObject rather than using the builtin IIB Java Parser.

Have a look at MbElement in particular the methods createElementAsLastChild(java.lang.String parserName) and createElementAsLastChildFromBitstream.

As per my earlier answer never forget your are trying to build a tree of elements.

One other trick I sometimes use is to build a sample output message and send it to an Input node connected to a Trace node. I then use the Trace node output to write code to build my actual output tree, you can even put a Trace node after your JavaCompute node to see what the Element tree you've currently built looks like and correct your mistakes. I mostly use this method for SOAP messages which can be quite complex.

If you really want to use external Java classes then search for Using JAXB with a JavaCompute node and follow the links from that article.

Title: IBM Integration bus, parsing json

Body:
Hello I have a problem to parse any JSON in IIB Toolkit. The exception thrown by java compute node is: java.lang.NoClassDefFoundError: org.json.JSONObject

I am parsing incoming JSON messages in UTF-8. I already tried to get them in JSON, but accepting them as BLOB and converting to JSON UTF-8 works for me.

String messageText = new String(outMessage.getRootElement().getLastChild().getLastChild().getValueAsString());
messageText = new String(DatatypeConverter.parseHexBinary(messageText),"UTF-8");
JSONObject json = new JSONObject("{}");

I would love to create JSON object from JSON string in UTF-8

Many thanks in advance!


问:
Styling not applied to DataTable in angular component
I have an angular component with the JS DataTable within it.

The html for the component is similar to this:

```<code><h3>Test</h3>

<table class="table table-striped table-bordered table-hover" #table id="table">
  <thead>
    <tr>
      <th *ngFor="let column of columns">{{column.name}}</th>
    </tr>
  </thead>
</table>
</code>```

I have a css file for the component:

```<code>h3 {
  color: blue;
}

.paginate_button {
  padding: 100px;
}
</code>```

Any styling I add for the table isn't applied but the styling for the h3 is!

If I add the .paginate_button style to the global styles.css the style is applied.

What am I missing?

答:
JS DataTable is a component in itself which has it's own css file, that's why the style you overwrite in your component css file is not getting reflected. However, if we write some style in global styles.css, it is applied in all the component automatically.

Class paginate_button isn't present in your component's template. It is actually present in JS DataTable's compoent. So the style cannot be change. Hope this makes sense. Thanks.

You can try this in global style.css:

```<code>.paginate_button {
  padding: 100px !important;
}
</code>```

Body:
I have an angular component with the JS DataTable within it.

The html for the component is similar to this:

Test

      {{column.name}}

I have a css file for the component:

h3 {
  color: blue;
}

.paginate_button {
  padding: 100px;
}

Any styling I add for the table isn't applied but the styling for the h3 is!

If I add the .paginate_button style to the global styles.css the style is applied.

What am I missing?

Body:
JS DataTable is a component in itself which has it's own css file, that's why the style you overwrite in your component css file is not getting reflected. However, if we write some style in global styles.css, it is applied in all the component automatically.

Class paginate_button isn't present in your component's template. It is actually present in JS DataTable's compoent. So the style cannot be change. Hope this makes sense. Thanks.

You can try this in global style.css:

.paginate_button {
  padding: 100px !important;
}


问:
Remove an item of an inner array inside an array - react native
I've an json data that has an array. Each element of an array has array named items. I want to remove the inner array element if the string doesnot match the itemName. I tried using filter method but its not working as expected. It only returns the matching inner array elements but all the outer array elements are removed too.
P.S see the code, json data, the output I get and the expected output. Thanks in advance

Code:

```<code>const update2 =
 state.menuResponse.map(
       item => {
        return item.items.filter(item => (item.itemName).includes("C"))
})

console.log("menuSearcheddd", update2)
</code>```

Json data

```<code>{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "2",
          "itemName": "burger-non veg",
        }
      ]
    }
  ]
}
</code>```

Output:

```<code>{
  "data": [
    {
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "items": []
    }
  ]
}
</code>```

What should be?

```<code>{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": []
    }
  ]
}
</code>```

答:
The outer elements are removed not because of the filter method, but because of the map method. See, in your map method you are disregarding every other property because you only return what you process on the items array.

So, code should look more like this:

```<code>const update2 = state.menuResponse.map(item => ({ ...item, items: item.items.filter(subItem => subItem.itemName.includes('C')) }));
</code>```

So that from your map method you are returning everything that was inside you object before processing it and only modifying the items property by filtering the array like you have already done it.

Haven't managed to test it, but should work, in theory...

Body:
I've an json data that has an array. Each element of an array has array named items. I want to remove the inner array element if the string doesnot match the itemName. I tried using filter method but its not working as expected. It only returns the matching inner array elements but all the outer array elements are removed too.
P.S see the code, json data, the output I get and the expected output. Thanks in advance

Code:

const update2 =
 state.menuResponse.map(
       item => {
        return item.items.filter(item => (item.itemName).includes("C"))
})

console.log("menuSearcheddd", update2)

Json data

{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": [
        {
          "itemId": "1",
          "itemName": "burger",
        },
        {
          "itemId": "2",
          "itemName": "burger-non veg",
        }
      ]
    }
  ]
}

Output:

{
  "data": [
    {
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "items": []
    }
  ]
}

What should be?

{
  "data": [
    {
      "menuHeader": "Starters",
      "items": [
        {
          "itemId": "ITD1ZYTH",
          "itemName": "Cheese balls",
        }
      ]
    },
    {
      "menuHeader": "string",
      "items": []
    }
  ]
}

Body:
The outer elements are removed not because of the filter method, but because of the map method. See, in your map method you are disregarding every other property because you only return what you process on the items array.

So, code should look more like this:

const update2 = state.menuResponse.map(item => ({ ...item, items: item.items.filter(subItem => subItem.itemName.includes('C')) }));

So that from your map method you are returning everything that was inside you object before processing it and only modifying the items property by filtering the array like you have already done it.

Haven't managed to test it, but should work, in theory...


问:
Zoom QGraphicsItem to fit QGraphicsView
I am trying to create a QGraphicsView that will allow someone to scale the current QGraphicsItem to fit the size of the QGraphicsView window.

I have overridden QGraphicsItem to create a custom version, and I implemented some methods so it knows how much it has been scaled (which is always proportional to the original, so there is only one scale factor - the same for width and height).

So in the scaleFactor setter I have the following:

```<code>void ImagePixmapItem::setScaleFactor(float sf){
    scaleFactor = sf;
    this->boundingRect().setWidth(this->boundingRect().width()*scaleFactor);
    this->boundingRect().setHeight(this->boundingRect().height()*scaleFactor);

}
</code>```

And in my main form, I have the following in a button:

```<code>   QRect portRect = ui->graphicsView->viewport()->rect();
    double scaleFactorX;
   if(portRect.width() <= (item->boundingRect().size().width()))
       scaleFactorX =portRect.width() /(item->boundingRect().size().width());
   else
       scaleFactorX = (item->boundingRect().size().width())/portRect.width();

    qDebug("Scalefactor: %4.3f \n", scaleFactorX);
    qDebug("item width: %4.3f \n", item->boundingRect().size().width());
    qDebug("item height: %4.3f \n", item->boundingRect().size().height());
    item->setScaleFactor(scaleFactorX);
    item->scale(scaleFactorX,scaleFactorX);
</code>```

Where item is one of those ImagePixmapItems.

This works good the first time time - my image is larger than the viewport, and it scales down nicely to fit the window (at least width wise). However, if I hit the button again, the same value for scaleFactorX and item width and height come back.

Can you change the boundingRect of an image after it has been transformed? If not, what should I do?

答:
First of all, QGraphicsItem::boundingRect() returns a copy of the rect. Changing it has no effect on the actual item. To change an item's geometry, you need to override that function and return a different rect. And call prepareGeometryChange() when you actually change it.

Now, if all you want is to fit the item in QGraphicsView's viewport, use QGraphicsView::fitInView().

Changing the transformation of an item is very different from changing the transformation from the scene to the view. The former changes how the item is placed in the scene in relation to other items. The later keeps the relation and only affect how the scene is "reflected" onto the view.

It doesn't make much difference if you have a single item in the scene. Just keep in mind when you are dealing more complex scene that item transformation deals with the mathematical model of your world, not how to view it.

Edit:

I just reread your code. It turns out you are calculating the scale factor wrong. Here's a basic, non-tested code:

```<code>QRect itemSize = graphicsView->mapFromScene(item->sceneBoundingRect()).boundingRect().size();
QRect scaledSize =itemSize.scale(graphicsView->viewport().size(), Qt::KeepAspectRatio);
double ratio = qMin((double)scaledSize.width()/itemSize().width(), (double)scaledSize.height()/itemSize().height());
item->setTransform(QTransform::fromScale(ratio,ratio), true);
</code>```

The point is to use sceneBoundingRect instead of boundingRect since boundingRect is the item local bounds which is always the same regardless of item transform. And sceneBoundingRect is the bounds after all transformations are applied.

Title: Zoom QGraphicsItem to fit QGraphicsView

Body:
I am trying to create a QGraphicsView that will allow someone to scale the current QGraphicsItem to fit the size of the QGraphicsView window.

I have overridden QGraphicsItem to create a custom version, and I implemented some methods so it knows how much it has been scaled (which is always proportional to the original, so there is only one scale factor - the same for width and height).

So in the scaleFactor setter I have the following:

void ImagePixmapItem::setScaleFactor(float sf){
    scaleFactor = sf;
    this->boundingRect().setWidth(this->boundingRect().width()*scaleFactor);
    this->boundingRect().setHeight(this->boundingRect().height()*scaleFactor);

}

And in my main form, I have the following in a button:

   QRect portRect = ui->graphicsView->viewport()->rect();
    double scaleFactorX;
   if(portRect.width() <= (item->boundingRect().size().width()))
       scaleFactorX =portRect.width() /(item->boundingRect().size().width());
   else
       scaleFactorX = (item->boundingRect().size().width())/portRect.width();

    qDebug("Scalefactor: %4.3f \n", scaleFactorX);
    qDebug("item width: %4.3f \n", item->boundingRect().size().width());
    qDebug("item height: %4.3f \n", item->boundingRect().size().height());
    item->setScaleFactor(scaleFactorX);
    item->scale(scaleFactorX,scaleFactorX);

Where item is one of those ImagePixmapItems.

This works good the first time time - my image is larger than the viewport, and it scales down nicely to fit the window (at least width wise). However, if I hit the button again, the same value for scaleFactorX and item width and height come back.

Can you change the boundingRect of an image after it has been transformed? If not, what should I do?

Body:
First of all, QGraphicsItem::boundingRect() returns a copy of the rect. Changing it has no effect on the actual item. To change an item's geometry, you need to override that function and return a different rect. And call prepareGeometryChange() when you actually change it.

Now, if all you want is to fit the item in QGraphicsView's viewport, use QGraphicsView::fitInView().

Changing the transformation of an item is very different from changing the transformation from the scene to the view. The former changes how the item is placed in the scene in relation to other items. The later keeps the relation and only affect how the scene is "reflected" onto the view.

It doesn't make much difference if you have a single item in the scene. Just keep in mind when you are dealing more complex scene that item transformation deals with the mathematical model of your world, not how to view it.

Edit:

I just reread your code. It turns out you are calculating the scale factor wrong. Here's a basic, non-tested code:

QRect itemSize = graphicsView->mapFromScene(item->sceneBoundingRect()).boundingRect().size();
QRect scaledSize =itemSize.scale(graphicsView->viewport().size(), Qt::KeepAspectRatio);
double ratio = qMin((double)scaledSize.width()/itemSize().width(), (double)scaledSize.height()/itemSize().height());
item->setTransform(QTransform::fromScale(ratio,ratio), true);

The point is to use sceneBoundingRect instead of boundingRect since boundingRect is the item local bounds which is always the same regardless of item transform. And sceneBoundingRect is the bounds after all transformations are applied.


问:
Allow Spring to have multiple WebMvcConfigurer implementations in different jars
When using Spring Web, in this case for rest endpoints & using Spring Boot 2, I can configure interceptors for my app using by implementing the WebMvcConfigurer interface:

@Configuration
public class SpringWebConfig implements WebMvcConfigurer
{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor).addPathPatterns("/api/endpoint/**");
    }
}
```

I added this interceptor to most of my apps in an automatic fashion by doing the following:

Create a "common-jar", and put the above interface under package

com.company.api.

In every app, add the package com.company.api to
the api scan.

This common package also contains the Interceptor and utility classes to make this interceptor work, so in effect, adding this common-jar would automatically add he interceptor to all operations in the app, which is a similar concept as to what Spring itself does: adding dependencies changes the default configuration of Spring.

The problem I'm facing now is this approach cannot be extended to a second interceptor in a second jar, because I already used the WebMvcConfigurer implementation. and I cannot have two.

I was thinking about maybe using some kind of composite-configurer pattern where we loop over every configurer, collect all interceptors, and then add them once, but unfortunately Spring doesn't allow this. What are my options?

Currently, the approach I took is duplicating the WebMvcConfigurer interface in every app that requires it. I feel sad when something changes, and I have to change the same snippet of code in every single app.

答:
If I understand your problem correctly, you don't want to implement all the methods of WebMvcConfigurer  in every app. You just want to add relevant interceptors and be done with it.

My approach would be to create an AbstractWebMvcConfigurerImpl by implementing the WebMvcConfigurer in the Common module. Just leave the addInterceptors() abstract and implement other methods. You can then extend that abstract implementation in your every Spring Boot project and just override the addInterceptors() method as per your need.

Also, you can have as many implementations of WebMvcConfigurer as you want in a Spring project. So, if you need to define some common interceptors in the Common module, you can extend the AbstractWebMvcConfigurerImpl in the common module also.

Please note that all your implementations of AbstractWebMvcConfigurerImpl should be annotated with @Configuration

Body:
When using Spring Web, in this case for rest endpoints & using Spring Boot 2, I can configure interceptors for my app using by implementing the WebMvcConfigurer interface:

@Configuration
public class SpringWebConfig implements WebMvcConfigurer
{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor).addPathPatterns("/api/endpoint/**");
    }
}

I added this interceptor to most of my apps in an automatic fashion by doing the following:

Create a "common-jar", and put the above interface under package

com.company.api.

In every app, add the package com.company.api to
the api scan.

This common package also contains the Interceptor and utility classes to make this interceptor work, so in effect, adding this common-jar would automatically add he interceptor to all operations in the app, which is a similar concept as to what Spring itself does: adding dependencies changes the default configuration of Spring.

The problem I'm facing now is this approach cannot be extended to a second interceptor in a second jar, because I already used the WebMvcConfigurer implementation. and I cannot have two.

I was thinking about maybe using some kind of composite-configurer pattern where we loop over every configurer, collect all interceptors, and then add them once, but unfortunately Spring doesn't allow this. What are my options?

Currently, the approach I took is duplicating the WebMvcConfigurer interface in every app that requires it. I feel sad when something changes, and I have to change the same snippet of code in every single app.


问:
How to resize image in imagemagick with rails?
I have an image, the size of the image is 1920x1080, now I want to resize it to 1080x1920, but when I resize it, it returns to 1080x712

this is my code

```<code>require 'rubygems'
require 'mini_magick'
image = MiniMagick::Image.open("PathOfTheImage")
image.resize "1080x1920"
image.write "output.png"
</code>```

How can I do it?

答:
This is an ImageMagick syntax thing. It's preserving aspect ratio instead of respecting your height argument.

Add a bang to force the dimensions image.resize "1080x1920"

```<code>image.resize "1080x1920!"
</code>```

Body:
I have an image, the size of the image is 1920x1080, now I want to resize it to 1080x1920, but when I resize it, it returns to 1080x712

this is my code

require 'rubygems'
require 'mini_magick'
image = MiniMagick::Image.open("PathOfTheImage")
image.resize "1080x1920"
image.write "output.png"

How can I do it?

Body:
This is an ImageMagick syntax thing. It's preserving aspect ratio instead of respecting your height argument.

Add a bang to force the dimensions image.resize "1080x1920"

image.resize "1080x1920!"


问:
an element is not visually searchable in chrome inspection
I am building a web scraper selenium but the element I want to click is actually searched in chrome inspection layout but can't be seen visually(like when you hit ctrl+F and search for an element by typing it in, it shows up in the DOM structure collapsing...)
So I can't proceed since I should make a "clicking" on it with my Python.

http://bitly.kr/Nypl88
is the link and the element I would like to click with selenium has an id called "cns_Tab21". When you search for it, the result total is 1 but can't be seen in the DOM.

Thank you for reading this post and for your answer in advance.

答:
Your element is hidden inside an iframe.

To get to it you will need to switch to the iframe first:

```<code>driver.get("https://finance.naver.com/item/coinfo.nhn?code=255440");
WebElement iframe = driver.findElement(By.id("coinfo_cp"));
driver.switchTo().frame(iframe);
WebElement tabElement = driver.findElement(By.id("cns_Tab21"));
</code>```

*Edit*

Added a Python implementation

```<code>driver = webdriver.Chrome()
driver.get("https://finance.naver.com/item/coinfo.nhn?code=255440")
iframe = driver.find_element_by_id("coinfo_cp")
driver.switch_to.frame(iframe)
tabElement = driver.find_element_by_id("cns_Tab21")
</code>```

Body:
Your element is hidden inside an iframe.

To get to it you will need to switch to the iframe first:

driver.get("https://finance.naver.com/item/coinfo.nhn?code=255440");
WebElement iframe = driver.findElement(By.id("coinfo_cp"));
driver.switchTo().frame(iframe);
WebElement tabElement = driver.findElement(By.id("cns_Tab21"));

*Edit*

Added a Python implementation

driver = webdriver.Chrome()
driver.get("https://finance.naver.com/item/coinfo.nhn?code=255440")
iframe = driver.find_element_by_id("coinfo_cp")
driver.switch_to.frame(iframe)
tabElement = driver.find_element_by_id("cns_Tab21")


问:
How To Create Table Easily From A Join Result on Tables with Same Column/Field Names
I am trying to do a join on 2 tables that have the same schema:

```<code>SELECT * FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid
</code>```

This works ok, until I decide to modify the query to save it:

```<code>CREATE TABLE `tableName` SELECT * FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid
</code>```

This gives an error saying that there are duplicate columns.

I have a primary key in both tables.

I found a solution by aliasing each column from each table like this:

```<code>CREATE TABLE `tableName` SELECT tl1.id AS L_id1, tl1.filepath AS L_filepath1, tl1.urlid AS L_urlid1, tl1.fieldname AS L_fieldname1, tl1.fieldvalue AS L_fieldvalue1, tl2.id AS L_id2, tl2.filepath AS L_filepath2, tl2.urlid AS L_urlid2, tl2.fieldname AS L_fieldname2, tl2.fieldvalue AS L_fieldvalue2 FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid
</code>```

However, this is tedious. What if there were 100+ columns in each table? Is there a way to make this work without having to manually aliasing each column name? I am looking for something that will make MySQL create a table with column names of the format "X.Y" where X is the original table name and Y is the original field name, but any other solutions would do as well.

P.S.: If it's not clear, when I used "*", I needed columns from both tables, not just one. They are two different tables with different data but with the same column names. (I can't change the names, by the way.)

答:
First, using mysql workbench.  you need to create the following view, by clicking on the desired schema, then right-clicking on view.

It should look something like this:

```<code>CREATE VIEW `schema`.`someView` (
    SELECT t1.*
    FROM `tl1` as t1
    JOIN `tl2` as t2
    ON (t1.urlid = t2.urlid)
)
</code>```

Now save it, then reopen it in the "views" tab and you should see this:

```<code>CREATE VIEW `schema`.`someView` (
    SELECT
    t1.col1,
    t1.col2,
    t1.col3,
    ...
    FROM `tl1` as t1
    JOIN `tl2` as t2
    ON (t1.urlid = t2.urlid)
)
</code>```

Now you can an alias to the duplicate columns, then add a t2.* to add the rest of the columns

```<code>CREATE VIEW `schema`.`someView` (
    SELECT
    t1.id as tl1_id,
    ...
    t2.*
    FROM `tl1` as t1
    JOIN `tl2` as t2
    ON (t1.urlid = t2.urlid)
)
</code>```

This is the fastest way I know to do this.  Hope it helps.

Body:
I am trying to do a join on 2 tables that have the same schema:

SELECT * FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid

This works ok, until I decide to modify the query to save it:

CREATE TABLE `tableName` SELECT * FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid

This gives an error saying that there are duplicate columns.

I have a primary key in both tables.

I found a solution by aliasing each column from each table like this:

CREATE TABLE `tableName` SELECT tl1.id AS L_id1, tl1.filepath AS L_filepath1, tl1.urlid AS L_urlid1, tl1.fieldname AS L_fieldname1, tl1.fieldvalue AS L_fieldvalue1, tl2.id AS L_id2, tl2.filepath AS L_filepath2, tl2.urlid AS L_urlid2, tl2.fieldname AS L_fieldname2, tl2.fieldvalue AS L_fieldvalue2 FROM `tl1` INNER JOIN `tl2` ON tl1.urlid = tl2.urlid

However, this is tedious. What if there were 100+ columns in each table? Is there a way to make this work without having to manually aliasing each column name? I am looking for something that will make MySQL create a table with column names of the format "X.Y" where X is the original table name and Y is the original field name, but any other solutions would do as well.

P.S.: If it's not clear, when I used "*", I needed columns from both tables, not just one. They are two different tables with different data but with the same column names. (I can't change the names, by the way.)

Body:
First, using mysql workbench.  you need to create the following view, by clicking on the desired schema, then right-clicking on view.

It should look something like this:

CREATE VIEW `schema`.`someView` (
    SELECT t1.*
    FROM `tl1` as t1
    JOIN `tl2` as t2
    ON (t1.urlid = t2.urlid)
)

Now save it, then reopen it in the "views" tab and you should see this:

CREATE VIEW `schema`.`someView` (
    SELECT
    t1.col1,
    t1.col2,
    t1.col3,
    ...
    FROM `tl1` as t1
    JOIN `tl2` as t2
    ON (t1.urlid = t2.urlid)
)

Now you can an alias to the duplicate columns, then add a t2.* to add the rest of the columns

CREATE VIEW `schema`.`someView` (
    SELECT
    t1.id as tl1_id,
    ...
    t2.*
    FROM `tl1` as t1
    JOIN `tl2` as t2
    ON (t1.urlid = t2.urlid)
)

This is the fastest way I know to do this.  Hope it helps.