问:
TypeScript Array of Tuples
So I have this simple example:

```<code>type SomeTuple = [string, number];

const foo = (options: SomeTuple[]) => console.log(options);

const options = [
    ['first', 1],
    ['second', 2],
];

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

foo(options); // Error

foo(otherOptions); // OK
</code>```

Basically there no more much to tell, I just can't figure out why TS keeps showing me error in case where I'am not providing type for options explicitly;

Playground

Thank you for your time!

答:
It looks like Typescript thinks that options is of type (string | number)[] so if you change your type definition like below, you should not get a compile error for options or otherOptions.  Hope this helps.</p>

```<code>type SomeTuple = (string | number)[];
</code>```

Title: TypeScript Array of Tuples

Body:
So I have this simple example:

type SomeTuple = [string, number];

const foo = (options: SomeTuple[]) => console.log(options);

const options = [
    ['first', 1],
    ['second', 2],
];

const otherOptions: SomeTuple[] = [
    ['first', 1],
    ['second', 2],
];

foo(options); // Error

foo(otherOptions); // OK

Basically there no more much to tell, I just can't figure out why TS keeps showing me error in case where I'am not providing type for options explicitly;

Playground

Thank you for your time!

Body:
It looks like Typescript thinks that options is of type (string | number)[] so if you change your type definition like below, you should not get a compile error for options or otherOptions.  Hope this helps.

type SomeTuple = (string | number)[];


来源: stackexchange

问:
Implement Tree with checkboxes and drag drop
Im trying to implement Tree view in Vue with checkboxes and also with drag & drop. But I do not know where to start.

I implemented checkboxes but I do not know how to add support when parent is selected to select all children, and also when select all children to select parent ?

Also Im having issue with Drag and Drop, I tried ussing vue-draggable but I do not know how to implement it

Im trying to implement, something like this:

https://ej2.syncfusion.com/vue/documentation/treeview/check-box/

Here is my sandbox, what I have managed to implement:

https://codesandbox.io/s/immutable-cookies-8lxxf

答: Check this example. They have implemented everything you need to start with. https://vuejsexamples.com/tree-and-multi-select-component-based-on-vue-js-2/</p>

ContentLicense: CC BY-SA 4.0


问:
how to set certain bucket in Firebase Storage using admin SDK?
if using default bucket, I can use code like this:

```<code>const storage = admin.storage()
const defaultBucket = storage.bucket()
const thumbnailFile = defaultBucket.file(`eventThumbnail/${creatorID}/${eventID}`)
</code>```

but now I have set a new bucket with certain name ("gs://newBucketNameHere"), so what is the code to make a reference to a new storage bucket ?

答:
You have to pass the name of the bucket to the bucket() method, but without the gs:// "protocol" part.

```<code>const newBucket = storage.bucket("newBucketNameHere")
const thumbnailFile = newBucket.file(`eventThumbnail/${creatorID}/${eventID}`)
</code>```

Body:
if using default bucket, I can use code like this:

const storage = admin.storage()
const defaultBucket = storage.bucket()
const thumbnailFile = defaultBucket.file(`eventThumbnail/${creatorID}/${eventID}`)

but now I have set a new bucket with certain name ("gs://newBucketNameHere"), so what is the code to make a reference to a new storage bucket ?

Body:
You have to pass the name of the bucket to the bucket() method, but without the gs:// "protocol" part.

const newBucket = storage.bucket("newBucketNameHere")
const thumbnailFile = newBucket.file(`eventThumbnail/${creatorID}/${eventID}`)


问:
Reading Google spread sheet without using any credential in Java
I am working with the google Spreadsheet and wanted to read all the data from it without using any credential.json file.

What I actually want is, If I have been provided a URL for spreadsheets then I should be able to read the data without using any client secrets.
How can I do it?

答:
You need to authenticate yourself yo use the API even if the sheet is public.

You could try just to make an HTTP request to actually download the information, take a look at this Gist to see all the formats you can use.

For exemple download/read the file as CSV:

```<code>curl 'https://docs.google.com/spreadsheets/d/1pObOjcxHEZHDb0DOA8mxcO3HY_koVcTNdmzjjE7Sj9w/export?format=csv'
</code>```

Body:
You need to authenticate yourself yo use the API even if the sheet is public.

You could try just to make an HTTP request to actually download the information, take a look at this Gist to see all the formats you can use.

For exemple download/read the file as CSV:

curl 'https://docs.google.com/spreadsheets/d/1pObOjcxHEZHDb0DOA8mxcO3HY_koVcTNdmzjjE7Sj9w/export?format=csv'


问:
PyCUDA/CUDA: Causes of non-deterministic launch failures?
Anyone following CUDA will probably have seen a few of my queries regarding a project I'm involved in, but for those who haven't I'll summarize. (Sorry for the long question in advance)

Three Kernels, One Generates a data set based on some input variables (deals with bit-combinations so can grow exponentially), another solves these generated linear systems, and another reduction kernel to get the final result out. These three kernels are ran over and over again as part of an optimisation algorithm for a particular system.

