问:
Algorithm to rank markets
I have a dataset that contains information about markets. The dataset contains the following: Volume of market, # of purchases, avg purchases across all days, avg purchases across all days and across all markets, and the avg percentage of how cheaper this market is compared to all the markets.

The data looks something like this:

```<code>market volume  numPurchases   transDate  avgDailyPurchases  AvgDailyPurchasesAll
JFK    500     32             20190102   50                 75
JFK    500     60             20190103   50                 75
ATL    450     40             20190102   40                 75

avgPercentCheaperThanAll
.22
.22
.75
</code>```

What I'd like to do is rank the markets. A top market is defined where avgDailyPurhcases is high relative to its volume and avgPercentCheaperThanAll is also high. So in the data above, ATL would be a better market than JFK even though JFK has more avgDailyPurchases, ATL is much cheaper than all the markets.

I tried using the IMDB formula where they rank movies, but instead I used my own representation of the variables for example:

```<code>weighted rating (WR) = (v ÷ (v+m)) × R + (m ÷ (v+m)) × C
v = volume of market
m = minimum volume required to be in the list
R = avgDailyPurchases
C = AvgDailyPurchasesAll
</code>```

This gives me an almost good list, but it is missing one major factor: The avgPercentCheaperThanAll. How can I add this into the equation to get better results?

答:
Few points that should be considered before designing the rating equation or any equation would be.

Identify the input variables: As could be understood it could be.

avgDailyPurhcases, AvgDailyPurchasesAll,  avgPercentCheaperThanAll,
  volume, a minimum threshold for volume

Normalize the input variables: From the above data, it can be inferred that volume runs in 100's, average daily purchases in 10's while your cheaper variable runs in decimals. If you try to use these variables in a single equation directly without normalizing then your rating will be biased and driven primarily by volume factor. Therefore you should consider normalizing them, use this link to learn about more Normalize Data.

Assign weights: You want avgPercentCheaperThanAll to have higher preference than avgDailyPurchases  variable, this would be achieved by assigning appropriate weights to the variables.

Define the relationships: You should consider defining relationships between your variables whether they are directly related or indirectly related for your rating.

Deriving the equation: The final step would be to derive to the equation. From the above step, this would be very easy just combine all relationships then you will be left with an equation of type:

Rating = [weight of variable 1]*[normalized variable 1 value] + .... so on.

You will be able to derive your required equation from the above steps and that equation would be more clear to you and more adapt to your situation. Otherwise, you can copy any rating equation on the web and modify it according to your need but each equation will give different results and you won't be able to control them when more input variables arrive.

Hope this helps.

Title: Algorithm to rank markets

Body:
I have a dataset that contains information about markets. The dataset contains the following: Volume of market, # of purchases, avg purchases across all days, avg purchases across all days and across all markets, and the avg percentage of how cheaper this market is compared to all the markets.

The data looks something like this:

market volume  numPurchases   transDate  avgDailyPurchases  AvgDailyPurchasesAll
JFK    500     32             20190102   50                 75
JFK    500     60             20190103   50                 75
ATL    450     40             20190102   40                 75

avgPercentCheaperThanAll
.22
.22
.75

What I'd like to do is rank the markets. A top market is defined where avgDailyPurhcases is high relative to its volume and avgPercentCheaperThanAll is also high. So in the data above, ATL would be a better market than JFK even though JFK has more avgDailyPurchases, ATL is much cheaper than all the markets.

I tried using the IMDB formula where they rank movies, but instead I used my own representation of the variables for example:

weighted rating (WR) = (v ÷ (v+m)) × R + (m ÷ (v+m)) × C
v = volume of market
m = minimum volume required to be in the list
R = avgDailyPurchases
C = AvgDailyPurchasesAll

This gives me an almost good list, but it is missing one major factor: The avgPercentCheaperThanAll. How can I add this into the equation to get better results?


来源: stackexchange

问:
ORA-00908: missing NULL keyword in Oracle SQL (blob data type)
I am encountering error in creating a table with constraints on 2 blob data types that should contain only json.

The error is ORA-00908: missing NULL keyword

Here is my script

```<code>CREATE TABLE TEST
  (
    LOG_ID NUMBER(19,0) NOT NULL,
    DATA_BEFORE BLOB NULL,
    DATA_AFTER BLOB NULL,
    CONSTRAINT LOG_ID_PK PRIMARY KEY (LOG_ID),
    CONSTRAINT DATA_BEFORE_JSON CHECK(DATA_BEFORE IS JSON FORMAT JSON)) LOB (DATA_BEFORE) STORE AS(STORAGE (NEXT 15M)),
    CONSTRAINT DATA_AFTER_JSON CHECK(DATA_AFTER IS JSON FORMAT JSON)) LOB (DATA_AFTER) STORE AS(STORAGE (NEXT 15M))
    );
</code>```

Thank you very much.

答:
You seem to be on a database whose version doesn't support what you are doing. For example, 11gR2:

```<code>SQL> select * from v$version;

BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
PL/SQL Release 11.2.0.4.0 - Production
CORE    11.2.0.4.0      Production
TNS for Linux: Version 11.2.0.4.0 - Production
NLSRTL Version 11.2.0.4.0 - Production

SQL> CREATE TABLE test
  2  (
  3     log_id       NUMBER (19, 0) CONSTRAINT pk_lid PRIMARY KEY,
  4     data_before  BLOB,
  5     data_after   BLOB,
  6     constraint   data_before_json CHECK (data_before IS json),
  7     constraint   data_after_json  check (data_after is json)
  8  )
  9     lob (data_before) store as(storage (next 15m)),
 10     lob (data_after)  store as(storage (next 15m));
   constraint   data_before_json CHECK (data_before IS json),
                                                       *
ERROR at line 6:
ORA-00908: missing NULL keyword
</code>```

On 12.2:

```<code>BANNER                                                                               CON_ID
-------------------------------------------------------------------------------- ----------
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production              0
PL/SQL Release 12.2.0.1.0 - Production                                                    0
CORE    12.2.0.1.0      Production                                                        0
TNS for Linux: Version 12.2.0.1.0 - Production                                            0
NLSRTL Version 12.2.0.1.0 - Production                                                    0

SQL> CREATE TABLE test
  2  (
  3     log_id       NUMBER (19, 0) CONSTRAINT pk_lid PRIMARY KEY,
  4     data_before  BLOB,
  5     data_after   BLOB,
  6     constraint   data_before_json CHECK (data_before IS json),
  7     constraint   data_after_json  check (data_after is json)
  8  )
  9     lob (data_before) store as(storage (next 15m)),
 10     lob (data_after)  store as(storage (next 15m));

Table created.

SQL>
</code>```

Pay attention to differences between your and my code.

ContentLicense: CC BY-SA 4.0

Body:
I am encountering error in creating a table with constraints on 2 blob data types that should contain only json.

The error is ORA-00908: missing NULL keyword

Here is my script

CREATE TABLE TEST
  (
    LOG_ID NUMBER(19,0) NOT NULL,
    DATA_BEFORE BLOB NULL,
    DATA_AFTER BLOB NULL,
    CONSTRAINT LOG_ID_PK PRIMARY KEY (LOG_ID),
    CONSTRAINT DATA_BEFORE_JSON CHECK(DATA_BEFORE IS JSON FORMAT JSON)) LOB (DATA_BEFORE) STORE AS(STORAGE (NEXT 15M)),
    CONSTRAINT DATA_AFTER_JSON CHECK(DATA_AFTER IS JSON FORMAT JSON)) LOB (DATA_AFTER) STORE AS(STORAGE (NEXT 15M))
    );

Thank you very much.

Body:
You seem to be on a database whose version doesn't support what you are doing. For example, 11gR2:

SQL> select * from v$version;

BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
PL/SQL Release 11.2.0.4.0 - Production
CORE    11.2.0.4.0      Production
TNS for Linux: Version 11.2.0.4.0 - Production
NLSRTL Version 11.2.0.4.0 - Production

SQL> CREATE TABLE test
  2  (
  3     log_id       NUMBER (19, 0) CONSTRAINT pk_lid PRIMARY KEY,
  4     data_before  BLOB,
  5     data_after   BLOB,
  6     constraint   data_before_json CHECK (data_before IS json),
  7     constraint   data_after_json  check (data_after is json)
  8  )
  9     lob (data_before) store as(storage (next 15m)),
 10     lob (data_after)  store as(storage (next 15m));
   constraint   data_before_json CHECK (data_before IS json),
                                                       *
ERROR at line 6:
ORA-00908: missing NULL keyword

On 12.2:

BANNER                                                                               CON_ID
-------------------------------------------------------------------------------- ----------
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production              0
PL/SQL Release 12.2.0.1.0 - Production                                                    0
CORE    12.2.0.1.0      Production                                                        0
TNS for Linux: Version 12.2.0.1.0 - Production                                            0
NLSRTL Version 12.2.0.1.0 - Production                                                    0

SQL> CREATE TABLE test
  2  (
  3     log_id       NUMBER (19, 0) CONSTRAINT pk_lid PRIMARY KEY,
  4     data_before  BLOB,
  5     data_after   BLOB,
  6     constraint   data_before_json CHECK (data_before IS json),
  7     constraint   data_after_json  check (data_after is json)
  8  )
  9     lob (data_before) store as(storage (next 15m)),
 10     lob (data_after)  store as(storage (next 15m));

Table created.

SQL>

Pay attention to differences between your and my code.


问:
sql query customer who ordered more than 15 times
how to get list of customers who ordered more than 15times.
i have customerId , orderId , orderValue , orderDate.

I tried

```<code>select *  from customertable Group By customerId having count (*) > 15
</code>```

答:
```<code>SELECT customerid, COUNT(*) counter
FROM customertable
GROUP BY customerId HAVING counter >= 15
</code>```

Body:
how to get list of customers who ordered more than 15times.
i have customerId , orderId , orderValue , orderDate.

I tried

select *  from customertable Group By customerId having count (*) > 15


问:
Web page doesn´t update automatically when uploading new content
I´m creating a static web page with HTML and CSS, the problem comes when I upload new info into the server. When I try to reload the page nothing changes. It only changes when I make a ctrl f5 reload. Is there a way to make the site to reload itself so the user can see the newest info every time they enter the web site?

I tried using a "?" sing ager calling the CSS file but it's not working

```<code>link href="CSS/styles.css?v=1.1" rel="stylesheet"

</code>```

答:
Most likely, your browser is caching the content of your website when you visit it.
The next time you visit, it'll show the native, cached copy (unless you "hard-refresh" it eg(Ctrl + F5)).So you need "Cache Busting"

You can follow this article, it may help you.

https://css-tricks.com/strategies-for-cache-busting-css/

Thank You...

Body:
I´m creating a static web page with HTML and CSS, the problem comes when I upload new info into the server. When I try to reload the page nothing changes. It only changes when I make a ctrl f5 reload. Is there a way to make the site to reload itself so the user can see the newest info every time they enter the web site?

I tried using a "?" sing ager calling the CSS file but it's not working

link href="CSS/styles.css?v=1.1" rel="stylesheet"


问:
Vuejs Laravel Passport - what should I do if access token is expired?
I am using Vuejs SPA with Laravel API as backend. I successfully got the personal access token and store in localStorage and Vuex state like below.

```<code>token: localStorage.getItem('token') || '',
expiresAt: localStorage.getItem('expiresAt') || '',
</code>```

I use the access token every time I send axios request to laravel api. Every thing works well. However, initially the token was set to 1 year expiration so when I develop I didn't care about token being expired and today suddenly I thought what is going to happen if token expired. So I set token expiry to 10 seconds in laravel AuthServiceProvier.php.

```<code>Passport::personalAccessTokensExpireIn(Carbon::now()->addSecond(10));
</code>```

and then I logged in and after 10 seconds, every requests stopped working because the token was expired and got 401 unauthorised error.

In this case, how can I know if the token is expired? I would like to redirect the user to login page if token is expired when the user is using the website.

答:
This is what I do. Axios will throw error if the response code is 4xx or 5xx, and then I add an if to check if response status is 401, then redirect to login page.

```<code>export default {
    methods: {
        loadData () {
            axios
                .request({
                    method: 'get',
                    url: 'https://mysite/api/route',
                })
                .then(response => {
                    // assign response.data to a variable
                })
                .catch(error => {
                    if (error.response.status === 401) {
                        this.$router.replace({name: 'login'})
                    }
                })
        }
    }
}
</code>```

But if you do it like this, you have to copy paste the catch on all axios call inside your programs.
The way I did it is to put the code above to a javascript files api.js, import the class to main.js, and assign it to Vue.prototype.$api

```<code>import api from './api'
Object.defineProperty(Vue.prototype, '$api', { value: api })
</code>```

So that in my component, I just call the axios like this.

```<code>this.$api.GET(url, params)
    .then(response => {
        // do something
    })
</code>```

The error is handled on api.js.
This is my full api.js

```<code>import Vue from 'vue'
import axios from 'axios'
import router from '@/router'

let config = {
  baseURL : process.env.VUE_APP_BASE_API,
  timeout : 30000,
  headers : {
    Accept         : 'application/json',
    'Content-Type' : 'application/json',
  },
}

const GET = (url, params) => REQUEST({ method: 'get', url, params })
const POST = (url, data) => REQUEST({ method: 'post', url, data })
const PUT = (url, data) => REQUEST({ method: 'put', url, data })
const PATCH = (url, data) => REQUEST({ method: 'patch', url, data })
const DELETE = url => REQUEST({ method: 'delete', url })

const REQUEST = conf => {
  conf = { ...conf, ...config }
  conf = setAccessTokenHeader(conf)

  return new Promise((resolve, reject) => {
    axios
      .request(conf)
      .then(response => {
        resolve(response.data)
      })
      .catch(error => {
        outputError(error)
        reject(error)
      })
  })
}

function setAccessTokenHeader (config) {
  const access_token = Vue.cookie.get('access_token')
  if (access_token) {
    config.headers.Authorization = 'Bearer ' + access_token
  }

  return config
}

/* https://github.com/axios/axios#handling-errors */
function outputError (error) {
  if (error.response) {
    /**
     * The request was made and the server responded with a
     * status code that falls out of the range of 2xx
     */
    if (error.response.status === 401) {
      router.replace({ name: 'login' })
      return
    }
    else {
      /* other response status such as 403, 404, 422, etc */
    }
  }
  else if (error.request) {
    /**
     * The request was made but no response was received
     * `error.request` is an instance of XMLHttpRequest in the browser
     * and an instance of http.ClientRequest in node.js
     */
  }
  else {
    /* Something happened in setting up the request that triggered an Error */
  }
}

export default {
  GET,
  POST,
  DELETE,
  PUT,
  PATCH,
  REQUEST,
}
</code>```

Body:
I am using Vuejs SPA with Laravel API as backend. I successfully got the personal access token and store in localStorage and Vuex state like below.

token: localStorage.getItem('token') || '',
expiresAt: localStorage.getItem('expiresAt') || '',

I use the access token every time I send axios request to laravel api. Every thing works well. However, initially the token was set to 1 year expiration so when I develop I didn't care about token being expired and today suddenly I thought what is going to happen if token expired. So I set token expiry to 10 seconds in laravel AuthServiceProvier.php.

Passport::personalAccessTokensExpireIn(Carbon::now()->addSecond(10));

and then I logged in and after 10 seconds, every requests stopped working because the token was expired and got 401 unauthorised error.

In this case, how can I know if the token is expired? I would like to redirect the user to login page if token is expired when the user is using the website.

Body:
This is what I do. Axios will throw error if the response code is 4xx or 5xx, and then I add an if to check if response status is 401, then redirect to login page.

export default {
    methods: {
        loadData () {
            axios
                .request({
                    method: 'get',
                    url: 'https://mysite/api/route',
                })
                .then(response => {
                    // assign response.data to a variable
                })
                .catch(error => {
                    if (error.response.status === 401) {
                        this.$router.replace({name: 'login'})
                    }
                })
        }
    }
}

But if you do it like this, you have to copy paste the catch on all axios call inside your programs.
The way I did it is to put the code above to a javascript files api.js, import the class to main.js, and assign it to Vue.prototype.$api

import api from './api'
Object.defineProperty(Vue.prototype, '$api', { value: api })

So that in my component, I just call the axios like this.

this.$api.GET(url, params)
    .then(response => {
        // do something
    })

The error is handled on api.js.
This is my full api.js

import Vue from 'vue'
import axios from 'axios'
import router from '@/router'

let config = {
  baseURL : process.env.VUE_APP_BASE_API,
  timeout : 30000,
  headers : {
    Accept         : 'application/json',
    'Content-Type' : 'application/json',
  },
}

const GET = (url, params) => REQUEST({ method: 'get', url, params })
const POST = (url, data) => REQUEST({ method: 'post', url, data })
const PUT = (url, data) => REQUEST({ method: 'put', url, data })
const PATCH = (url, data) => REQUEST({ method: 'patch', url, data })
const DELETE = url => REQUEST({ method: 'delete', url })

const REQUEST = conf => {
  conf = { ...conf, ...config }
  conf = setAccessTokenHeader(conf)

  return new Promise((resolve, reject) => {
    axios
      .request(conf)
      .then(response => {
        resolve(response.data)
      })
      .catch(error => {
        outputError(error)
        reject(error)
      })
  })
}

function setAccessTokenHeader (config) {
  const access_token = Vue.cookie.get('access_token')
  if (access_token) {
    config.headers.Authorization = 'Bearer ' + access_token
  }

  return config
}

/* https://github.com/axios/axios#handling-errors */
function outputError (error) {
  if (error.response) {
    /**
     * The request was made and the server responded with a
     * status code that falls out of the range of 2xx
     */
    if (error.response.status === 401) {
      router.replace({ name: 'login' })
      return
    }
    else {
      /* other response status such as 403, 404, 422, etc */
    }
  }
  else if (error.request) {
    /**
     * The request was made but no response was received
     * `error.request` is an instance of XMLHttpRequest in the browser
     * and an instance of http.ClientRequest in node.js
     */
  }
  else {
    /* Something happened in setting up the request that triggered an Error */
  }
}