On my dev machine (Geforce 9800GT, running under CUDA 4.0) this works  perfectly, all the time, no matter what I throw at it (up to a computational limit based on the stated exponential nature), but on a test machine (4xTesla S1070's, only one used, under CUDA 3.1) the exact same code (Python base, PyCUDA interface to CUDA kernels), produces the exact results for 'small' cases, but in mid-range cases, the solving stage fails on random iterations.

Previous problems I've had with this code have been to do with the numeric instability of the problem, and have been deterministic in nature (i.e fails at exactly the same stage every time), but this one is frankly pissing me off, as it will fail whenever it wants to.

As such, I don't have a reliable way to breaking the CUDA code out from the Python framework and doing proper debugging, and PyCUDA's debugger support is questionable to say the least.

I've checked the usual things like pre-kernel-invocation checking of free memory on the device, and occupation calculations say that the grid and block allocations are fine. I'm not doing any crazy 4.0 specific stuff, I'm freeing everything I allocate on the device at each iteration and I've fixed all the data types as being floats.

TL;DR, Has anyone come across any gotchas regarding CUDA 3.1 that I haven't seen in the release notes, or any issues with PyCUDA's autoinit memory management environment that would cause intermittent launch failures on repeated invocations?

答: You can use nVidia CUDA Profiler and see what gets executed before the failure.</p>

ContentLicense: CC BY-SA 3.0


问:
Vue.js 'openNav' is defined but never used / 'closeNav' is defined but never used
When starting the website it shows the errors mentioned in the title.

Here's the HTML part:

```<code><span style="font-size:30px;cursor:pointer;" onclick="openNav()">☰</span>

    <div id="mySidenav" class="sidenav">
      <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
      <a href="#">{{name1}}</a>
      <a href="#">{{name2}}</a>
      <a href="#">{{name3}}</a>
      <a href="#">{{name4}}</a>
      </div>
</code>```

And here is the js part:

```<code>//Vue App
  // eslint-disable-next-line
  var app = new Vue({
    el: '#app',
    data: {
      name1: 'name 1',
      name2: 'name 2',
      name3: 'name 3',
      name4: 'name 4'
    }
  })
  export default {
    name: 'HelloWorld',
    props: {
      msg: String
    }
  }

  //Navbar
  function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
  }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
  }
</code>```

As you can see both, closeNav and openNav are used in the HTML code.

答:
in vue you should define your functions in methods like this:

```<code>export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods: {
    openNav() {
      document.getElementById('mySidenav').style.width = '250px'
    },
    closeNav() {
      document.getElementById('mySidenav').style.width = '0'
    }
  }
}
</code>```

then you can call them with v-on:click in your code like:

```<code><span v-on:click="openNav()" style="font-size:30px;cursor:pointer;"
      >☰</span
    >

    <div id="mySidenav" class="sidenav">
      <a href="javascript:void(0)" class="closebtn" onclick="closeNav()"
        >×</a
      >
      <a href="#">{{ name1 }}</a>
      <a href="#">{{ name2 }}</a>
      <a href="#">{{ name3 }}</a>
      <a href="#">{{ name4 }}</a>
    </div>
</code>```

PS : alternatively you can use @click instead of `v-on:click'

Body:
When starting the website it shows the errors mentioned in the title.

Here's the HTML part:

☰

      ×
      {{name1}}
      {{name2}}
      {{name3}}
      {{name4}}

And here is the js part:

//Vue App
  // eslint-disable-next-line
  var app = new Vue({
    el: '#app',
    data: {
      name1: 'name 1',
      name2: 'name 2',
      name3: 'name 3',
      name4: 'name 4'
    }
  })
  export default {
    name: 'HelloWorld',
    props: {
      msg: String
    }
  }

  //Navbar
  function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
  }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
  }

As you can see both, closeNav and openNav are used in the HTML code.

Body:
in vue you should define your functions in methods like this:

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods: {
    openNav() {
      document.getElementById('mySidenav').style.width = '250px'
    },
    closeNav() {
      document.getElementById('mySidenav').style.width = '0'
    }
  }
}

then you can call them with v-on:click in your code like:

<span v-on:click="openNav()" style="font-size:30px;cursor:pointer;"
      >&#9776;</span
    >

    <div id="mySidenav" class="sidenav">
      <a href="javascript:void(0)" class="closebtn" onclick="closeNav()"
        >&times;</a
      >
      <a href="#">{{ name1 }}</a>
      <a href="#">{{ name2 }}</a>
      <a href="#">{{ name3 }}</a>
      <a href="#">{{ name4 }}</a>
    </div>

PS : alternatively you can use @click instead of `v-on:click'


问:
Check if array contains elements and if some elements are same then check for corresponding value in another array
```<code>var number = ['123', '123', '987', '567','675','675']
var city = ['Mumbai', 'Pune', 'Delhi', 'Bangalore','london','New York']
</code>```

In the above array, I want to check if a number is the same for different cities. like 123, this number is the same for Mumbai and Pune then it should show an error. Javascript with max ES6 version is preferred.

答:
The function will return an object whose key is a repeating item and the value is the indices of these repeats. Using them you can find and return city names in error provided that the number arrays in the first array correspond to the names of cities in the second

```<code>function checkReplicate (array) {
    return array.reduce((acc, cur, i) => {

        let hash = {},
            filtred = array.filter(v1 => v1 === cur);

         if (filtred.length > 1) {
             acc[cur] ? acc[cur].push(i) : acc[cur] = [i];

         }
          return acc;

    }, {});
}
</code>```

If an empty object returns, no matches were found.

However, such a data structure is not optimal. Given your mention of ExtJS, it would be more convenient to describe your data using the model, add to the store with memory proxy

Body:
var number = ['123', '123', '987', '567','675','675']
var city = ['Mumbai', 'Pune', 'Delhi', 'Bangalore','london','New York']

In the above array, I want to check if a number is the same for different cities. like 123, this number is the same for Mumbai and Pune then it should show an error. Javascript with max ES6 version is preferred.

Body:
The function will return an object whose key is a repeating item and the value is the indices of these repeats. Using them you can find and return city names in error provided that the number arrays in the first array correspond to the names of cities in the second

function checkReplicate (array) {
    return array.reduce((acc, cur, i) => {

        let hash = {},
            filtred = array.filter(v1 => v1 === cur);

         if (filtred.length > 1) {
             acc[cur] ? acc[cur].push(i) : acc[cur] = [i];

         }
          return acc;

    }, {});
}

If an empty object returns, no matches were found.

However, such a data structure is not optimal. Given your mention of ExtJS, it would be more convenient to describe your data using the model, add to the store with memory proxy


问:
Replace multiple OR operators with a single IN or ANY operator
I would like to query a list of cities that end in vowels and I would like each city in the list to be distinct. The code noted below works fine but I would like to achieve the same thing using the IN or ANY operators.I have attached a picture of the description of the table I'm working with. Thank you!

```<code>SELECT DISTINCT City FROM Station
WHERE City LIKE '%a'
OR City LIKE '%e'
OR City LIKE '%i'
OR City LIKE '%o'
OR City LIKE '%u';
</code>```

Table description

答:
If you want to use in, you can:

```<code>where substr(city, -1) in ('a', 'e', 'i', 'o', 'u')
</code>```

You can use lower() if you need to handle upper-case as well.

Body:
I would like to query a list of cities that end in vowels and I would like each city in the list to be distinct. The code noted below works fine but I would like to achieve the same thing using the IN or ANY operators.I have attached a picture of the description of the table I'm working with. Thank you!

SELECT DISTINCT City FROM Station
WHERE City LIKE '%a'
OR City LIKE '%e'
OR City LIKE '%i'
OR City LIKE '%o'
OR City LIKE '%u';

Table description

Body:
If you want to use in, you can:

where substr(city, -1) in ('a', 'e', 'i', 'o', 'u')

You can use lower() if you need to handle upper-case as well.


问:
How to join two streaming datasets when one dataset involves aggregation
I am getting below error in below code snippet -

Exception in thread "main" org.apache.spark.sql.AnalysisException:
  Append output mode not supported when there are streaming aggregations
  on streaming DataFrames/DataSets without watermark;;

Below is my input schema

```<code>val schema = new StructType()
.add("product",StringType)
.add("org",StringType)
.add("quantity", IntegerType)
.add("booked_at",TimestampType)
</code>```

Creating streaming source dataset

```<code>val payload_df = spark
.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "localhost:9092")
.option("subscribe", "test1")
.option("startingOffsets", "latest")
.load()
.selectExpr("CAST(value AS STRING) as payload")
.select(from_json(col("payload"), schema).as("data"))
.select("data.*")
</code>```

Creating another streaming dataframe where aggregation is done and then joining it with original source dataframe to filter out records

```<code>payload_df.createOrReplaceTempView("orders")
    val stage_df = spark.sql("select org, product, max(booked_at) as booked_at from orders group by 1,2")
  stage_df.createOrReplaceTempView("stage")

  val total_qty = spark.sql(
    "select o.* from orders o join stage s on o.org = s.org and o.product = s.product and o.booked_at > s.booked_at ")
</code>```

Finally, I was trying to display results on console with Append output mode. I am not able to figure out where I need to add watermark or how to resolve this. My objective is to filter out only those events in every trigger which have higher timestamp then the maximum timestamp received in any of the earlier triggers

```<code>total_qty
    .writeStream
    .format("console")
    .outputMode("append")
    .start()
    .awaitTermination()
</code>```

答:
With spark structured streaming you can make aggregation directly on stream only with watermark. If you have a column with the timestamp of the event you can do it like this:

```<code>val payload_df = spark
.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "localhost:9092")
.option("subscribe", "test1")
.option("startingOffsets", "latest")
.load()
.selectExpr("CAST(value AS STRING) as payload")
.select(from_json(col("payload"), schema).as("data"))
.select("data.*")
.withWatermark("event_time", "1 minutes")
</code>```

On queries with aggregation you have 3 types of outputs:

Append mode uses watermark to drop old aggregation state. But the output of a windowed aggregation is delayed the late threshold
specified in withWatermark() as by the modes semantics, rows can be
added to the Result Table only once after they are finalized (i.e.
after watermark is crossed). See the Late Data section for more
details.

Update mode uses watermark to drop old aggregation state.

Complete mode does not drop old aggregation state since by definition this mode preserves all data in the Result Table.

Edit later:
You have to add window on your groupBy method.
val aggFg = payload_df.groupBy(window($"event_time", "1 minute"), $"org", $"product")
.agg(max(booked_at).as("booked_at"))

Body:
I am getting below error in below code snippet -

Exception in thread "main" org.apache.spark.sql.AnalysisException:
  Append output mode not supported when there are streaming aggregations
  on streaming DataFrames/DataSets without watermark;;

Below is my input schema

val schema = new StructType()
.add("product",StringType)
.add("org",StringType)
.add("quantity", IntegerType)
.add("booked_at",TimestampType)

Creating streaming source dataset

val payload_df = spark
.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "localhost:9092")
.option("subscribe", "test1")
.option("startingOffsets", "latest")
.load()
.selectExpr("CAST(value AS STRING) as payload")
.select(from_json(col("payload"), schema).as("data"))
.select("data.*")

Creating another streaming dataframe where aggregation is done and then joining it with original source dataframe to filter out records

payload_df.createOrReplaceTempView("orders")
    val stage_df = spark.sql("select org, product, max(booked_at) as booked_at from orders group by 1,2")
  stage_df.createOrReplaceTempView("stage")

  val total_qty = spark.sql(
    "select o.* from orders o join stage s on o.org = s.org and o.product = s.product and o.booked_at > s.booked_at ")

Finally, I was trying to display results on console with Append output mode. I am not able to figure out where I need to add watermark or how to resolve this. My objective is to filter out only those events in every trigger which have higher timestamp then the maximum timestamp received in any of the earlier triggers

total_qty
    .writeStream
    .format("console")
    .outputMode("append")
    .start()
    .awaitTermination()

Body:
With spark structured streaming you can make aggregation directly on stream only with watermark. If you have a column with the timestamp of the event you can do it like this:

val payload_df = spark
.readStream
.format("kafka")
.option("kafka.bootstrap.servers", "localhost:9092")
.option("subscribe", "test1")
.option("startingOffsets", "latest")
.load()
.selectExpr("CAST(value AS STRING) as payload")
.select(from_json(col("payload"), schema).as("data"))
.select("data.*")
.withWatermark("event_time", "1 minutes")

On queries with aggregation you have 3 types of outputs:

Append mode uses watermark to drop old aggregation state. But the output of a windowed aggregation is delayed the late threshold
specified in withWatermark() as by the modes semantics, rows can be
added to the Result Table only once after they are finalized (i.e.
after watermark is crossed). See the Late Data section for more
details.

Update mode uses watermark to drop old aggregation state.

Complete mode does not drop old aggregation state since by definition this mode preserves all data in the Result Table.

Edit later:
You have to add window on your groupBy method.
val aggFg = payload_df.groupBy(window($"event_time", "1 minute"), $"org", $"product")
.agg(max(booked_at).as("booked_at"))


问:
Gitlab - "letsencrypt['enable'] = true" produce error in reconfigure
I installed Gitlab 12.7.6 on CentOS7

I follow the instruction here for configure the SSL
it said to

letsencrypt['enable'] = true                      # GitLab 10.5 and 10.6 require this option

When I changed it to 'true' and run 'gitlab-ctl reconfigure'  I get the error:

There was an error running gitlab-ctl reconfigure:

letsencrypt_certificate[gitlab.mydomain]
  (letsencrypt::http_authorization line 5) had an error: RuntimeError:
  acme_certificate[staging]
  (/opt/gitlab/embedded/cookbooks/cache/cookbooks/letsencrypt/resources/certificate.rb
  line 25) had an error: RuntimeError: ruby_block[create certificate for
  gitlab.mydomain]
  (/opt/gitlab/embedded/cookbooks/cache/cookbooks/acme/resources/certificate.rb
  line 108) had an error: RuntimeError: [gitlab.mydomain] Validation
  failed, unable to request certificate

Running handlers complete Chef Client failed. 18 resources updated in
  01 minutes 08 seconds

When it set as 'false' I get no error.

Thanks.

答: To get SSL support with letsencrypt your machine should have a Fully Qualified Domain Name. From the error it looks like your machine is called gitlab.mydomain, so either you are running it in LAN only, in which case you should disable letsencrypt, or you have not set correctly its domain name in gitlab configuration.


问:
Google C2DM servers
As far as I know, Google C2DM servers gives notifications from third party server. Is it possible to make Google C2DM servers your host for data. Can one send data from an android application to Google C2DM servers for other users of the same application to receive notification of the data</p>

答: Yes, It is possible you have to first OAuthenticate your self with Google using registration key, what your application have got from the C2DM server side. For more information see Lars Vogel Tutorial where you can see how we can set up our local server code in an application to send messages. For first register your application on Google C2DM server using google registration link here.</p>

Title: Google C2DM servers


问:
How to pass data via post request to a field whose schema is an array of objects in WordPress REST API
So just starting out with WordPress REST API