export default {
  GET,
  POST,
  DELETE,
  PUT,
  PATCH,
  REQUEST,
}


问:
Why do I get this error inserting a character into a MATLAB matrix?
I am constructing a 16x16 matrix, consisting of just letters in MATLAB. I tried for example:

```<code>for i=1:2:3
    C(i,2)=char('B');
end
</code>```

to place the letter 'B' in its corresponding place in the matrix. However this gives a value of 66 in the matrix instead of just the letter 'B'. What is going wrong?

答: Matlab stores the letter 'B' as integer ASCII code. Ini fact, char means int8.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am constructing a 16x16 matrix, consisting of just letters in MATLAB. I tried for example:

for i=1:2:3
    C(i,2)=char('B');
end

to place the letter 'B' in its corresponding place in the matrix. However this gives a value of 66 in the matrix instead of just the letter 'B'. What is going wrong?


问:
if my form submits the value in database download a pdf which is on server
```<code>$kite = "INSERT INTO `download` (name,email,contact,program,city,state)

VALUES ('" . $_POST['name'] . "','" . $_POST['email'] . "','" . $_POST['mobile'] . "','" . $_POST['program']."','" . $_POST['city']."','" . $_POST['state']."')";

$query=mysqli_query($sql,$kite);

if($query)
{ ?>
<meta http-equiv="refresh" content="3;/pdf/quadcopter.pdf" download>

 <?php
}
</code>```

答:
Assuming that you want to download a file, after the form has been submitted:

```<code>$kite = "INSERT INTO `download` (name,email,contact,program,city,state)
VALUES ('" . $_POST['name'] . "','" . $_POST['email'] . "','" . $_POST['mobile'] . "','" . $_POST['program']."','" . $_POST['city']."','" . $_POST['state']."')";

$query=mysqli_query($sql,$kite);
if($query) {
  header('Content-Description: File Transfer');
  header('Content-Type: application/pdf');
  header('Content-Disposition: attachment; filename="quadcopter.pdf"');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize("/path/to/quadcopter.pdf"));
  readfile("/path/to/quadcopter.pdf");
  die();
} else {
  // query error
}
</code>```

Two observation here:

you should not use $_POST values directly into your sql statements, as your code is open to sql injection;

you should not echo any code prior to the header functions inside the code (if you do that, the code will fail).

Body:
Assuming that you want to download a file, after the form has been submitted:

$kite = "INSERT INTO `download` (name,email,contact,program,city,state)
VALUES ('" . $_POST['name'] . "','" . $_POST['email'] . "','" . $_POST['mobile'] . "','" . $_POST['program']."','" . $_POST['city']."','" . $_POST['state']."')";

$query=mysqli_query($sql,$kite);
if($query) {
  header('Content-Description: File Transfer');
  header('Content-Type: application/pdf');
  header('Content-Disposition: attachment; filename="quadcopter.pdf"');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize("/path/to/quadcopter.pdf"));
  readfile("/path/to/quadcopter.pdf");
  die();
} else {
  // query error
}

Two observation here:

you should not use $_POST values directly into your sql statements, as your code is open to sql injection;

you should not echo any code prior to the header functions inside the code (if you do that, the code will fail).


问:
How to reset Bitbucket password in GitHub Desktop on Mac?
I'm using a Bitbucket repo in GitHub Desktop for Mac.

Since Atlassian changed my password, GitHub Desktop can't log in anymore and doesn't give me opportunity to provide new password. It says "Check preferences to make sure you're still logged in", but preferences only talks about GitHub account.

I'm able to push using command-line git.

Any ideas how to solve this?

Where can I submit issues for GitHub Desktop?

答:
Recently I have faced a problem. My password wasn't save in keychain. My solution is described below...

Got to the folder ~/Library/Application Support/SourceTree

Delete the file {Username}@STAuth-bitbucket.org

Restart Sourcetree

Try to fetch, password filed appear, give your new password

Also can run "git fetch" command in terminal and need to type password

Done


问:
Python Regex Capturing Group
```<code>string1 = "abcdbcdbcde"
</code>```

I want to extract string1 into three parts:
(first part and third part can be empty string)

first part:  a

second part (repeitions of some string):  bcdbcdbcd

third part: e

```<code>import re

string1 = "abcdbcdbcde"
m = re.match("(.*)(.+){2,}(.*)", string1)
print m.groups()[0], m.groups()[1], m.groups()[2]
</code>```

Of cuz, the code above doesn't work.

As I know, parentheses operator can be used as RegEx capturing group or reference to the pattern. How to use the parentheses operator in these 2 cases at the same time?

What I want:

```<code>m.groups()[0] = "a"
m.groups()[1] = "bcdbcdbcd"
m.groups()[2] = "e"
</code>```

答:
The following regex should work (caveat below):

```<code>^(.*?)((.+?)\3+)(.*)
</code>```

Explanation:

^      # Start of string
(.*?)  # Match any number of characters, as few as possible, until...
(      # (Start capturing group #2)
 (.+?) # ... a string is matched (and captured in group #3)
 \3+   # that is repeated at least once.
)      # End of group #2
(.*)   # Match the rest of the string
```

Test it live on regex101.com.

Caveat: If the string is long and doesn't have any obvious repeats, this is going to have very bad performance characteristics (O(n!), I think), since the regex engine has to check each and every permutation of substrings. See catastrophic backtracking.

Title: Python Regex Capturing Group

Body:
string1 = "abcdbcdbcde"

I want to extract string1 into three parts:
(first part and third part can be empty string)

first part:  a

second part (repeitions of some string):  bcdbcdbcd

third part: e

import re

string1 = "abcdbcdbcde"
m = re.match("(.*)(.+){2,}(.*)", string1)
print m.groups()[0], m.groups()[1], m.groups()[2]

Of cuz, the code above doesn't work.

As I know, parentheses operator can be used as RegEx capturing group or reference to the pattern. How to use the parentheses operator in these 2 cases at the same time?

What I want:

m.groups()[0] = "a"
m.groups()[1] = "bcdbcdbcd"
m.groups()[2] = "e"

Body:
The following regex should work (caveat below):

^(.*?)((.+?)\3+)(.*)

Explanation:

^      # Start of string
(.*?)  # Match any number of characters, as few as possible, until...
(      # (Start capturing group #2)
 (.+?) # ... a string is matched (and captured in group #3)
 \3+   # that is repeated at least once.
)      # End of group #2
(.*)   # Match the rest of the string

Test it live on regex101.com.

Caveat: If the string is long and doesn't have any obvious repeats, this is going to have very bad performance characteristics (O(n!), I think), since the regex engine has to check each and every permutation of substrings. See catastrophic backtracking.


问:
Css Grid layout in mm (for printing)
I'm trying to create a grid layout to print items on a page. The units should be in millimeters but the result is far from correct.
I'm using css grid layout to use flow since my items are random count but should be displayed 2x8 on each page.

    @media all {
      @page {
        size: 210mm 297mm;
        margin-top: 18mm;
        margin-bottom: 18mm;
        margin-left: 4mm;
        margin-right: 4mm;
      }
      .passcodeCell {
        width: 100mm;
        height: 70mm;
        border-style: dashed;
        align-content: center;
        position: relative;
      }
      .passcodeGrid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-template-rows: 1fr 1fr 1fr 1fr;
        grid-column-gap: 3mm;
        align-items: center;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="passcodeGrid">
      <div class="passcodeCell"></div>
      <div class="passcodeCell"></div>
      <div class="passcodeCell"></div>
      <div class="passcodeCell"></div>
      <div class="passcodeCell"></div>
      <div class="passcodeCell"></div>
      <div class="passcodeCell"></div>
      <div class="passcodeCell"></div>
      <div class="passcodeCell"></div>
    </div></code>```

The result should be a grid 2x8 cells on a A4 page (210x297mm), each cells should be 100mmx70mm but I get a grid 2x5.9 with cells 70mmx50mm. I'm using Chrome.
What's wrong with my layout? Is it possible to define a precise layout for printing in CSS?

答:
set widths in the grid will help you</p>

```<code>.passcodeGrid {
  display: grid;
  grid-template-rows: repeat(4, 70mm);
  grid-template-columns: repeat(2, 100mm);
}
</code>```

Title: Css Grid layout in mm (for printing)

Body:
I'm trying to create a grid layout to print items on a page. The units should be in millimeters but the result is far from correct.
I'm using css grid layout to use flow since my items are random count but should be displayed 2x8 on each page.

    @media all {
      @page {
        size: 210mm 297mm;
        margin-top: 18mm;
        margin-bottom: 18mm;
        margin-left: 4mm;
        margin-right: 4mm;
      }
      .passcodeCell {
        width: 100mm;
        height: 70mm;
        border-style: dashed;
        align-content: center;
        position: relative;
      }
      .passcodeGrid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-template-rows: 1fr 1fr 1fr 1fr;
        grid-column-gap: 3mm;
        align-items: center;
      }

The result should be a grid 2x8 cells on a A4 page (210x297mm), each cells should be 100mmx70mm but I get a grid 2x5.9 with cells 70mmx50mm. I'm using Chrome.
What's wrong with my layout? Is it possible to define a precise layout for printing in CSS?

Body:
set widths in the grid will help you

.passcodeGrid {
  display: grid;
  grid-template-rows: repeat(4, 70mm);
  grid-template-columns: repeat(2, 100mm);
}


问:
NuxtJS routing error: Page not found when navigating to an existing route
Just started using Nuxt, and I love it so far. I just have one specific issue, I'm using prismic.io as headless CMS for my personal page. I have a few pages and a "blog" page. I'm having an issue when navigating to the blog route, it returns page not found. Now, it's kind of odd because it's working perfectly in my local host, it's just behaving that way when deployed.

Site's being deployed on Netlify.

I already tried switching the route's links and building the project on my local machine and it's working like charm.

Link to site:
https://wonderful-gates-27a024.netlify.com/

This is my file structure for the pages:

```<code>Pages/
-- blog/
---- _uid.vue
-- About.vue
-- Blog.vue
-- Contact.vue
-- Works.vue
-- index.vue
</code>```

Steps to replicate the issue

Navigate to about

Navigate to contact

Navigate to blog (Sometimes the error shows on this step)

Click on an article

Navigate back to the blog (here it should display not found)

Steps to navigate back to blog after the error shows up:

On the url bar, paste wonderful-gates-27a024.netlify.com/blog and hit enter.

I'm getting page not found error

答:
It works sometimes because you are navigating to

```<code>https://wonderful-gates-27a024.netlify.com/blog/
</code>```

Which is different from

```<code>https://wonderful-gates-27a024.netlify.com/blog
</code>```

the page which is /blog

```<code>https://wonderful-gates-27a024.netlify.com/blog
</code>```

doesn't exist while the page

```<code> https://wonderful-gates-27a024.netlify.com/blog/
</code>```

exists. which is /blog/_uid

so if you want it to work make

```<code>Pages/
-- blog/
---- _uid.vue
---- index.vue// make this file and the /blog will work
-- About.vue
-- Blog.vue
-- Contact.vue
-- Works.vue
-- index.vue
</code>```

Body:
Just started using Nuxt, and I love it so far. I just have one specific issue, I'm using prismic.io as headless CMS for my personal page. I have a few pages and a "blog" page. I'm having an issue when navigating to the blog route, it returns page not found. Now, it's kind of odd because it's working perfectly in my local host, it's just behaving that way when deployed.

Site's being deployed on Netlify.

I already tried switching the route's links and building the project on my local machine and it's working like charm.

Link to site:
https://wonderful-gates-27a024.netlify.com/

This is my file structure for the pages:

Pages/
-- blog/
---- _uid.vue
-- About.vue
-- Blog.vue
-- Contact.vue
-- Works.vue
-- index.vue

Steps to replicate the issue

Navigate to about

Navigate to contact

Navigate to blog (Sometimes the error shows on this step)

Click on an article

Navigate back to the blog (here it should display not found)

Steps to navigate back to blog after the error shows up:

On the url bar, paste wonderful-gates-27a024.netlify.com/blog and hit enter.

I'm getting page not found error

Body:
It works sometimes because you are navigating to

https://wonderful-gates-27a024.netlify.com/blog/

Which is different from

https://wonderful-gates-27a024.netlify.com/blog

the page which is /blog

https://wonderful-gates-27a024.netlify.com/blog

doesn't exist while the page

 https://wonderful-gates-27a024.netlify.com/blog/

exists. which is /blog/_uid

so if you want it to work make

Pages/
-- blog/
---- _uid.vue
---- index.vue// make this file and the /blog will work
-- About.vue
-- Blog.vue
-- Contact.vue
-- Works.vue
-- index.vue


问:
How can I get the real image value from each item in my list and subscribe it to another list?
I have a list of services that have multiple property like serviceId, serviceName and photoProfile called from a database using a spring REST API.

The 'photoProfile' property only has the id of the profile picture which if you use the 'localhost:8082/downloadFile/'+photoProfile would get you the image which is in turn is stored in a folder in the spring project.

After looking for a while online, I've found how I can actually get the real image to display on my website but now I'm stuck since I need to do this for the whole list.

Here's my angular code:

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginComponent } from '../login/login.component';
import { UserService } from '../user.service';
import { Observable, forkJoin } from 'rxjs';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { combineLatest } from 'rxjs/operators';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  loggedIn: boolean;
  services: any[] = [];
  imgSrc: any;
  newList: any[] = [];
  constructor(private router: Router, private service: UserService, private http: HttpClient) {
  }

  ngOnInit() {
    this.service.getServices().subscribe(res => {
    this.services = res;
    console.log('services: ', this.services);
});
    for (let i = 0; i < this.services.length; i++) {
      const element = this.services[i];
      this.getImage('http://localhost:4200/downloadFile/' + element.photoProfile).subscribe(data => {
      this.createImageFromBlob(data);
    });
    this.newList.push(this.imgSrc);
    console.log(this.newList);
    //I want to add the element from the services list and the image value after being converted to the new list
    }
  }

  getImage(imageUrl: string): Observable<Blob> {
    return this.http.get(imageUrl, {responseType: 'blob'});
  }

  createImageFromBlob(image: Blob) {
    const reader = new FileReader();
    reader.addEventListener('load', () => {
      this.imgSrc = reader.result;
    }, false);
    if (image) {
      reader.readAsDataURL(image);
    }
  }
}
</code>```

Thank you for your help.

答:
You need to add the new list inside the ngOnInit after you are subscribing to the services list. Because currently. You don't have the services when the for loop runs. You need to run the for loop after you have the result from services. Like this:</p>

```<code>ngOnInit() {
    this.service.getServices().subscribe(res => {
    this.services = res;
    console.log('services: ', this.services);

    for (let i = 0; i < this.services.length; i++) {
      const element = this.services[i];
      this.getImage('http://localhost:4200/downloadFile/' + element.photoProfile).subscribe(data => {
        this.createImageFromBlob(data);
        element.imgSrc = this.imgSrc;
        this.newList.push(element);
       });
    console.log(this.newList);
    }
  }
});
</code>```

Body:
I have a list of services that have multiple property like serviceId, serviceName and photoProfile called from a database using a spring REST API.

The 'photoProfile' property only has the id of the profile picture which if you use the 'localhost:8082/downloadFile/'+photoProfile would get you the image which is in turn is stored in a folder in the spring project.

After looking for a while online, I've found how I can actually get the real image to display on my website but now I'm stuck since I need to do this for the whole list.

Here's my angular code:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LoginComponent } from '../login/login.component';
import { UserService } from '../user.service';
import { Observable, forkJoin } from 'rxjs';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { combineLatest } from 'rxjs/operators';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  loggedIn: boolean;
  services: any[] = [];
  imgSrc: any;
  newList: any[] = [];
  constructor(private router: Router, private service: UserService, private http: HttpClient) {
  }

  ngOnInit() {
    this.service.getServices().subscribe(res => {
    this.services = res;
    console.log('services: ', this.services);
});
    for (let i = 0; i < this.services.length; i++) {
      const element = this.services[i];
      this.getImage('http://localhost:4200/downloadFile/' + element.photoProfile).subscribe(data => {
      this.createImageFromBlob(data);
    });
    this.newList.push(this.imgSrc);
    console.log(this.newList);
    //I want to add the element from the services list and the image value after being converted to the new list
    }
  }

  getImage(imageUrl: string): Observable<Blob> {
    return this.http.get(imageUrl, {responseType: 'blob'});
  }

  createImageFromBlob(image: Blob) {
    const reader = new FileReader();
    reader.addEventListener('load', () => {
      this.imgSrc = reader.result;
    }, false);
    if (image) {
      reader.readAsDataURL(image);
    }
  }
}

Thank you for your help.

Body:
You need to add the new list inside the ngOnInit after you are subscribing to the services list. Because currently. You don't have the services when the for loop runs. You need to run the for loop after you have the result from services. Like this:

ngOnInit() {
    this.service.getServices().subscribe(res => {
    this.services = res;
    console.log('services: ', this.services);

    for (let i = 0; i < this.services.length; i++) {
      const element = this.services[i];
      this.getImage('http://localhost:4200/downloadFile/' + element.photoProfile).subscribe(data => {
        this.createImageFromBlob(data);
        element.imgSrc = this.imgSrc;
        this.newList.push(element);
       });
    console.log(this.newList);
    }
  }
});


问:
Problem with BS4 printing only certain parts of the web page
I am having a problem with bs4 only finding some things in html. To be specific when I try to print span.nav2__menu-link-main-text it selects it and prints it without a problem but when I try to select other part of the page it probably selects it but It doesnt want to print it out. Here is the code that prints and the code that doesnt print:

Tried using different parsers other than lxml and none worked.

```<code>#This one prints

from bs4 import BeautifulSoup
import requests
import lxml

url = 'https://osu.ppy.sh/users/18723891'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

for i in soup.select('span.nav2__menu-link-main-text'):
    print(i.text)

#This one does not print

from bs4 import BeautifulSoup
import requests
import lxml

url = 'https://osu.ppy.sh/users/https://osu.ppy.sh/users/18723891'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

for i in soup.select('div.value-dispaly__value'):
    print(i.text)