I am creating my own REST API Controller (Meaning having my own class extending \WP_REST_Controller class)

I am exposing API routes for a Custom Post Type

The code is very long so I won't paste all code here, just the important ones

So everything so far is ok, I am able to read data from the routes and create data through the routes

One issue I have is I am having trouble trying to send data through POST request for fields whose schema is array of object

So given this schema

```<code>    $schema = array(
        '$schema'    => 'http://json-schema.org/draft-04/schema#',
        'title'      => $this->post_type,
        'type'       => 'object',
        'properties' => array(
            'id'          => array(
                'description' => __( 'Unique identifier for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'integer',
                'context'     => array( 'view', 'edit', 'embed' ),
                'readonly'    => true,
            ),
            'title'             => array(
                'description' => __( 'The title for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'string',
                'context'     => array( 'view', 'edit', 'embed' ),
            ),
            'description' => array(
                'description' => __( 'The description for the survey cpt object', 'wp-plugin-boilerplate' ),
                'type'        => 'string',
                'context'     => array( 'view', 'edit', 'embed' )
            ),
            'status'      => array(
                'description' => __( 'A named status for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'string',
                'enum'        => array_keys( get_post_stati( array( 'internal' => false ) ) ),
                'context'     => array( 'view', 'edit' ),
            ),
            'type'        => array(
                'description' => __( 'Type of Post for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'string',
                'context'     => array( 'view', 'edit', 'embed' ),
                'readonly'    => true,
            ),
            'fields'      => array(
                'description' => __( 'Set of fields for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'array',
                'context'     => array( 'view', 'edit', 'embed' ),
                'items'       => array(
                    'type'       => 'object',
                    'properties' => array(
                        'field_type'  => array( 'type' => 'string' ),
                        'description' => array( 'type' => 'string' ),
                        'order'       => array( 'type' => 'integer' )
                    )
                )
            )
        )
    );
</code>```

So the fields field is an array of objects,

Just ignore authentication to avoid further complicating things for the mean time, I just allowed public creation of cpt items via REST API atm.

When I send a POST request via postman like this

Note: The operation above is successful if I remove/not pass the fields field.

So is there something wrong to the way I define the schema? or something wrong on sending the data?

Thanks in advance.

Edit:

Also tried this

Edit:

Confirm this is an issue only for PostMan, sending POST request via AXIOS works ok

答:
Instead of the form-data option, Can you try with raw option with below code:

```<code>{
    "title": "Test Survey 5",
    "description": "lalala"
    "status": "publish",
    "fields": {
        "field_name1": "value1",
        "field_name2": "value2"
    }
}
</code>```

Use your original field_name and value for "field_name1" and "field_name2".

Let me know if any query.

Thanks

Jenil

Body:
So just starting out with WordPress REST API

I am creating my own REST API Controller (Meaning having my own class extending \WP_REST_Controller class)

I am exposing API routes for a Custom Post Type

The code is very long so I won't paste all code here, just the important ones

So everything so far is ok, I am able to read data from the routes and create data through the routes

One issue I have is I am having trouble trying to send data through POST request for fields whose schema is array of object