</code>```

I expect this program to print the current value of div.value-dispaly__value
but when I start the program it prints nothing even tough I can see the value is 4000 when I inspect the page.

答:
Website page is javascript request rendering to get data, so you need to use automation library like selenium. download selenium web driver as per your browser requirement.

Download selenium web driver for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

https://christopher.su/2015/selenium-chromedriver-ubuntu/

Selenium tutorial:

https://selenium-python.readthedocs.io/

Replace your code to this:

```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://osu.ppy.sh/users/12008062')
time.sleep(3)

soup = BeautifulSoup(driver.page_source, 'lxml')

for i in soup.find_all('div',{"class":"value-display__value"}):
    print(i.get_text())
</code>```

O/P:

```<code>#47,514
#108
11d 19h 49m
44
4,000
11d 19h 49m
44
4,000
#47,514
#108
0
0
</code>```

Body:
I am having a problem with bs4 only finding some things in html. To be specific when I try to print span.nav2__menu-link-main-text it selects it and prints it without a problem but when I try to select other part of the page it probably selects it but It doesnt want to print it out. Here is the code that prints and the code that doesnt print:

Tried using different parsers other than lxml and none worked.

#This one prints

from bs4 import BeautifulSoup
import requests
import lxml

url = 'https://osu.ppy.sh/users/18723891'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

for i in soup.select('span.nav2__menu-link-main-text'):
    print(i.text)

#This one does not print

from bs4 import BeautifulSoup
import requests
import lxml

url = 'https://osu.ppy.sh/users/https://osu.ppy.sh/users/18723891'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'lxml')

for i in soup.select('div.value-dispaly__value'):
    print(i.text)

I expect this program to print the current value of div.value-dispaly__value
but when I start the program it prints nothing even tough I can see the value is 4000 when I inspect the page.

Body:
Website page is javascript request rendering to get data, so you need to use automation library like selenium. download selenium web driver as per your browser requirement.

Download selenium web driver for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

https://christopher.su/2015/selenium-chromedriver-ubuntu/

Selenium tutorial:

https://selenium-python.readthedocs.io/

Replace your code to this:

from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://osu.ppy.sh/users/12008062')
time.sleep(3)

soup = BeautifulSoup(driver.page_source, 'lxml')

for i in soup.find_all('div',{"class":"value-display__value"}):
    print(i.get_text())

O/P:

#47,514
#108
11d 19h 49m
44
4,000
11d 19h 49m
44
4,000
#47,514
#108
0
0


问:
username of google cloud instance - where to find out
My gmail account I used to create my google cloud instance is johnsmith@gmail.com.

When I tried to connect to instance with WinSCP using "johnsmith" it failed, but it worked with "JOHN.SMITH"?  Where can I find out my exact username for google cloud instance?

UPDATE. I tried web-based SSH and typed whoami, it returned "johnsmith". "john.smith" is my windows local username. It is all very confusing.

ANOTHER UPDATE: My google cloud instance is Ubuntu 16.04 and I am connecting from Windows 7 local machine

P.S. I made up the name, but preserved format for this question.

P.S.S SO does not let me post because I don't meet their standard. Here is some bogus code to meet the standard:

```<code>print("Hello, World!")
</code>```

答:
Under Cloud Shell Session:

gcloud compute os-login describe-profile

You will see your username.

Body:
My gmail account I used to create my google cloud instance is johnsmith@gmail.com.

When I tried to connect to instance with WinSCP using "johnsmith" it failed, but it worked with "JOHN.SMITH"?  Where can I find out my exact username for google cloud instance?

UPDATE. I tried web-based SSH and typed whoami, it returned "johnsmith". "john.smith" is my windows local username. It is all very confusing.

ANOTHER UPDATE: My google cloud instance is Ubuntu 16.04 and I am connecting from Windows 7 local machine

P.S. I made up the name, but preserved format for this question.

P.S.S SO does not let me post because I don't meet their standard. Here is some bogus code to meet the standard:

print("Hello, World!")


问:
Erlang: whether two lists have a common element
```<code>a = [1, 2, 3],
b = [4, 5, 6],
c = [1, 7, 8],
</code>```

has_common_element(a, b) is false since there are no common elements between the two arrays.

has_common_element(a, c) is true since there is at least one common element (1) between the two arrays.

I can use lists:member to check whether a single element is in the list. How do I implement has_common_element in Erlang to check whether two lists have a common element?

答:
Both @bxdoan and @choroba solutions work and are very concise. You do not give information about the size of the lists and their content, and it may be important.

The solution with list comprehension tests a list which size is the cross product of the 2 input list and thus gets very slow with big input lists. The solution with sets grows less faster. I propose you another one, less concise, but which behaves better for longer lists. I also add a solution using lists:member (not efficient) and another using maps (similar to sort).

```<code>-module (inter).

-export ([test/2,s1/2,s2/2,s3/2,s4/2,s5/2]).

test(Method,Size) ->
    A = [rand:uniform(Size*10000) || _ <- lists:duplicate(Size, 0)],
    % B may contain common element with A
    B = [rand:uniform(Size*10000) || _ <- lists:duplicate(Size, 0)],
    % C is by construction disjoint with A
    C = [rand:uniform(Size*10000)+Size*10000 || _ <- lists:duplicate(Size, 0)],
    io:format("test algorithm ~s~n",[method(Method)]),
    {test(Method,A,B),test(Method,A,C)}.

test(M,L1,L2) ->
    timer:tc(?MODULE, M, [L1,L2]).

method(s1) ->
    "List comprehension";
method(s2) ->
    "List sorted";
method(s3) ->
    "List to set";
method(s4) ->
    "List to map";
method(s5) ->
    "lists:member".

s1(L1,L2) ->
    [] =/= [X || X <- L1, Y <- L2, X =:= Y].

s2(L1,L2) ->
    s2_help(lists:sort(L1),lists:sort(L2)).

s2_help([],_) -> false;
s2_help(_,[]) -> false;
s2_help([_A|_],[_A|_]) -> true;
s2_help([H1|T1],[H2|T2]) when H1 > H2 -> s2_help([H1|T1],T2);
s2_help(L1,L2) -> s2_help(tl(L1),L2).

s3(L1,L2) ->
    not(sets:is_disjoint(sets:from_list(L1), sets:from_list(L2))).

s4(L1,L2) ->
    s4_help(lists:foldl(fun(X,Acc) -> maps:put(X, 0, Acc) end,#{},L1),L2).

s4_help(_,[]) -> false;
s4_help(Map,[H|T]) ->
    case maps:is_key(H, Map) of
        true -> true;
        false -> s4_help(Map,T)
    end.

s5([],_) -> false;
s5([H|T],L2) ->
    case lists:member(H, L2) of
        true -> true;
        false -> s5(T,L2)
    end.
</code>```

and then the results:

```<code>55> c(inter).
{ok,inter}
56> inter:test(s1,100).
test algorithm List comprehension
{{0,false},{0,false}}
57> inter:test(s2,100).
test algorithm List sorted
{{0,false},{0,false}}
58> inter:test(s3,100).
test algorithm List to set
{{0,false},{0,false}}
59> inter:test(s1,1000).
test algorithm List comprehension
{{16000,true},{0,false}}
60> inter:test(s2,1000).
test algorithm List sorted
{{0,false},{0,false}}
61> inter:test(s3,1000).
test algorithm List to set
{{0,false},{0,false}}
62> inter:test(s1,10000).
test algorithm List comprehension
{{468999,false},{484000,false}}
63> inter:test(s2,10000).
test algorithm List sorted
{{15000,false},{0,false}}
64> inter:test(s3,10000).
test algorithm List to set
{{31000,false},{32000,false}}
65> inter:test(s1,100000).
test algorithm List comprehension
{{48515953,true},{48030953,false}}
66> inter:test(s2,100000).
test algorithm List sorted
{{62000,true},{78000,false}}
67> inter:test(s3,100000).
test algorithm List to set
{{1233999,true},{1296999,false}}
...
69> inter:test(s4,100).
test algorithm List to map
{{0,false},{0,false}}
70> inter:test(s4,1000).
test algorithm List to map
{{0,false},{0,false}}
71> inter:test(s4,10000).
test algorithm List to map
{{0,false},{16000,false}}
72> inter:test(s4,100000).
test algorithm List to map
{{62000,true},{78000,false}}
73> inter:test(s5,100).
test algorithm lists:member
{{0,false},{0,false}}
74> inter:test(s5,1000).
test algorithm lists:member
{{0,false},{0,false}}
75> inter:test(s5,10000).
test algorithm lists:member
{{31000,true},{171999,false}}
76> inter:test(s5,100000).
test algorithm lists:member
{{921000,true},{19031980,false}}
77>
</code>```

Body:
a = [1, 2, 3],
b = [4, 5, 6],
c = [1, 7, 8],

has_common_element(a, b) is false since there are no common elements between the two arrays.

has_common_element(a, c) is true since there is at least one common element (1) between the two arrays.

I can use lists:member to check whether a single element is in the list. How do I implement has_common_element in Erlang to check whether two lists have a common element?

Body:
Both @bxdoan and @choroba solutions work and are very concise. You do not give information about the size of the lists and their content, and it may be important.

The solution with list comprehension tests a list which size is the cross product of the 2 input list and thus gets very slow with big input lists. The solution with sets grows less faster. I propose you another one, less concise, but which behaves better for longer lists. I also add a solution using lists:member (not efficient) and another using maps (similar to sort).

-module (inter).

-export ([test/2,s1/2,s2/2,s3/2,s4/2,s5/2]).

test(Method,Size) ->
    A = [rand:uniform(Size*10000) || _ <- lists:duplicate(Size, 0)],
    % B may contain common element with A
    B = [rand:uniform(Size*10000) || _ <- lists:duplicate(Size, 0)],
    % C is by construction disjoint with A
    C = [rand:uniform(Size*10000)+Size*10000 || _ <- lists:duplicate(Size, 0)],
    io:format("test algorithm ~s~n",[method(Method)]),
    {test(Method,A,B),test(Method,A,C)}.

test(M,L1,L2) ->
    timer:tc(?MODULE, M, [L1,L2]).

method(s1) ->
    "List comprehension";
method(s2) ->
    "List sorted";
method(s3) ->
    "List to set";
method(s4) ->
    "List to map";
method(s5) ->
    "lists:member".

s1(L1,L2) ->
    [] =/= [X || X <- L1, Y <- L2, X =:= Y].

s2(L1,L2) ->
    s2_help(lists:sort(L1),lists:sort(L2)).

s2_help([],_) -> false;
s2_help(_,[]) -> false;
s2_help([_A|_],[_A|_]) -> true;
s2_help([H1|T1],[H2|T2]) when H1 > H2 -> s2_help([H1|T1],T2);
s2_help(L1,L2) -> s2_help(tl(L1),L2).

s3(L1,L2) ->
    not(sets:is_disjoint(sets:from_list(L1), sets:from_list(L2))).

s4(L1,L2) ->
    s4_help(lists:foldl(fun(X,Acc) -> maps:put(X, 0, Acc) end,#{},L1),L2).

s4_help(_,[]) -> false;
s4_help(Map,[H|T]) ->
    case maps:is_key(H, Map) of
        true -> true;
        false -> s4_help(Map,T)
    end.

s5([],_) -> false;
s5([H|T],L2) ->
    case lists:member(H, L2) of
        true -> true;
        false -> s5(T,L2)
    end.

and then the results:

55> c(inter).
{ok,inter}
56> inter:test(s1,100).
test algorithm List comprehension
{{0,false},{0,false}}
57> inter:test(s2,100).
test algorithm List sorted
{{0,false},{0,false}}
58> inter:test(s3,100).
test algorithm List to set
{{0,false},{0,false}}
59> inter:test(s1,1000).
test algorithm List comprehension
{{16000,true},{0,false}}
60> inter:test(s2,1000).
test algorithm List sorted
{{0,false},{0,false}}
61> inter:test(s3,1000).
test algorithm List to set
{{0,false},{0,false}}
62> inter:test(s1,10000).
test algorithm List comprehension
{{468999,false},{484000,false}}
63> inter:test(s2,10000).
test algorithm List sorted
{{15000,false},{0,false}}
64> inter:test(s3,10000).
test algorithm List to set
{{31000,false},{32000,false}}
65> inter:test(s1,100000).
test algorithm List comprehension
{{48515953,true},{48030953,false}}
66> inter:test(s2,100000).
test algorithm List sorted
{{62000,true},{78000,false}}
67> inter:test(s3,100000).
test algorithm List to set
{{1233999,true},{1296999,false}}
...
69> inter:test(s4,100).
test algorithm List to map
{{0,false},{0,false}}
70> inter:test(s4,1000).
test algorithm List to map
{{0,false},{0,false}}
71> inter:test(s4,10000).
test algorithm List to map
{{0,false},{16000,false}}
72> inter:test(s4,100000).
test algorithm List to map
{{62000,true},{78000,false}}
73> inter:test(s5,100).
test algorithm lists:member
{{0,false},{0,false}}
74> inter:test(s5,1000).
test algorithm lists:member
{{0,false},{0,false}}
75> inter:test(s5,10000).
test algorithm lists:member
{{31000,true},{171999,false}}
76> inter:test(s5,100000).
test algorithm lists:member
{{921000,true},{19031980,false}}
77>


问:
Regex in PHP expecting to match strings like "${string}" not working
I’ve got:

```<code>$ap=0;
$matches=array();
d($ap, $vv[$value],$matches);
$ap = preg_match("/\$[({].+[)}]/", $vv[$value], $matches);
d($ap, $vv[$value],$matches);
</code>```

d() is a custom function like var_dump().

When $vv[$value] is "exec_prefix = ${prefix}", why is that $ap is 0, and there’s no matches ($matches is still an empty array)?

I am expecting "${prefix}" to be matched.

I tried the regex in regexpal.com and it matches too.

答:
In your regex, you are trying to use $ as the start of field marker.  As PHP needs the $ to be escaped otherwise it will think it's introducing a variable substitution (in double quotes) it will use the \ you've included for this purpose.  BUT this then leaves the regex as

```<code>/$[({].+[)}]/
</code>```

and this means it will use the $ as the end of string marker - and therefore not find the content your after.

So, you need a second escape before the dollar to make sure it is picked up properly...

```<code>$ap = preg_match("/\\$[({].+[)}]/", $vv[$value], $matches);
</code>```

Body:
I’ve got:

$ap=0;
$matches=array();
d($ap, $vv[$value],$matches);
$ap = preg_match("/\$[({].+[)}]/", $vv[$value], $matches);
d($ap, $vv[$value],$matches);

d() is a custom function like var_dump().

When $vv[$value] is "exec_prefix = ${prefix}", why is that $ap is 0, and there’s no matches ($matches is still an empty array)?

I am expecting "${prefix}" to be matched.

I tried the regex in regexpal.com and it matches too.

Body:
In your regex, you are trying to use $ as the start of field marker.  As PHP needs the $ to be escaped otherwise it will think it's introducing a variable substitution (in double quotes) it will use the \ you've included for this purpose.  BUT this then leaves the regex as

/$[({].+[)}]/

and this means it will use the $ as the end of string marker - and therefore not find the content your after.

So, you need a second escape before the dollar to make sure it is picked up properly...

$ap = preg_match("/\\$[({].+[)}]/", $vv[$value], $matches);


问:
ERROR: ssh: Could not resolve hostname knode: Temporary failure in name resolution
I have already got the ssh key but when I am trying to copy the ssh key to my node I am getting error in copying that key.

I have already tried to do that in root user and also tried many other methods but none of it worked.

I have tried the command:

```<code>sudo-copy-id -i knode
</code>```

Using this command the key must have been copied to my node.

But I am getting this error:

```<code>/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/moglix/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: ERROR: ssh: Could not resolve hostname knode: Temporary failure in name resolution
</code>```

答:
host name knode is not resolving, use fully qualified domain name or check why host name is not resolving.
You can are an entry in /etc/host file for "knode" with ip as workaround  </p>

Body:
I have already got the ssh key but when I am trying to copy the ssh key to my node I am getting error in copying that key.

I have already tried to do that in root user and also tried many other methods but none of it worked.

I have tried the command:

sudo-copy-id -i knode

Using this command the key must have been copied to my node.

But I am getting this error:

/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/moglix/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: ERROR: ssh: Could not resolve hostname knode: Temporary failure in name resolution


问:
How to remove Cache-control header no-cache
My team and I are working on a Laravel API which communicates with a Vue.js frontend that uses the Apollo client to consume the GraphQL responses.

We have an issue with cache-control headers being added to the response.

Apollo cannot cache the contents because the response contains this header:

```<code>Cache-Control: no-cache, private
</code>```

In php.ini, we have this to disable sending cache-control headers by PHP:

```<code>; Set to {nocache,private,public,} to determine HTTP caching aspects
; or leave this empty to avoid sending anti-caching headers.
; http://php.net/session.cache-limiter
session.cache_limiter =
</code>```

In the nginx config we cannot find anything that is setting those headers. I checked the global nginx.conf and config file we setup in sites/available.

I can add this to the nginx config, but it will only add another header:

```<code>add_header Cache-Control "public";

Cache-Control: no-cache, private
Cache-Control: public
</code>```

If this header is not coming from PHP or nginx, then where could it be coming from?
And how can I remove or overwrite it?

Laravel 5.5

Folkloreatelier/laravel-graphql

PHP 7.1

nginx 1.14.0

Ubuntu 16.04

答:
you can do this by Adding in your .htaccess if you are using apache

```<code>Header always set Cache-Control "no-cache, public"
</code>```

so it will remove the Cache-Control:private
and give the header response as

```<code>Cache-Control:no-cache , public
</code>```

Body:
My team and I are working on a Laravel API which communicates with a Vue.js frontend that uses the Apollo client to consume the GraphQL responses.

We have an issue with cache-control headers being added to the response.

Apollo cannot cache the contents because the response contains this header:

Cache-Control: no-cache, private

In php.ini, we have this to disable sending cache-control headers by PHP:

; Set to {nocache,private,public,} to determine HTTP caching aspects
; or leave this empty to avoid sending anti-caching headers.
; http://php.net/session.cache-limiter
session.cache_limiter =

In the nginx config we cannot find anything that is setting those headers. I checked the global nginx.conf and config file we setup in sites/available.

I can add this to the nginx config, but it will only add another header:

add_header Cache-Control "public";

Cache-Control: no-cache, private
Cache-Control: public

If this header is not coming from PHP or nginx, then where could it be coming from?
And how can I remove or overwrite it?

Laravel 5.5

Folkloreatelier/laravel-graphql

PHP 7.1

nginx 1.14.0

Ubuntu 16.04

Body:
you can do this by Adding in your .htaccess if you are using apache

Header always set Cache-Control "no-cache, public"

so it will remove the Cache-Control:private
and give the header response as

Cache-Control:no-cache , public


问:
How to do Led blink with each port, using stm32 (stm32f103c8t6) boards and Adruino
I am completely new to this and willing to do a simple task using stm32f103c8t6 board, which is "led blink".

Using ArduinoIDE and a simple circuit as shown in the picture, everything goes fine on port PC13. but as soon as I try other ports, it doesn't work.
My aim is to be able to toggle the led status using ports PA0 to PA5.

Here is my code:

```<code>void setup() {
  // initialize the digital pin as an output.
  pinMode(PC13, OUTPUT);
}

void loop() {
  digitalWrite(PC13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(PC13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}
</code>```

I change PC13 to PA0, and rewire the board, but no luck :(

How can I solve this issue.
Any kind of help is highly appreciated.

答: Sorry for the stupid question. My problem was that I had a broken wire,and when I changed it, everything was working fine. </p>

Body:
I am completely new to this and willing to do a simple task using stm32f103c8t6 board, which is "led blink".

Using ArduinoIDE and a simple circuit as shown in the picture, everything goes fine on port PC13. but as soon as I try other ports, it doesn't work.
My aim is to be able to toggle the led status using ports PA0 to PA5.

Here is my code:

void setup() {
  // initialize the digital pin as an output.
  pinMode(PC13, OUTPUT);
}

void loop() {
  digitalWrite(PC13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(PC13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

I change PC13 to PA0, and rewire the board, but no luck :(

How can I solve this issue.
Any kind of help is highly appreciated.


问:
Virtal Assistant throwing 'Sorry it looks like something went wrong'
I have created a virtual assistant using the Microsoft virtual assistant template. When testing in the emulator whatever message i send i am getting a 'something went wrong reply.'

I am new to the entire bot framework ecosystem and it is becoming very difficult to proceed.

In the log what i can see is:

```<code>    [11:26:32]Emulator listening on http://localhost:65233
[11:26:32]ngrok not configured (only needed when connecting to remotely hosted bots)
[11:26:32]Connecting to bots hosted remotely
[11:26:32]Edit ngrok settings
[11:26:32]POST201directline.startConversation
[11:26:39]<-messageapplication/vnd.microsoft.card.adaptive
[11:26:39]POST200conversations.replyToActivity
[11:26:54]->messagehi
[11:26:55]<-traceThe given key 'en' was not present in the dictiona...
[11:26:55]POST200conversations.replyToActivity
[11:26:55]<-trace at System.Collections.Generic.Dictionary`2.get_...
[11:26:55]POST200conversations.replyToActivity
[11:26:55]<-messageSorry, it looks like something went wrong.
[11:26:55]POST200conversations.replyToActivity
[11:26:55]POST200directline.postActivity
[11:27:48]->messagehello
[11:27:48]<-traceThe given key 'en' was not present in the dictiona...
[11:27:48]POST200conversations.replyToActivity
[11:27:48]<-trace at System.Collections.Generic.Dictionary`2.get_...
[11:27:48]POST200conversations.replyToActivity
[11:27:48]<-messageSorry, it looks like something went wrong.
[11:27:48]POST200conversations.replyToActivity
[11:27:48]POST200directline.postActivity
</code>```

From what I understood the 'en' is not present in dictionary and I am not sure what is means. I checked in the Responses folder and could not see an en file not sure if that is the issue:

My emulator screenshot is attached:

Any help would be useful.

答:
I believe the issue you are experiencing is a problem on the following lines inside MainDialog.cs:

```<code>var locale = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
var cognitiveModels = _services.CognitiveModelSets[locale];
</code>```

This tries to use the locale (retrieved from the current thread as per this documentation) as the key to access the cognitive models in your cognitivemodels.json file.

Inside your cognitivemodels.json file it should look like:

```<code>{
  "cognitiveModels": {
    // This line below here is what could be missing/incorrect in yours
    "en": {
      "dispatchModel": {
        "type": "dispatch",
        "region": "westus",
        ...
      },
      "knowledgebases": [
        {
          "id": "chitchat",
          "name": "chitchat",
          ...
        },
        {
          "id": "faq",
          "name": "faq",
          ...
        },
      ],
      "languageModels": [
        {
          "id": "general",
          "name": "msag-test-va-boten_general",
          "region": "westus",
          ...
        }
      ]
    }
  },
  "defaultLocale": "en-us"
}

</code>```

The en key insides the cognitiveModels object is what the code is trying to use to retrieve your cognitive models, thus if the locale pulled out in the code doesn't match the locale keys in your cognitivemodels.json then you will get the dictionary key error.

EDIT

The issue the OP has was a failed deploy. The steps we took were to:

Checked the deploy_log.txt inside the Deployment folder for errors.

If this case it was empty - not a good sign.

Checked the deploy_cognitive_models_log.txt inside the Deployment folder for errors.

There was an error present Error: Cannot find module 'C:\Users\dip_chatterjee\AppData\Roaming\npm\node_modules\botdispatch\bin\dispatch.js.

To fix this error we reinstalled all of the required npm packages as per step 5 of this guide then ran the deploy script as per this guide.

Body:
I have created a virtual assistant using the Microsoft virtual assistant template. When testing in the emulator whatever message i send i am getting a 'something went wrong reply.'

I am new to the entire bot framework ecosystem and it is becoming very difficult to proceed.

In the log what i can see is:

    [11:26:32]Emulator listening on http://localhost:65233
[11:26:32]ngrok not configured (only needed when connecting to remotely hosted bots)
[11:26:32]Connecting to bots hosted remotely
[11:26:32]Edit ngrok settings
[11:26:32]POST201directline.startConversation
[11:26:39]<-messageapplication/vnd.microsoft.card.adaptive
[11:26:39]POST200conversations.replyToActivity
[11:26:54]->messagehi
[11:26:55]<-traceThe given key 'en' was not present in the dictiona...
[11:26:55]POST200conversations.replyToActivity
[11:26:55]<-trace at System.Collections.Generic.Dictionary`2.get_...
[11:26:55]POST200conversations.replyToActivity
[11:26:55]<-messageSorry, it looks like something went wrong.
[11:26:55]POST200conversations.replyToActivity
[11:26:55]POST200directline.postActivity
[11:27:48]->messagehello
[11:27:48]<-traceThe given key 'en' was not present in the dictiona...
[11:27:48]POST200conversations.replyToActivity
[11:27:48]<-trace at System.Collections.Generic.Dictionary`2.get_...
[11:27:48]POST200conversations.replyToActivity
[11:27:48]<-messageSorry, it looks like something went wrong.
[11:27:48]POST200conversations.replyToActivity
[11:27:48]POST200directline.postActivity

From what I understood the 'en' is not present in dictionary and I am not sure what is means. I checked in the Responses folder and could not see an en file not sure if that is the issue:

My emulator screenshot is attached:

Any help would be useful.

Body:
I believe the issue you are experiencing is a problem on the following lines inside MainDialog.cs:

var locale = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
var cognitiveModels = _services.CognitiveModelSets[locale];

This tries to use the locale (retrieved from the current thread as per this documentation) as the key to access the cognitive models in your cognitivemodels.json file.

Inside your cognitivemodels.json file it should look like:

{
  "cognitiveModels": {
    // This line below here is what could be missing/incorrect in yours
    "en": {
      "dispatchModel": {
        "type": "dispatch",
        "region": "westus",
        ...
      },
      "knowledgebases": [
        {
          "id": "chitchat",
          "name": "chitchat",
          ...
        },
        {
          "id": "faq",
          "name": "faq",
          ...
        },
      ],
      "languageModels": [
        {
          "id": "general",
          "name": "msag-test-va-boten_general",
          "region": "westus",
          ...
        }
      ]
    }
  },
  "defaultLocale": "en-us"
}

The en key insides the cognitiveModels object is what the code is trying to use to retrieve your cognitive models, thus if the locale pulled out in the code doesn't match the locale keys in your cognitivemodels.json then you will get the dictionary key error.

EDIT

The issue the OP has was a failed deploy. The steps we took were to:

Checked the deploy_log.txt inside the Deployment folder for errors.

If this case it was empty - not a good sign.

Checked the deploy_cognitive_models_log.txt inside the Deployment folder for errors.

There was an error present Error: Cannot find module 'C:\Users\dip_chatterjee\AppData\Roaming\npm\node_modules\botdispatch\bin\dispatch.js.

To fix this error we reinstalled all of the required npm packages as per step 5 of this guide then ran the deploy script as per this guide.


问:
Reliability of using HEAD Request to Check Web Page Status
I've been testing a small app I've written that basically does a http HEAD request to check whether a page exists, redirects etc. I've noticed that some pages respond differently to HEAD than GET requests. For example:

```<code>curl -I http://www.youtube.com/bbcpersian
</code>```

returns a 404. It's definitely there. Some (quite major) sites even return 500 errors in response to a HEAD - which I'm guessing isn't deliberate.

So my questions are:

Is there any good reason why certain sites (or pages within sites) would behave like this other than configuration issues or a web master wanting to block bots?

If I can't rely on a HEAD request am I just left with doing a GET and aborting the request once I have the headers. That feels a bit "wrong" …

While the number of pages that behave like this is small in % terms each false positive is ultimately manually investigated which results in a lot of wasted effort.

答:
The URL you are trying:
http://www.youtube.com/bbcpersian
is not the correct URL and thus it gives 404.

The correct URL is:
https://www.youtube.com/user/BBCPersian and it gives 200.

Body:
I've been testing a small app I've written that basically does a http HEAD request to check whether a page exists, redirects etc. I've noticed that some pages respond differently to HEAD than GET requests. For example:

curl -I http://www.youtube.com/bbcpersian

returns a 404. It's definitely there. Some (quite major) sites even return 500 errors in response to a HEAD - which I'm guessing isn't deliberate.

So my questions are:

Is there any good reason why certain sites (or pages within sites) would behave like this other than configuration issues or a web master wanting to block bots?

If I can't rely on a HEAD request am I just left with doing a GET and aborting the request once I have the headers. That feels a bit "wrong" …

While the number of pages that behave like this is small in % terms each false positive is ultimately manually investigated which results in a lot of wasted effort.


问:
How to find if a document is a good match for a query, e.g., normalize elasticsearch score?
The score computed by Elasticsearch provides a ranking between the documents, but it does not tell if the documents are a good match for the request. Currently, the first document can either match on all fields or just one. The only information that the score provides is that it is the best match.

Would it be possible to get a normalized score with respect to the query ? For example, a score of 1 would be a document matching perfectly the query and a score of 0.1 a document matching poorly.

答:
In short, no, it is not possible to get a real normalized score for a query, but it is possible to get a good enough score normalization that works in many cases.

The problem to get a score that tells if the document is a good match or not for a query is to find what would be the best document for this query, and consequently the maximum score. Using elasticsearch and most (if not all) metrics, the maximum score is not bounded.

Even with a simple match query, you can technically reach an infinite score with a document that repeat the queried term an infinite number of time. Without bound on the score, it is not possible to get a true normalized score.

But all hopes are not lost. Instead of normalizing against the best possible score you can normalize against a fake ideal document which is supposed to get the maximum score. For example, if you are querying two fields name and occupation with queried terms Jane Doe and Cook your ideal document can be

```<code>{
    "name": "Jane Doe",
    "occupation": "Cook"
}
</code>```

If the index contains a document with for example the name Jane Jane Doe then the ideal document may not get the maximum score. If the queried fields are relatively short, you probably do not have to worry about term duplication. If you have fields with many terms you may decide to duplicate some terms which are frequent in the ideal document. If the objective is to find if the document is a good match or not, it is usually not a problem to have a document scored higher than the ideal document.

The good news is that if you are using at least elasticsearch 6.4 you do not have to index the fake document to get its score for a query. You may use the endpoint _scripts/painless/_execute to obtain the score of the ideal document.

```<code>GET _scripts/painless/_execute
{
    "script": {
        "source": "_score"
    },
    "context": "score",
    "context_setup": {
        "index": <INDEX>,
        "document": <THE_IDEAL_DOCUMENT>,
        "query": <YOUR_QUERY>
    }
}
</code>```

Please note that the fields statistics of the fake document such as the number of documents containing a field and the number of fields containing the queried term will be taken into account when computing the score. If you have many documents, this should not be a problem, but for very not frequent field or term (say below 20) you can notice a lower score for the ideal document compared to a previously indexed document.

Body:
In short, no, it is not possible to get a real normalized score for a query, but it is possible to get a good enough score normalization that works in many cases.

The problem to get a score that tells if the document is a good match or not for a query is to find what would be the best document for this query, and consequently the maximum score. Using elasticsearch and most (if not all) metrics, the maximum score is not bounded.

Even with a simple match query, you can technically reach an infinite score with a document that repeat the queried term an infinite number of time. Without bound on the score, it is not possible to get a true normalized score.

But all hopes are not lost. Instead of normalizing against the best possible score you can normalize against a fake ideal document which is supposed to get the maximum score. For example, if you are querying two fields name and occupation with queried terms Jane Doe and Cook your ideal document can be

{
    "name": "Jane Doe",
    "occupation": "Cook"
}

If the index contains a document with for example the name Jane Jane Doe then the ideal document may not get the maximum score. If the queried fields are relatively short, you probably do not have to worry about term duplication. If you have fields with many terms you may decide to duplicate some terms which are frequent in the ideal document. If the objective is to find if the document is a good match or not, it is usually not a problem to have a document scored higher than the ideal document.

The good news is that if you are using at least elasticsearch 6.4 you do not have to index the fake document to get its score for a query. You may use the endpoint _scripts/painless/_execute to obtain the score of the ideal document.

GET _scripts/painless/_execute
{
    "script": {
        "source": "_score"
    },
    "context": "score",
    "context_setup": {
        "index": <INDEX>,
        "document": <THE_IDEAL_DOCUMENT>,
        "query": <YOUR_QUERY>
    }
}

Please note that the fields statistics of the fake document such as the number of documents containing a field and the number of fields containing the queried term will be taken into account when computing the score. If you have many documents, this should not be a problem, but for very not frequent field or term (say below 20) you can notice a lower score for the ideal document compared to a previously indexed document.


问:
How to optimize knex migration?
i'm working on a project that has been using bookshelfjs (with knexjs migration system) since its beginning (1 year and a half).
We now have a little bit less than 80 migrations and it's starting to take a lot of time (more than 2 minutes) to run all migrations. We are deploying using continuous integration so the migrations have to be run in the test process and in the deployment process.

I'd like to know how to optimize that. Is that possible to start from a clean state ? I don't care about losing rollback possibilities. The project is much more mature right now and we don't need to iterate much anymore on the data structure part.

Is there any best practice ? I'm coming from the Doctrine (PHP) world and it's really different.

Thanks for your advice !

答: When using knex.schema.createTable to create table with foregin keys from another table, and later when you run knex migrate:latest, the table with foreign keys should be processed before the one using the foreign keys. For example, table1 has foreign key key1 from talbe2, to make sure table2 is processed first, you can add numbers before the name of the table. Then in your migrations folder, there will be 1table2.js, 2table1.js. This looks hacky and not pretty, but it works!

Title: How to optimize knex migration?


问:
Sourcetree change password of existing account
I use Sourcetree to pull and push to a server over ssh. Sourcetree has remembered the password but the password has changed. I cannot find how to inform Sourcetree of the new password.

Based on Google searches, I have tried the following things:

Looked under Tools > Options > Authentication in Sourcetree. Nothing is listed here.

Looked in the Windows Credential Manager in the Control Panel. Nothing related to git/Sourcetree or the server in question is listed here either.

I am using Sourcetree 2.0.18.1

Update

I have been circumventing this problem by using key based authentication through pageant. In the meantime, there have also been updates to Sourcetree and I'm currently using 2.3.1 for which editing/removing the %LOCALAPPDATA%\Atlassian\SourceTree\passwd file works (2.0.18 didn't have that file).

答:
For Mac given steps can help you...

Got to the folder ~/Library/Application Support/SourceTree

Delete the file {Username}@STAuth-bitbucket.org

Restart Sourcetree

Try to fetch, password filed appear, give your new password

Also can run "git fetch" command in terminal and need to type password

Done


问:
How to detect orientation change in layout in Android?
I just implemented a orientation change feature - e.g. when the layout changes from portrait to landscape (or vice versa). How can I detect when the orientation change event finished.

The OrientationEventListener didn't work. How can I get notifications about layout orientation change events?

答:
If accepted answer doesn't work for you, make sure you didn't define in manifest file:

```<code>android:screenOrientation="portrait"
</code>```

Which is my case.

Body:
If accepted answer doesn't work for you, make sure you didn't define in manifest file:

android:screenOrientation="portrait"

Which is my case.


问:
Is app store product id a sensitive data?
Developing the store of my app I'm wandering if the product ids of the in app purchase is a sensitive data. My goal is to store them on the server to be able to upload them on the fly when there is a special offers for example so if this is sensitive data that can be used to trick the shop or anything else should it be protected or it doesn't matter?</p>

答:
Product IDs of inApp purchase in not a sensitive data. There is no harm keeping It stored into server side.

But whenever you Add new inApp purchase first you will need to send it for Apple review. Directly you can't make it usable.

So for approval of inApp purchase you will must have to submit new version of the application with that inApp purchase will be sent for approval.

So eventually there is no meaning for keeping it on server.

Hope it helps to everyone.