So given this schema

    $schema = array(
        '$schema'    => 'http://json-schema.org/draft-04/schema#',
        'title'      => $this->post_type,
        'type'       => 'object',
        'properties' => array(
            'id'          => array(
                'description' => __( 'Unique identifier for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'integer',
                'context'     => array( 'view', 'edit', 'embed' ),
                'readonly'    => true,
            ),
            'title'             => array(
                'description' => __( 'The title for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'string',
                'context'     => array( 'view', 'edit', 'embed' ),
            ),
            'description' => array(
                'description' => __( 'The description for the survey cpt object', 'wp-plugin-boilerplate' ),
                'type'        => 'string',
                'context'     => array( 'view', 'edit', 'embed' )
            ),
            'status'      => array(
                'description' => __( 'A named status for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'string',
                'enum'        => array_keys( get_post_stati( array( 'internal' => false ) ) ),
                'context'     => array( 'view', 'edit' ),
            ),
            'type'        => array(
                'description' => __( 'Type of Post for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'string',
                'context'     => array( 'view', 'edit', 'embed' ),
                'readonly'    => true,
            ),
            'fields'      => array(
                'description' => __( 'Set of fields for the survey cpt object.', 'wp-plugin-boilerplate' ),
                'type'        => 'array',
                'context'     => array( 'view', 'edit', 'embed' ),
                'items'       => array(
                    'type'       => 'object',
                    'properties' => array(
                        'field_type'  => array( 'type' => 'string' ),
                        'description' => array( 'type' => 'string' ),
                        'order'       => array( 'type' => 'integer' )
                    )
                )
            )
        )
    );

So the fields field is an array of objects,

Just ignore authentication to avoid further complicating things for the mean time, I just allowed public creation of cpt items via REST API atm.

When I send a POST request via postman like this

Note: The operation above is successful if I remove/not pass the fields field.

So is there something wrong to the way I define the schema? or something wrong on sending the data?

Thanks in advance.

Edit:

Also tried this

Edit:

Confirm this is an issue only for PostMan, sending POST request via AXIOS works ok

Body:
Instead of the form-data option, Can you try with raw option with below code:

{
    "title": "Test Survey 5",
    "description": "lalala"
    "status": "publish",
    "fields": {
        "field_name1": "value1",
        "field_name2": "value2"
    }
}

Use your original field_name and value for "field_name1" and "field_name2".

Let me know if any query.

Thanks

Jenil


问:
How to get a global state of the locks in Linux kernel?
I'm writing some code for the Linux kernel and I noticed the interrupts are disabled when I need them to be enabled so that a process can handle a  signal. It would be fantastic if I could just obtain a list of all the locks currently being hold in the system, as my suspicion is that a lock somewhere has disabled interruptions... This is, assuming that it was a lock that disabled the interruptions. If not, it would also be nice to know how did so (or where). Does the Linux kernel keep any record of this?

答:
Yes, the kernel definitely has the ability to keep track of currently held locks, but that's costly and only done for debugging purposes. You should configure and compile your kernel with debugging enabled (specifically CONFIG_LOCKDEP, which also depends on other config options).

Once that is done, in struct task_struct there are various fields such as lockdep_depth (number of currently held locks) and held_locks (array of struct held_lock representing currently held locks) that could be useful for you. You could check those fields for the current task when your module is running to find out what is going on.

Take a look at the two private functions lockdep_print_held_locks() and print_lock() from kernel/locking/lockdep.c to see how to extract useful information from those struct held_lock. You could also use the kgdb kernel debugger in order to look specifically at what is happening when your kernel code runs.


问:
App Center shows no build variants for React Native Android
I am trying to set up a build for a React Native app on App Center.
I have linked the app to the Azure Devops Repository, and selected the branch and attempted to create a build.

However, when I try to create the build, it finds the package.json but does not find any build variants:

I have confirmed that it is finding the package.json for the app (I remove it and it complains).
I know that the build variants come from the build types in the build.gradle, which has a release variant in it.

I've googled the heck out of this and burned two evenings on it.
I have another project that builds just fine, and I cannot see the difference between them.

Why is AppCenter not able to pick up the build variants? How do I configure them?

答:
Just to close this question, the issue is a limitation currently on Azure DevOps.

As reported by MS and the maximum depth of the package.json is actually only two levels deep, not 4 levels as described in their documentation.


问:
Encoding.GetEncoding ucs 2 little endian
I'm trying to find a string or (not so ideally) int representation of UCS-2 little endian to input into Encoding.GetEncoding().

I am looking for this information because I'm using StreamReader to read a content of a file and I want to use Encoding.GetEncoding to construct it.

The reason for that is I'm reading several different files with variable encodings and I need to be able to specify in configuration which encoding to use for what file.

答:
UCS-2 can be considered a subset of UTF-16, and thus any UTF-16 capable decoder should also be able to handle UCS-2; the difference is that UCS-2 doesn't cover the entire range of unicode, and thus there are some additional values that can be expressed in UTF-16 but not in UCS-2. We just shouldn't expect to see those values here, if the file was written by an encoder that only knows UCS-2.

This is pretty much the same as saying that you can use a UTF-8 decoder to read data that was written in pure ASCII (where by "pure" here, I mean 7-bit ASCII, not the extended code-pages that use the 8th bit).

As such, any of:

Encoding direct = Encoding.Unicode;
Encoding byCode = Encoding.GetEncoding(1200);
Encoding byName = Encoding.GetEncoding("Unicode");
```

should work fine here.

Body:
UCS-2 can be considered a subset of UTF-16, and thus any UTF-16 capable decoder should also be able to handle UCS-2; the difference is that UCS-2 doesn't cover the entire range of unicode, and thus there are some additional values that can be expressed in UTF-16 but not in UCS-2. We just shouldn't expect to see those values here, if the file was written by an encoder that only knows UCS-2.

This is pretty much the same as saying that you can use a UTF-8 decoder to read data that was written in pure ASCII (where by "pure" here, I mean 7-bit ASCII, not the extended code-pages that use the 8th bit).

As such, any of:

Encoding direct = Encoding.Unicode;
Encoding byCode = Encoding.GetEncoding(1200);
Encoding byName = Encoding.GetEncoding("Unicode");

should work fine here.


问:
SQL Server: Why SELECT * INTO is faster than SELECT * (network excluded)
Why would Query2 dramatically outperform Query1?

Query1:

```<code>SELECT * FROM [SomeComplexView];
</code>```

Takes 4 minutes, does not use parallelism in query plan

Query2:

```<code>SELECT * INTO #t1 FROM [SomeComplexView];
SELECT * FROM #t1;
</code>```

Takes 15 seconds, uses parallelism. I guess the answer should be quite simple and generic, so I omit the complexities of the view.

答:
http://dataeducation.com/next-level-parallel-plan-forcing-an-alternative-to-8649/

When the query optimizer decides whether or not to select a parallel
  plan, it first comes up with a serial plan cost, then compares it to
  the parallel plan cost. If the parallel plan cost is lower, that’s the
  one that gets used. This parallel plan cost is based on the serial
  cost, but with a few key modifications:...

```<code>--estimated plans
--serial cost:399
--parallel cost:204 <---!
select a.*
into #abc
from master.dbo.spt_values as a
cross join master.dbo.spt_values as b
--option(maxdop 1)
--option (maxdop 2)

--serial cost: 28 <---!
--parallelx2 cost:41
--parallelx4 cost:20
--parallelx8 cost:10
select a.*
from master.dbo.spt_values as a
cross join master.dbo.spt_values as b
--option (maxdop 1)
--option (querytraceon 8649, maxdop 2)
</code>```

Body:
Why would Query2 dramatically outperform Query1?

Query1:

SELECT * FROM [SomeComplexView];

Takes 4 minutes, does not use parallelism in query plan

Query2:

SELECT * INTO #t1 FROM [SomeComplexView];
SELECT * FROM #t1;

Takes 15 seconds, uses parallelism. I guess the answer should be quite simple and generic, so I omit the complexities of the view.

Body:
http://dataeducation.com/next-level-parallel-plan-forcing-an-alternative-to-8649/

When the query optimizer decides whether or not to select a parallel
  plan, it first comes up with a serial plan cost, then compares it to
  the parallel plan cost. If the parallel plan cost is lower, that’s the
  one that gets used. This parallel plan cost is based on the serial
  cost, but with a few key modifications:...

--estimated plans
--serial cost:399
--parallel cost:204 <---!
select a.*
into #abc
from master.dbo.spt_values as a
cross join master.dbo.spt_values as b
--option(maxdop 1)
--option (maxdop 2)

--serial cost: 28 <---!
--parallelx2 cost:41
--parallelx4 cost:20
--parallelx8 cost:10
select a.*
from master.dbo.spt_values as a
cross join master.dbo.spt_values as b
--option (maxdop 1)
--option (querytraceon 8649, maxdop 2)


问:
Error in Moving sql database files
I want to copy my database mdf and ldf files programmatically and also change their names.
I tried File.Move() and "Alter database mydb modify file ..." and "use master exec sp_detach_db mydb" but i recieve this error "user doesnt have permission to do this action" or other errors like this.
note that i am an administrator user.
please help me</p>

答:
It would be easier if you do this as an SSIS package. If you're using SSIS 2005 there is a transfer database task that will allow you to do what you're after. If you're using SSIS 2008 then i believe they have renamed this task to Copy Database Task.

Either way it's quite straightforward to sort out.

Thanks,

Simon

Title: Error in Moving sql database files


问:
Getting list of Mac text-to-speech voices programmatically?
The mac command say can specify the voice used with the -v flag.

```<code>say -v Alex "compile completed, put your swords down."
</code>```

The available voices can be seen in System Preferences/Speech/Text to Speech.  How can I get this list programmatically?

答:
You can use the following to sample all the available voices:</p>

```<code>say -v '?' | awk '{$2=$3=""; printf "-v %s", $1; $1=""; print " \"" $0 "\""}'| xargs -L1 say
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The mac command say can specify the voice used with the -v flag.

say -v Alex "compile completed, put your swords down."

The available voices can be seen in System Preferences/Speech/Text to Speech.  How can I get this list programmatically?

Body:
You can use the following to sample all the available voices:

say -v '?' | awk '{$2=$3=""; printf "-v %s", $1; $1=""; print " \"" $0 "\""}'| xargs -L1 say


问:
Change size from woocommerce PayPal checkout button in cart
I use the WooCommerce PayPal Checkout Gateway Plugin.
In the Backend of wordpress I set the default button-size: medium.
Trying to change the css through childtheme css or the plugins wc-gateway-ppec-frontend.css isn't possible.
Someone has any solution?</p>

答:
That PayPal image is being loaded from Paypal’s servers. So in order to change it you will have to modify the plugin code.

For PayPal button shape in checkout page navigate to: (line 46)

wp-content/plugins/woocommerce-gateway-paypal-powered-by-braintree/includes/payment-forms/class-wc-braintree-paypal-payment-form.php

For PayPal button shape in cart page navigate to: (line 141)

wp-content/plugins/woocommerce-gateway-paypal-powered-by-braintree/includes/class-wc-braintree-paypal-cart.php

```<code>$default_button_styles = array(
    label: 'checkout',       // pay | paypal | buynow | checkout | credit
    size:  'responsive',     // small | medium | large | responsive
    shape: 'rect',           // pill | rect
    color: 'gold',           // gold | blue | silver | black
    tagline: false,          // true | false
    fundingicons: true,      // true | false
);
</code>```

Use the below code in your functions.php file. Upload a Custom Paypal Logo in your Media Library and then replace that URL in "$express_checkout_img_url" in the below function.

```<code>// Hook in
add_filter( ‘woocommerce_paypal_express_checkout_button_img_url’ , ‘custom_override_woocommerce_paypal_express_checkout_button_img_url’ );

// Our hooked in function – $fields is passed via the filter!
function custom_override_woocommerce_paypal_express_checkout_button_img_url( $variablen ) {
$express_checkout_img_url = '/wp-content/themes/XXXXXX/images/M3_Logo_01.jpg';
return $express_checkout_img_url;
}
</code>```

Check below URLs for some other ideas:
https://docs.woocommerce.com/document/paypal-express-checkout/#section-7

https://isabelcastillo.com/change-woocommerce-paypal-icon-to-custom-image-with-credit-card-icons

Body:
That PayPal image is being loaded from Paypal’s servers. So in order to change it you will have to modify the plugin code.

For PayPal button shape in checkout page navigate to: (line 46)

wp-content/plugins/woocommerce-gateway-paypal-powered-by-braintree/includes/payment-forms/class-wc-braintree-paypal-payment-form.php

For PayPal button shape in cart page navigate to: (line 141)

wp-content/plugins/woocommerce-gateway-paypal-powered-by-braintree/includes/class-wc-braintree-paypal-cart.php

$default_button_styles = array(
    label: 'checkout',       // pay | paypal | buynow | checkout | credit
    size:  'responsive',     // small | medium | large | responsive
    shape: 'rect',           // pill | rect
    color: 'gold',           // gold | blue | silver | black
    tagline: false,          // true | false
    fundingicons: true,      // true | false
);

Use the below code in your functions.php file. Upload a Custom Paypal Logo in your Media Library and then replace that URL in "$express_checkout_img_url" in the below function.

// Hook in
add_filter( ‘woocommerce_paypal_express_checkout_button_img_url’ , ‘custom_override_woocommerce_paypal_express_checkout_button_img_url’ );

// Our hooked in function – $fields is passed via the filter!
function custom_override_woocommerce_paypal_express_checkout_button_img_url( $variablen ) {
$express_checkout_img_url = '/wp-content/themes/XXXXXX/images/M3_Logo_01.jpg';
return $express_checkout_img_url;
}

Check below URLs for some other ideas:
https://docs.woocommerce.com/document/paypal-express-checkout/#section-7

https://isabelcastillo.com/change-woocommerce-paypal-icon-to-custom-image-with-credit-card-icons


问:
Not getting the expected output in strings
I am trying to remove vowels from a string and then printing it.

```<code>#include<iostream>
#include<string>

using namespace std;

int main(){
    string orig;
    string temp;
    cin >> orig;

    for(int i=0 ; i<orig.size() ; i++){

        if(orig[i] != 'a' || orig[i] != 'A' ||orig[i] != 'e'||orig[i] != 'E'||orig[i] != 'i'||orig[i] != 'I'||
        orig[i] != 'o'||orig[i] != 'O'||orig[i] != 'u'||orig[i] != 'U'){

            temp += orig[i];

        }
    }
    cout<<temp;
    return 0;
    }
</code>```

But this program is printing the same input string without any change. I am not getting, where things going wrong.

答:
If you want to not to include the vowels you should be using && not ||.

```<code>    if (orig[i] != 'a' || orig[i] != 'A' ||orig[i] != 'e'||orig[i] != 'E'||orig[i] != 'i'||orig[i] != 'I'||
    orig[i] != 'o'||orig[i] != 'O'||orig[i] != 'u'||orig[i] != 'U')
</code>```

should be

```<code>    if(orig[i] != 'a' && orig[i] != 'A' && orig[i] != 'e' && orig[i] != 'E' && orig[i] != 'i'&& orig[i] != 'I'&&
    orig[i] != 'o'&& orig[i] != 'O'&& orig[i] != 'u'&& orig[i] != 'U')
</code>```

Body:
I am trying to remove vowels from a string and then printing it.

#include<iostream>
#include<string>

using namespace std;

int main(){
    string orig;
    string temp;
    cin >> orig;

    for(int i=0 ; i<orig.size() ; i++){

        if(orig[i] != 'a' || orig[i] != 'A' ||orig[i] != 'e'||orig[i] != 'E'||orig[i] != 'i'||orig[i] != 'I'||
        orig[i] != 'o'||orig[i] != 'O'||orig[i] != 'u'||orig[i] != 'U'){

            temp += orig[i];

        }
    }
    cout<<temp;
    return 0;
    }

But this program is printing the same input string without any change. I am not getting, where things going wrong.

Body:
If you want to not to include the vowels you should be using && not ||.

    if (orig[i] != 'a' || orig[i] != 'A' ||orig[i] != 'e'||orig[i] != 'E'||orig[i] != 'i'||orig[i] != 'I'||
    orig[i] != 'o'||orig[i] != 'O'||orig[i] != 'u'||orig[i] != 'U')

should be

    if(orig[i] != 'a' && orig[i] != 'A' && orig[i] != 'e' && orig[i] != 'E' && orig[i] != 'i'&& orig[i] != 'I'&&
    orig[i] != 'o'&& orig[i] != 'O'&& orig[i] != 'u'&& orig[i] != 'U')


问:
How would I snap a position to a rectangular grid?
I'm trying to make a midi-editor in processing and I need to have rectangular cells that you can click on to add a note there.

So far I've done googling but haven't found a result. What happens is when you click the further down the less accurate it gets.

I don't know what is going wrong and I've had this problem in the past but couldn't fix it.

Note: The cells are not square.

答:
Example processing code to snap the mouse coordinates to the center of the nearest grid cell (where cell dimensions are defined by rectangle width and height).</p>

```<code>int w = 48; // rectangle width
int h = 24; // rectangle height

int snapX = round(mouseX / w) * w + w/2; // '+ w/2' is offset to center of cell
int snapY = round(mouseY / h) * h + h/2;   // '+ h/2' is offset to center of cell
</code>```

Body:
Example processing code to snap the mouse coordinates to the center of the nearest grid cell (where cell dimensions are defined by rectangle width and height).

int w = 48; // rectangle width
int h = 24; // rectangle height

int snapX = round(mouseX / w) * w + w/2; // '+ w/2' is offset to center of cell
int snapY = round(mouseY / h) * h + h/2;   // '+ h/2' is offset to center of cell


问:
iPhone App :How to play Youtube video in app using MPMoviePlayerController
iPhone App :How to play Youtube video in app using MPMoviePlayerController

for that  i write the code:

```<code> NSString *urlAddress = @"http://www.youtube.com/xyz";
 NSLog(@"URL ADDress : %@",urlAddress);

 //Create a URL object.
  NSURL *url = [NSURL URLWithString:urlAddress];

movie = [[MPMoviePlayerController alloc] initWithContentURL:url];
movie.scalingMode=MPMovieScalingModeAspectFill;
    movie.view.frame = CGRectMake(0.0, 0.0, 320.0, 460.0);
[self.view addSubview:movie.view];
[movie play];
</code>```

if i pass the url of local directory it is playing video

```<code> NSString* filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Video.mp4"];
NSURL* url = [[[NSURL alloc] initFileURLWithPath:filePath] autorelease];
</code>```

How can I play video directly from youtube url to MPMoviePlayerController?

答:
```<code>  NSString *url = @"http://www.example.com/path/to/movie.mp4";
  MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:url]];
  [moviePlayer play];
</code>```

Check this and release the controller.

Body:
iPhone App :How to play Youtube video in app using MPMoviePlayerController

for that  i write the code:

 NSString *urlAddress = @"http://www.youtube.com/xyz";
 NSLog(@"URL ADDress : %@",urlAddress);

 //Create a URL object.
  NSURL *url = [NSURL URLWithString:urlAddress];

movie = [[MPMoviePlayerController alloc] initWithContentURL:url];
movie.scalingMode=MPMovieScalingModeAspectFill;
    movie.view.frame = CGRectMake(0.0, 0.0, 320.0, 460.0);
[self.view addSubview:movie.view];
[movie play];

if i pass the url of local directory it is playing video

 NSString* filePath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Video.mp4"];
NSURL* url = [[[NSURL alloc] initFileURLWithPath:filePath] autorelease];

How can I play video directly from youtube url to MPMoviePlayerController?

Body:
  NSString *url = @"http://www.example.com/path/to/movie.mp4";
  MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:url]];
  [moviePlayer play];

Check this and release the controller.


问:
Is storing project configuration in environment variables a bad practice?
Some background first:
i am currently testing a class that sends a GET request with a configurable url, which is built like this

```<code>url = f"{os.environ["TARGET_URL"]}/api/etc"
</code>```

For normal operation, my TARGET_URL environment variable is set at project startup from a .env file and everything works. When testing locally, everything is still fine, tests passes and everyone is happy. My issue arose when I discovered that my Drone CI server failed to complete the project's build because the TARGET_URL environment variable wasn't found.

After some digging I found out that I had the wrong (dumb) idea that environment variables were reset at every project/test startup, and I basically was using my production environment variable all this time (even during tests) because it was set at first project startup.

From this story comes my question: given that environment variables are kept between executions, would storing configurations in them result in a bad practice? Is there an equally convenient alternative (no global objects and access from everywhere in the code) that can be used instead?

答:
Environment variables stored in config files or .env files is not a bad practice.

However, it is recommended that you use a key vault such as Azure Key Vault or AWS Key Management System for production deployments.

This way you further remove the keys away from your server (if env files) as well as code (if it is in config files)

Body:
Some background first:
i am currently testing a class that sends a GET request with a configurable url, which is built like this

url = f"{os.environ["TARGET_URL"]}/api/etc"

For normal operation, my TARGET_URL environment variable is set at project startup from a .env file and everything works. When testing locally, everything is still fine, tests passes and everyone is happy. My issue arose when I discovered that my Drone CI server failed to complete the project's build because the TARGET_URL environment variable wasn't found.

After some digging I found out that I had the wrong (dumb) idea that environment variables were reset at every project/test startup, and I basically was using my production environment variable all this time (even during tests) because it was set at first project startup.

From this story comes my question: given that environment variables are kept between executions, would storing configurations in them result in a bad practice? Is there an equally convenient alternative (no global objects and access from everywhere in the code) that can be used instead?


问:
How to allow an iframe tag in `dompurify` including all of its attributes
I want dompurify to allow iframe tags, and I add iframe as an exception(ADD_TAGS). But that removes some attributes of it. I want all attributes to be there.

```<code><!doctype html>
<html>
    <head>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/1.0.3/purify.min.js"></script>    </head>
    <body>
        <!-- Our DIV to receive content -->
        <div id="sanitized"></div>

        <!-- Now let's sanitize that content -->
        <script>
            /* jshint globalstrict:true, multistr:true */
            /* global DOMPurify */
            'use strict';

            // Specify dirty HTML
            var dirty = '<iframe allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" scrolling="no" src="https://www.youtube.com/embed/vJG698U2Mvo" width="560"></iframe>';

            var config = { ADD_TAGS: ['iframe'], KEEP_CONTENT: false }

            // Clean HTML string and write into our DIV
            var clean = DOMPurify.sanitize(dirty, config);
            console.log('clean: ', clean)
            document.getElementById('sanitized').innerHTML = clean;
        </script>
    </body>
</html>
</code>```

Here is the sanitized output

```<code>"clean: <iframe width='560' src='https://www.youtube.com/embed/vJG698U2Mvo' height='315'></iframe>"
</code>```

答:
If I understand the documentation correctly, you also need to register the necessary non-standard attributes that you want to keep using: </p>

```<code>DOMPurify.sanitize(dirty, { ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'] });
</code>```

Body:
I want dompurify to allow iframe tags, and I add iframe as an exception(ADD_TAGS). But that removes some attributes of it. I want all attributes to be there.

<!doctype html>

Here is the sanitized output

"clean: "

Body:
If I understand the documentation correctly, you also need to register the necessary non-standard attributes that you want to keep using:

DOMPurify.sanitize(dirty, { ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'] });


问:
How can I perform left join of two tables when they are being updated
I have two tables: tb1 and tb2, I'm performing left join to create new table called tb3,  from these two tables. once in a while, tb1 and tb2 are being updated with new rows and want to perform same left join to create updated tb3 table, can I do this task without writing new left joins everytime tables are updating? whats the best solution for that kind of task?</p>

答:
Use a view:

```<code>create view v_tb3 as
    select . . .
    from table1 t1 left join
         table2 t2
         on . . .
    . . .;
</code>```

This will run the query every time you access the view.  That will ensure that the data is up-to-date.

If you actually want to persist the data as a table (so it does not need to be recalculated), then you can use a materialized view:

```<code>create materialized view mv_tb3 as
    select . . .
    from table1 t1 left join
         table2 t2
         on . . .
    . . .;
</code>```

However, there are caveats on how recent the data is.  And maintaining the view requires overhead.  A left join is not typically particularly expensive, so I would generally recommend a simple view.

Body:
Use a view:

create view v_tb3 as
    select . . .
    from table1 t1 left join
         table2 t2
         on . . .
    . . .;

This will run the query every time you access the view.  That will ensure that the data is up-to-date.

If you actually want to persist the data as a table (so it does not need to be recalculated), then you can use a materialized view:

create materialized view mv_tb3 as
    select . . .
    from table1 t1 left join
         table2 t2
         on . . .
    . . .;

However, there are caveats on how recent the data is.  And maintaining the view requires overhead.  A left join is not typically particularly expensive, so I would generally recommend a simple view.


问:
Using awk how do I replace a word in a file with unique values?
This is the file I want to use:

test.txt:

```<code>apiVersion: v1
data:
  app_username: something
  app_password: {{RANDOM}}
  another_app_username: something
  another_app_password: {{RANDOM}}
</code>```

I currently have this bash script:

test.sh:

```<code>random(){
  printf $(openssl rand -base64 15) | openssl base64
}

export -f random

awk '{
  gsub(/{{RANDOM}}/, system("random"), $0); printf
}' test.txt
</code>```

This outputs:

```<code>TVQ3K0hmZmZGMTBPYW9BT0pIbzc=
apiVersion: v1QlBXZzVFNXFUdzBXNzdwdmtWc2w=
data:eDJDcUZKU1U2d1EwaWc5cVhQYUY=
  app_username: somethingay93S3NTNStQKy9jVXFOUHBSZnY=
  app_password: 0NTBJTUpueWRuU1VZYmlWSXZwS0k=
  another_app_username: somethingdzdCWXltMytSUWRFY2RicVh5ZkI=
  another_app_password: 0%
</code>```

As you can see, it's doing something. It's removing {{RANDOM}} but not replacing it. Instead it's putting the output of the 'random' function at the end of every new line.

答:
You may use it like this:

```<code>awk 'function rndm(cmd, line, r) {
   cmd = "random"
   if ( (cmd | getline line) > 0)
      r=line
   close(cmd)
   return r
}
{
   gsub(/{{RANDOM}}/, rndm())
} 1' file
</code>```

```<code>apiVersion: v1
data:
  app_username: something
  app_password: blBVOFduMzRLSEtSWjlRK0czT1M=
  another_app_username: something
  another_app_password: WWtZb1dWN2tnN0NwZEo1NTB2ZHE=
</code>```

Body:
This is the file I want to use:

test.txt:

apiVersion: v1
data:
  app_username: something
  app_password: {{RANDOM}}
  another_app_username: something
  another_app_password: {{RANDOM}}

I currently have this bash script:

test.sh:

random(){
  printf $(openssl rand -base64 15) | openssl base64
}

export -f random

awk '{
  gsub(/{{RANDOM}}/, system("random"), $0); printf
}' test.txt

This outputs:

TVQ3K0hmZmZGMTBPYW9BT0pIbzc=
apiVersion: v1QlBXZzVFNXFUdzBXNzdwdmtWc2w=
data:eDJDcUZKU1U2d1EwaWc5cVhQYUY=
  app_username: somethingay93S3NTNStQKy9jVXFOUHBSZnY=
  app_password: 0NTBJTUpueWRuU1VZYmlWSXZwS0k=
  another_app_username: somethingdzdCWXltMytSUWRFY2RicVh5ZkI=
  another_app_password: 0%

As you can see, it's doing something. It's removing {{RANDOM}} but not replacing it. Instead it's putting the output of the 'random' function at the end of every new line.

Body:
You may use it like this:

awk 'function rndm(cmd, line, r) {
   cmd = "random"
   if ( (cmd | getline line) > 0)
      r=line
   close(cmd)
   return r
}
{
   gsub(/{{RANDOM}}/, rndm())
} 1' file

apiVersion: v1
data:
  app_username: something
  app_password: blBVOFduMzRLSEtSWjlRK0czT1M=
  another_app_username: something
  another_app_password: WWtZb1dWN2tnN0NwZEo1NTB2ZHE=


问:
Trigger another job from a job, but based on a boolean
Was able to figure out how to trigger another job from my job using Trigger/call builds on other projects. This is how I have my setup currently -

Main job Configuration:

Choice param values: No, Build another job to setup binaries

Build -> Trigger/call builds on other projects:

Configured the params the job expects

When I select the choice currently when triggering main job, it triggers the other job correctly.

Does anyone if there's a way to simply use a boolean param? (instead of the choice param)

答: This is what I was looking for in case someone else trying to figure this out - https://plugins.jenkins.io/conditional-buildstep/</p>


问:
AWS Lambda Error: Quit inactivity timeout at Quit
I am facing a strange issue on AWS Lambda in which my API calls fail with a 502 error,

I checked the CloudWatch logs, and in these cases, not even my 1st line of code which is logging the event object is getting printed

The function call is not reaching the DAO layer of my code for sure.

The logs are showing the following trace -

```<code>2019-07-25T08:03:55.668Z    2329a426-a841-4ce2-91ed-1000c623ba14    Error: Quit inactivity timeout
at Quit.<anonymous> (/opt/layer/node_modules/mysql/lib/protocol/Protocol.js:160:17)
at emitNone (events.js:106:13)
at Quit.emit (events.js:208:7)
at Quit._onTimeout (/opt/layer/node_modules/mysql/lib/protocol/sequences/Sequence.js:124:8)
at Timer._onTimeout (/opt/layer/node_modules/mysql/lib/protocol/Timer.js:32:23)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
</code>```

Here's a log sample of this strange request -

I this API behavior is inconsistent,

These failure calls don't even print the first line of my handler

I am using node 8.10 and mysql lib "mysql": "^2.17.1"

答:
how are you?

I was facing the same problem and I solved it very simply:

I changed the connection.end (); by connectionn.destroy ();

The destroy, after performing its function, immediately terminates the connection with the DB. the "end" is asynchronous and this can be the cause of the error.

Look:

"To force the connection close immediately, you can use the destroy() method. The destroy() method guarantees that no more callbacks or events will be triggered for the connection.
Note that the destroy() method does not take any callback argument like the end() method."

Font:https://www.mysqltutorial.org/mysql-nodejs/connect/

Body:
I am facing a strange issue on AWS Lambda in which my API calls fail with a 502 error,

I checked the CloudWatch logs, and in these cases, not even my 1st line of code which is logging the event object is getting printed

The function call is not reaching the DAO layer of my code for sure.

The logs are showing the following trace -

2019-07-25T08:03:55.668Z    2329a426-a841-4ce2-91ed-1000c623ba14    Error: Quit inactivity timeout
at Quit.<anonymous> (/opt/layer/node_modules/mysql/lib/protocol/Protocol.js:160:17)
at emitNone (events.js:106:13)
at Quit.emit (events.js:208:7)
at Quit._onTimeout (/opt/layer/node_modules/mysql/lib/protocol/sequences/Sequence.js:124:8)
at Timer._onTimeout (/opt/layer/node_modules/mysql/lib/protocol/Timer.js:32:23)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)

Here's a log sample of this strange request -

I this API behavior is inconsistent,

These failure calls don't even print the first line of my handler

I am using node 8.10 and mysql lib "mysql": "^2.17.1"


问:
how to make chart using data from database?
HI
i am making a window application using visual studio 2010 and vb.net. i want to make charts daynimacilly using data from the database. how this can be done?

thanks
Yatin

答:
The following could be usefull:

Samples Environment for .NET Framework 4 Chart Controls Released!


问:
Convert json file with multiple lines to R dataframe
I'm using jsonr to read a JSON file in to R. However, the fromJSON(file="file.json") command is only reading the first line of the file. Here's the JSON:

```<code>{"id":"a","emailAddress":"a@a.com","name":"abc"}
{"id":"b","emailAddress":"b@b.com","name":"def"}
{"id":"c","emailAddress":"c@c.com","name":"ghi"}
</code>```

How do I get all 3 rows into an R dataframe? Note that the above content lives in a single file.

答:
I found a hacky way to do that; First i read in the whole file/string with readr, then i split the data by new lines "\n", and finally i parse each line with fromJSON and then i bind it into one dataframe:</p>

```<code>library(jsonlite)
library(readr)

json_raw   <- readr::read_file("file.json")
json_lines <- unlist(strsplit(json_raw, "\\n"))
json_df    <- do.call(rbind, lapply(json_lines,
                                  FUN = function(x){as.data.frame(jsonlite::fromJSON(x))}))
</code>```

Body:
I'm using jsonr to read a JSON file in to R. However, the fromJSON(file="file.json") command is only reading the first line of the file. Here's the JSON:

{"id":"a","emailAddress":"a@a.com","name":"abc"}
{"id":"b","emailAddress":"b@b.com","name":"def"}
{"id":"c","emailAddress":"c@c.com","name":"ghi"}

How do I get all 3 rows into an R dataframe? Note that the above content lives in a single file.

Body:
I found a hacky way to do that; First i read in the whole file/string with readr, then i split the data by new lines "\n", and finally i parse each line with fromJSON and then i bind it into one dataframe:

library(jsonlite)
library(readr)

json_raw   <- readr::read_file("file.json")
json_lines <- unlist(strsplit(json_raw, "\\n"))
json_df    <- do.call(rbind, lapply(json_lines,
                                  FUN = function(x){as.data.frame(jsonlite::fromJSON(x))}))


问:
Is it possible to get the Instagram profile picture and other basic details?
I'm trying to get the details of the user using the access_token from the Instagram APIs, Instagram Basic Display API and Instagram Graph API. What I found is the details are bit messy and by going deep into it I'm not able to conclude the final result as I want.

What I got to know during the implementation is that Instagram has stopped the public APIs. does that mean apart from getting auth-token then had stopped everything?.

I have even tried the Instagram Basic Display API which is only giving the access of 4 fields account_type, id, media_count, username. Is it possible to get any other field from the same API?

If so How do I get the profile picture of the user and other basic details of the Instagram user?

any help will be appreciated

答:
Currently, the API endpoint for retrieving a user's profile information only allows for the retrieval of the 4 fields you listed above. This is, up to now, all that has been made available for retrieval through the me endpoint of the Instagram Basic Display API for getting a User node.

Until the API developers further extend the API's endpoints and capabilities, you won't be able to use this API programmatically to get a user's profile image.


问:
Print Date and Time In Visual Studio C++ build?
How would I print the date and time for the purposes of the build. Ie: When the console for my application starts up I want to do this:

```<code>Binary Build date: 03/03/2009 @ 10:00AM
</code>```

I think this would be a super useful function for all applications to have behind the scenes for programmers, especially in a team environment.

Is there a simple way to do this using Visual Studio 2008 in C++. Thanks.

答: Note that the time and date macros only work as desired if the particular file containing them is guaranteed to be compiled during every build. </p>

OwnerDisplayName: Brock Woolf

Body:
How would I print the date and time for the purposes of the build. Ie: When the console for my application starts up I want to do this:

Binary Build date: 03/03/2009 @ 10:00AM

I think this would be a super useful function for all applications to have behind the scenes for programmers, especially in a team environment.

Is there a simple way to do this using Visual Studio 2008 in C++. Thanks.

LastEditorDisplayName: Iraimbilanja

OwnerDisplayName: anon


问:
weightsum text and image are not displaying properly in xml android
For the below xml code weight sum is 4 i have divided into 4 parts .2 parts for displaying text and remaining 2 parts again divided into 2 parts . 1 part contains text and another part contains image .but for the send 2 parts are not displaying properly.

text of the second layout is moving left side .
Can any one help me

```<code><LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal"
                            android:weightSum="4"
                            android:layout_marginTop="4dp"
                            android:paddingBottom="10dp"
                            android:id="@+id/outcomess"
                            android:layout_below="@+id/statuss">

                            <TextView
                                android:id="@+id/text_outcome"
                                style="@style/Base.TextAppearance.AppCompat.Subhead"
                                android:layout_width="0dp"
                                android:layout_height="wrap_content"
                                android:layout_below="@+id/bill_district"
                                android:paddingLeft="16dp"
                                android:paddingRight="16dp"
                                android:text="Outcome"
                                android:textStyle="bold"
                                android:layout_weight="2"
                                android:textColor="@color/gray"
                                android:textSize="15sp"
                                />

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal"
                        android:weightSum="2">
                            <TextView
                                android:id="@+id/outcome"
                                style="@style/Base.TextAppearance.AppCompat.Subhead"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Not Interested"
                                android:layout_weight="1"
                                android:textColor="@color/gray"
                                android:textSize="15sp"/>
                            <ImageView
                                android:layout_width="20dp"
                                android:layout_height="20dp"
                                android:id="@+id/image"
                                android:layout_weight="1"
                                android:src="@drawable/ic_thumb_up_black_24dp">

                            </ImageView>
                    </LinearLayout>

                        </LinearLayout>
</code>```

答:
```<code>>  you mentioned weightSum="4" so add weight second Linearlayout

  <LinearLayout
        android:id="@+id/outcomess"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/statuss"
        android:layout_marginTop="4dp"
        android:orientation="horizontal"
        android:paddingBottom="10dp"
        android:weightSum="4">

        <TextView
            android:id="@+id/text_outcome"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/bill_district"
            android:layout_weight="2"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:text="Outcome"
            android:textSize="15sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_weight="2"
            android:weightSum="">

            <TextView
                android:id="@+id/outcome"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Not Interested"
                android:textSize="15sp" />

            <ImageView
                android:id="@+id/image"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_weight="1"
                android:src="@drawable/car">

            </ImageView>
        </LinearLayout>

    </LinearLayout>
</code>```

Body:
For the below xml code weight sum is 4 i have divided into 4 parts .2 parts for displaying text and remaining 2 parts again divided into 2 parts . 1 part contains text and another part contains image .but for the send 2 parts are not displaying properly.

text of the second layout is moving left side .
Can any one help me

<LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal"
                            android:weightSum="4"
                            android:layout_marginTop="4dp"
                            android:paddingBottom="10dp"
                            android:id="@+id/outcomess"
                            android:layout_below="@+id/statuss">

                            <TextView
                                android:id="@+id/text_outcome"
                                style="@style/Base.TextAppearance.AppCompat.Subhead"
                                android:layout_width="0dp"
                                android:layout_height="wrap_content"
                                android:layout_below="@+id/bill_district"
                                android:paddingLeft="16dp"
                                android:paddingRight="16dp"
                                android:text="Outcome"
                                android:textStyle="bold"
                                android:layout_weight="2"
                                android:textColor="@color/gray"
                                android:textSize="15sp"
                                />

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="horizontal"
                        android:weightSum="2">
                            <TextView
                                android:id="@+id/outcome"
                                style="@style/Base.TextAppearance.AppCompat.Subhead"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="Not Interested"
                                android:layout_weight="1"
                                android:textColor="@color/gray"
                                android:textSize="15sp"/>
                            <ImageView
                                android:layout_width="20dp"
                                android:layout_height="20dp"
                                android:id="@+id/image"
                                android:layout_weight="1"
                                android:src="@drawable/ic_thumb_up_black_24dp">

                            </ImageView>
                    </LinearLayout>

                        </LinearLayout>


问:
R error “Can't join on … because of incompatible types (list / list)”
I'm aware that questions with similar error codes have been asked, but our problem is not answered so far.

Problem: self join of dataframe on itself by a column that has lists as content.

DATA:

```<code>bsp_fn <- c("1","2","3","4","5")
bsp_liste1 <- list(list("a","b","c"),list("a","b"),list("a","c"),list("a","b","c"),list("b","c"))
bsp_df <- tibble(bsp_fn,bsp_liste1)
</code>```

PROBLEM:

```<code>bsp_df %>% inner_join(bsp_df,by="bsp_liste1")

Error: Can't join on'bsp_liste1' x 'bsp_liste1' because of incompatible types (list / list)
</code>```

QUESTION:

Can I join "by comparison" of the lists? Since the list "a","b","c" appears twice, I would expect a match here.

答:
I don't think you can join using lists as by, I think by has to be an atomic data structure. However, this works:

```<code>bsp_df %>%
  mutate(ID = paste0(unlist(bsp_liste1), collapse="")) %>%
  inner_join(bsp_df %>% mutate(ID = paste0(unlist(bsp_liste1), collapse="")),by="ID")
</code>```

Body:
I'm aware that questions with similar error codes have been asked, but our problem is not answered so far.

Problem: self join of dataframe on itself by a column that has lists as content.

DATA:

bsp_fn <- c("1","2","3","4","5")
bsp_liste1 <- list(list("a","b","c"),list("a","b"),list("a","c"),list("a","b","c"),list("b","c"))
bsp_df <- tibble(bsp_fn,bsp_liste1)

PROBLEM:

bsp_df %>% inner_join(bsp_df,by="bsp_liste1")

Error: Can't join on'bsp_liste1' x 'bsp_liste1' because of incompatible types (list / list)

QUESTION:

Can I join "by comparison" of the lists? Since the list "a","b","c" appears twice, I would expect a match here.

Body:
I don't think you can join using lists as by, I think by has to be an atomic data structure. However, this works:

bsp_df %>%
  mutate(ID = paste0(unlist(bsp_liste1), collapse="")) %>%
  inner_join(bsp_df %>% mutate(ID = paste0(unlist(bsp_liste1), collapse="")),by="ID")


问:
/bin/sh: jlink: not found. command '/bin/sh -c jlink' returned a non-zero code: 127
the dockerfile used -

```<code>FROM azul/zulu-openjdk-alpine:11 as jdk

RUN jlink \
    --module-path /usr/lib/jvm/*/jmods/ \
    --verbose \
    --add-modules java.base,jdk.unsupported,java.sql,java.desktop \
    --compress 2 \
    --no-header-files \
    --no-man-pages \
    --output /opt/jdk-11-minimal

FROM alpine:3.10
ENV JAVA_HOME=/opt/jdk-11-minimal
ENV PATH=$PATH:/opt/jdk-11-minimal/bin
COPY --from=jdk /opt/jdk-11-minimal /opt/jdk-11-minimal
</code>```

why jlink can't be found in azul/zulu-openjdk-alpine:11?

答:
Please, use $JAVA_HOME/bin/jlink.

For historical reasons $JAVA_HOME/bin is not included in PATH, so you need to state it directly.

Body:
the dockerfile used -

FROM azul/zulu-openjdk-alpine:11 as jdk

RUN jlink \
    --module-path /usr/lib/jvm/*/jmods/ \
    --verbose \
    --add-modules java.base,jdk.unsupported,java.sql,java.desktop \
    --compress 2 \
    --no-header-files \
    --no-man-pages \
    --output /opt/jdk-11-minimal

FROM alpine:3.10
ENV JAVA_HOME=/opt/jdk-11-minimal
ENV PATH=$PATH:/opt/jdk-11-minimal/bin
COPY --from=jdk /opt/jdk-11-minimal /opt/jdk-11-minimal

why jlink can't be found in azul/zulu-openjdk-alpine:11?


答:
You're using or operators instead of ands. What you want to check is that the certain letter is none of the vowels, that is, not 'a' and not 'A' and not 'e'...
Swap the || with && and you'll have it.

#include<iostream>
#include<string>

using namespace std;

int main(){
    string orig;
    string temp;
    cin >> orig;

    for(int i=0 ; i<orig.size() ; i++){

        if(orig[i] != 'a' && orig[i] != 'A' && orig[i] != 'e' && orig[i] != 'E' && orig[i] != 'i' && orig[i] != 'I'&& orig[i] != 'o' && orig[i] != 'O' && orig[i] != 'u' && orig[i] != 'U'){

            temp += orig[i];

        }
    }
    cout<<temp;
    return 0;
    }
```

Title: Not getting the expected output in strings

Body:
I am trying to remove vowels from a string and then printing it.

#include<iostream>
#include<string>

using namespace std;

int main(){
    string orig;
    string temp;
    cin >> orig;

    for(int i=0 ; i<orig.size() ; i++){

        if(orig[i] != 'a' || orig[i] != 'A' ||orig[i] != 'e'||orig[i] != 'E'||orig[i] != 'i'||orig[i] != 'I'||
        orig[i] != 'o'||orig[i] != 'O'||orig[i] != 'u'||orig[i] != 'U'){

            temp += orig[i];

        }
    }
    cout<<temp;
    return 0;
    }

But this program is printing the same input string without any change. I am not getting, where things going wrong.


问:
Error inflating class android.support.v7.widget.CardView?
I am trying to add card view in my XML but I keep getting this exception

```<code>android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.CardView
</code>```

I am using the google code

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
... >
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="200dp"
    android:layout_height="200dp"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.v7.widget.CardView>
</code>```

Create Cards

I have even added the card view jar. I am using eclipse for dev.

What is the issue?

答:
Blockquote
  implementation 'com.android.support:cardview-v7:23.3.+'

```<code><androidx.cardview.widget.CardView
  android:id="@+id/card_view"
  android:layout_width="match_parent"
  android:layout_gravity="center"
  android:layout_margin="2dp"
  card_view:cardCornerRadius="5dp"
  android:layout_height="300dp">
</code>```

Body:
I am trying to add card view in my XML but I keep getting this exception

android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.CardView

I am using the google code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
... >

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="200dp"
    android:layout_height="200dp"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.v7.widget.CardView>

Create Cards

I have even added the card view jar. I am using eclipse for dev.

What is the issue?

Body:
Blockquote
  implementation 'com.android.support:cardview-v7:23.3.+'

<androidx.cardview.widget.CardView
  android:id="@+id/card_view"
  android:layout_width="match_parent"
  android:layout_gravity="center"
  android:layout_margin="2dp"
  card_view:cardCornerRadius="5dp"
  android:layout_height="300dp">


问:
Creating and pushing elements in an new array depends on conditions
My Data Array

```<code>data:[
0:{
   id:1 ,.....
   competetion:[
          0:{
              id: 1....,
              match:[
                      0:{id: 1 ......},
                      1:{same}
                      .
                      .
                    ]
          1:{same}]},
          2:{same}
          .
          .
        ]
  },
1:{same},
2:{same}
.
.
.
]

</code>```

For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...

My Code: Here i am looping it:

```<code>this.sportsSidebar = response.data;   // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
    this.sportarr.push({       // I declared a new array where i want to push the element
      id: i,
      value: false
    });
}
</code>```

答:
i Appriciate Pathikrit Sanyal and Fahd Lihidheb For the ansers
Here Is my Change according to Pathikrit Sanyal

```<code>  for (let i = 0; i < arrlength; i++) {
        let competition = [];
        competition = response.data[i].competetion.map((val, index) => {
          let match = [];
          match = val.match.map((value, indx) => {
            return {
              id: indx,
              value: false
            };
          });
          return {
            id: index,
            value: false,
            match
          };
        });
        this.sportarr.push({
          id: i,
          value: false,
          competetion: competition
        });
        console.log('myarrr...', this.sportarr);
      }
</code>```

Now i am getting what i wanted

Body:
My Data Array

data:[
0:{
   id:1 ,.....
   competetion:[
          0:{
              id: 1....,
              match:[
                      0:{id: 1 ......},
                      1:{same}
                      .
                      .
                    ]
          1:{same}]},
          2:{same}
          .
          .
        ]
  },
1:{same},
2:{same}
.
.
.
]

For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...

My Code: Here i am looping it:

this.sportsSidebar = response.data;   // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
    this.sportarr.push({       // I declared a new array where i want to push the element
      id: i,
      value: false
    });
}

Body:
i Appriciate Pathikrit Sanyal and Fahd Lihidheb For the ansers
Here Is my Change according to Pathikrit Sanyal

  for (let i = 0; i < arrlength; i++) {
        let competition = [];
        competition = response.data[i].competetion.map((val, index) => {
          let match = [];
          match = val.match.map((value, indx) => {
            return {
              id: indx,
              value: false
            };
          });
          return {
            id: index,
            value: false,
            match
          };
        });
        this.sportarr.push({
          id: i,
          value: false,
          competetion: competition
        });
        console.log('myarrr...', this.sportarr);
      }

Now i am getting what i wanted


问:
Remove last instance of string from an element's text
I am trying to to cut the last CHF text out of the div. I couldn't get this to work.

$(document).ready(function() {
  var myval = $(".gui-big.guy-price strong").text();
  console.log(myval);
  myval = myval.substring(0, myval.length - 3);
  $("div.gui-big.guy-price strong").val(myval);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gui-item gui-big">
  <div class="gui-desc">
    <strong>Gesamt inkl. MwSt:</strong>
  </div>
  <div class="gui-price">
    <strong>CHF53,70 CHF</strong>
  </div></code>```

答:
Firstly note that your selectors are incorrect. It has a typo, and requires spaces to indicate that you're looking for child elements.

To replace the last occurence of one string within another you can use a regular expression. To make this more succinct you can provide a function to text() which accepts the current value as an argument and returns the new value to be set. Try this:

$(document).ready(function() {
  $('.gui-big .gui-price strong').text((i, t) => t.replace(/CHF([^CHF]*)$/, '$1'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gui-item gui-big">
  <div class="gui-desc">
    <strong>Gesamt inkl. MwSt:</strong>
  </div>
  <div class="gui-price">
    <strong>CHF53,70 CHF</strong>
  </div>
</div></code>```

Body:
I am trying to to cut the last CHF text out of the div. I couldn't get this to work.

$(document).ready(function() {
  var myval = $(".gui-big.guy-price strong").text();
  console.log(myval);
  myval = myval.substring(0, myval.length - 3);
  $("div.gui-big.guy-price strong").val(myval);
});

    Gesamt inkl. MwSt:

    CHF53,70 CHF

Body:
Firstly note that your selectors are incorrect. It has a typo, and requires spaces to indicate that you're looking for child elements.

To replace the last occurence of one string within another you can use a regular expression. To make this more succinct you can provide a function to text() which accepts the current value as an argument and returns the new value to be set. Try this:

$(document).ready(function() {
  $('.gui-big .gui-price strong').text((i, t) => t.replace(/CHF([^CHF]*)$/, '$1'));
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gui-item gui-big">
  <div class="gui-desc">
    <strong>Gesamt inkl. MwSt:</strong>
  </div>
  <div class="gui-price">
    <strong>CHF53,70 CHF</strong>
  </div>
</div>


问:
How to compare date if one column has start and end date
The column has a start and end date

```<code>month_name
23 March, 2018 - 23 April, 2018
</code>```

23 March, 2018 is the start date and 23 April, 2018 is the end date

How can I use them as to the start date and end date to query?

答:
For each and every query that would need to use these dates, you would have to unpick one or both of these dates that are relevant to the query using this kind of text and date  manipulation

```<code>SELECT .....
WHERE whatever_else
AND STR_TO_DATE(SUBSTRING_INDEX(monthname, ' -', 1 ), '%d %M,%Y') = '2018-03-23'
AND STR_TO_DATE(SUBSTRING(monthname, INSTR(monthname, '- ') +2 ), '%d %M,%Y') = '2018-04-23'
</code>```

In short your queries would be a complete nightmare to write and maintain and any indexing benefits you might have been able to use had these 2 dates been saved in 2 seperate columns are completely lost.

SUBSTRING_INDEX()

SUBSTRING()

INSTR()

STR_TO_DATE()

Body:
The column has a start and end date

month_name
23 March, 2018 - 23 April, 2018

23 March, 2018 is the start date and 23 April, 2018 is the end date

How can I use them as to the start date and end date to query?

Body:
For each and every query that would need to use these dates, you would have to unpick one or both of these dates that are relevant to the query using this kind of text and date  manipulation

SELECT .....
WHERE whatever_else
AND STR_TO_DATE(SUBSTRING_INDEX(monthname, ' -', 1 ), '%d %M,%Y') = '2018-03-23'
AND STR_TO_DATE(SUBSTRING(monthname, INSTR(monthname, '- ') +2 ), '%d %M,%Y') = '2018-04-23'

In short your queries would be a complete nightmare to write and maintain and any indexing benefits you might have been able to use had these 2 dates been saved in 2 seperate columns are completely lost.

SUBSTRING_INDEX()

SUBSTRING()

INSTR()

STR_TO_DATE()


问:
How can I automatically populate a cell in Google Sheets with an image from a Pinterest page?
Let's say I have a Google Sheet with URLs to individual pins on Pinterest in column B. For example: https://www.pinterest.com/pin/146578162860144581/

I'd like to populate cells in column C with the main image from the URL in column B.

Currently I have to do this manually by clicking through to the URL in column B, copy the image URL, and insert image into the cell in column C.

Is there a way to automate this?

答:
Solution

Yes, you can achieve this using the sheet's Google's Apps Script. Below the following piece of code you can find a brief explanation on how this works.

The code

function populateImage() {
  var sheet = SpreadsheetApp.getActiveSheet();
  // Get cell values of your link column
  var values = sheet.getRange('B1:B5').getValues();
  // Range where we want to insert the images
  var imgrange = sheet.getRange('C1:C5');

  for (i=0;i<5;i++){
    // Cell we want to insert the image
    var cell = imgrange.getCell(i+1, 1);

    // Pin Id which is at the end of each url provided, in this case 146578162860144581
    var number = values[i][0].substring(29,values[i][0].length-1);

    // Url to make the fetch request to access the json of that pin
    var url = 'https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids='+number;
    var response = UrlFetchApp.fetch(url);
    var json = response.getContentText();
    var data =  JSON.parse(json);

    // Url of the image of the pin
    var imgurl =data.data[0].images["237x"].url;

    // Insert image from url
    cell.setFormula('=image("'+imgurl+'")');
  }

}```

Result

Explanation

To insert an image in a website in your sheet you will need the image url. This is the most tricky part in this issue. Pinterest does not provide a good way to get this image url by just fetching to the pin url as this request will return HTML data and not json. To achieve this you will need to make a fetch request to this url https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=PINIDNUMBER. You can find more information about this in this Stack Overflow question, credit goes to @SambhavSharma .

When you fetch following this url you will get the pin's json from which you can retrieve your desired image url (apart from many other data about this pin). With it you can simply insert it in the next column.

I hope this has helped you, let me know if you need anything else or if you did not understand something.

Body:
Solution

Yes, you can achieve this using the sheet's Google's Apps Script. Below the following piece of code you can find a brief explanation on how this works.

The code

function populateImage() {
  var sheet = SpreadsheetApp.getActiveSheet();
  // Get cell values of your link column
  var values = sheet.getRange('B1:B5').getValues();
  // Range where we want to insert the images
  var imgrange = sheet.getRange('C1:C5');

  for (i=0;i<5;i++){
    // Cell we want to insert the image
    var cell = imgrange.getCell(i+1, 1);

    // Pin Id which is at the end of each url provided, in this case 146578162860144581
    var number = values[i][0].substring(29,values[i][0].length-1);

    // Url to make the fetch request to access the json of that pin
    var url = 'https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids='+number;
    var response = UrlFetchApp.fetch(url);
    var json = response.getContentText();
    var data =  JSON.parse(json);

    // Url of the image of the pin
    var imgurl =data.data[0].images["237x"].url;

    // Insert image from url
    cell.setFormula('=image("'+imgurl+'")');
  }

}

Result

Explanation

To insert an image in a website in your sheet you will need the image url. This is the most tricky part in this issue. Pinterest does not provide a good way to get this image url by just fetching to the pin url as this request will return HTML data and not json. To achieve this you will need to make a fetch request to this url https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=PINIDNUMBER. You can find more information about this in this Stack Overflow question, credit goes to @SambhavSharma .

When you fetch following this url you will get the pin's json from which you can retrieve your desired image url (apart from many other data about this pin). With it you can simply insert it in the next column.

I hope this has helped you, let me know if you need anything else or if you did not understand something.


问:
Border color on default input style
here's a tricky question...

I have default styled input fields (no css added, just width/height/padding), but now I want to give it a red border (error style). How can I do this? Just setting border will delete the default style of the input, setting only border-color will look weird, setting an outline will work in some cases (and doesn't look so good in Firefox).

Any tips?

EDIT: Come on guys read the question before answering. I want the browser default look of the input, I just want to give it a red border.

答:
whats actually wrong with:

```<code>input { border: 1px solid #f00; }
</code>```

do you only want it on inputs with errors? in that case give the input a class of error...

```<code>input.error { border: 1px solid #f00; }
</code>```

Title: Border color on default input style

Body:
whats actually wrong with:

input { border: 1px solid #f00; }

do you only want it on inputs with errors? in that case give the input a class of error...

input.error { border: 1px solid #f00; }