问:
dining philosophers with deadlock livelock and starvation
this is a solution for the dining philosophers problem from geeksforgeeks using semaphores:

```<code>#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>

#define N 5
#define THINKING 2
#define HUNGRY 1
#define EATING 0
#define LEFT (phnum + 4) % N
#define RIGHT (phnum + 1) % N

int state[N];
int phil[N] = { 0, 1, 2, 3, 4 };

sem_t mutex;
sem_t S[N];

void test(int phnum)
{
    if (state[phnum] == HUNGRY
        && state[LEFT] != EATING
        && state[RIGHT] != EATING) {
        // state that eating
        state[phnum] = EATING;

        sleep(2);

        printf("Philosopher %d takes fork %d and %d\n",
                    phnum + 1, LEFT + 1, phnum + 1);

        printf("Philosopher %d is Eating\n", phnum + 1);

        // sem_post(&S[phnum]) has no effect
        // during takefork
        // used to wake up hungry philosophers
        // during putfork
        sem_post(&S[phnum]);
    }
}

// take up chopsticks
void take_fork(int phnum)
{

    sem_wait(&mutex);

    // state that hungry
    state[phnum] = HUNGRY;

    printf("Philosopher %d is Hungry\n", phnum + 1);

    // eat if neighbours are not eating
    test(phnum);

    sem_post(&mutex);

    // if unable to eat wait to be signalled
    sem_wait(&S[phnum]);

    sleep(1);
}

// put down chopsticks
void put_fork(int phnum)
{

    sem_wait(&mutex);

    // state that thinking
    state[phnum] = THINKING;

    printf("Philosopher %d putting fork %d and %d down\n",
        phnum + 1, LEFT + 1, phnum + 1);
    printf("Philosopher %d is thinking\n", phnum + 1);

    test(LEFT);
    test(RIGHT);

    sem_post(&mutex);
}

void* philospher(void* num)
{

    while (1) {

        int* i = num;

        sleep(1);

        take_fork(*i);

        sleep(0);

        put_fork(*i);
    }
}

int main()
{

    int i;
    pthread_t thread_id[N];

    // initialize the mutexes
    sem_init(&mutex, 0, 1);

    for (i = 0; i < N; i++)

        sem_init(&S[i], 0, 0);

    for (i = 0; i < N; i++) {

        // create philosopher processes
        pthread_create(&thread_id[i], NULL,
                    philospher, &phil[i]);

        printf("Philosopher %d is thinking\n", i + 1);
    }

    for (i = 0; i < N; i++)

        pthread_join(thread_id[i], NULL);
}
</code>```

https://www.geeksforgeeks.org/dining-philosopher-problem-using-semaphores/

this code have a low probability for deadlock livelock and starvation,
i want to change it that it will have deadlock,livelock or starvation with high probability,
how can i do that?

also how i can ensure this solution will not have any of those problems for 100% (if possible)

答:
Ok, first, the best solution i know for the dinning philosophers problem is this (from modern operating systems - 4th edition of Tannebaum and Bos):

```<code>#define TRUE 1
#define N 5
#define LEFT (i+N-1)%N
#define RIGHT (i+1)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2

typedef int semaphore;
int state[N];
semaphore mutex = 1;
semaphore s[N];

void
philosopher(int i){
  while(TRUE){
    think();
    take_forks(i);
    eat();
    put_forks(i)
  }
}

void
take_forks(int i){
  down(&mutex);
  state[i] = HUNGRY;
  test(i);
  up(&mutex);
  down(&s[i]);
}

void
put_forks(i){
  down(&mutex);
  state[i] = THINKING;
  test(LEFT);
  test(RIGHT);
  up(&mutex);
}

void
test(int i){
  if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING){
    state[i] = EATING;
    up(&s[i]);
  }
}
</code>```

Off course for simplicity prototypes and some function are omitted, but the point is that if you want to create a completely unsafe dining philosopher, the solution is a think like this:

```<code>  #define N 5

  void philosopher(int i){
    while(TRUE){
      think();
      take_fork(i);
      take_fork((i+1)%N);
      eat();
      put_fork(i);
      put_fork((i+1)%N);
    }
  }
</code>```

explanaiton:
This program will produce pretty easly a race condition, infact two philosopher will take the same fork, this because we don't use semaphores for wait our turn for eat and it will also produce a starvation because we don't use test() for check if some one were using already our fork, so if you want to modify your program for have this problems you should remove the test() and all the pieces of code where you have used semaphores and any kind of test.

Body:
this is a solution for the dining philosophers problem from geeksforgeeks using semaphores:

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>

#define N 5
#define THINKING 2
#define HUNGRY 1
#define EATING 0
#define LEFT (phnum + 4) % N
#define RIGHT (phnum + 1) % N

int state[N];
int phil[N] = { 0, 1, 2, 3, 4 };

sem_t mutex;
sem_t S[N];

void test(int phnum)
{
    if (state[phnum] == HUNGRY
        && state[LEFT] != EATING
        && state[RIGHT] != EATING) {
        // state that eating
        state[phnum] = EATING;

        sleep(2);

        printf("Philosopher %d takes fork %d and %d\n",
                    phnum + 1, LEFT + 1, phnum + 1);

        printf("Philosopher %d is Eating\n", phnum + 1);

        // sem_post(&S[phnum]) has no effect
        // during takefork
        // used to wake up hungry philosophers
        // during putfork
        sem_post(&S[phnum]);
    }
}

// take up chopsticks
void take_fork(int phnum)
{

    sem_wait(&mutex);

    // state that hungry
    state[phnum] = HUNGRY;

    printf("Philosopher %d is Hungry\n", phnum + 1);

    // eat if neighbours are not eating
    test(phnum);

    sem_post(&mutex);

    // if unable to eat wait to be signalled
    sem_wait(&S[phnum]);

    sleep(1);
}

// put down chopsticks
void put_fork(int phnum)
{

    sem_wait(&mutex);

    // state that thinking
    state[phnum] = THINKING;

    printf("Philosopher %d putting fork %d and %d down\n",
        phnum + 1, LEFT + 1, phnum + 1);
    printf("Philosopher %d is thinking\n", phnum + 1);

    test(LEFT);
    test(RIGHT);

    sem_post(&mutex);
}

void* philospher(void* num)
{

    while (1) {

        int* i = num;

        sleep(1);

        take_fork(*i);

        sleep(0);

        put_fork(*i);
    }
}

int main()
{

    int i;
    pthread_t thread_id[N];

    // initialize the mutexes
    sem_init(&mutex, 0, 1);

    for (i = 0; i < N; i++)

        sem_init(&S[i], 0, 0);

    for (i = 0; i < N; i++) {

        // create philosopher processes
        pthread_create(&thread_id[i], NULL,
                    philospher, &phil[i]);

        printf("Philosopher %d is thinking\n", i + 1);
    }

    for (i = 0; i < N; i++)

        pthread_join(thread_id[i], NULL);
}

https://www.geeksforgeeks.org/dining-philosopher-problem-using-semaphores/

this code have a low probability for deadlock livelock and starvation,
i want to change it that it will have deadlock,livelock or starvation with high probability,
how can i do that?

also how i can ensure this solution will not have any of those problems for 100% (if possible)

Body:
Ok, first, the best solution i know for the dinning philosophers problem is this (from modern operating systems - 4th edition of Tannebaum and Bos):

#define TRUE 1
#define N 5
#define LEFT (i+N-1)%N
#define RIGHT (i+1)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2

typedef int semaphore;
int state[N];
semaphore mutex = 1;
semaphore s[N];

void
philosopher(int i){
  while(TRUE){
    think();
    take_forks(i);
    eat();
    put_forks(i)
  }
}

void
take_forks(int i){
  down(&mutex);
  state[i] = HUNGRY;
  test(i);
  up(&mutex);
  down(&s[i]);
}

void
put_forks(i){
  down(&mutex);
  state[i] = THINKING;
  test(LEFT);
  test(RIGHT);
  up(&mutex);
}

void
test(int i){
  if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING){
    state[i] = EATING;
    up(&s[i]);
  }
}

Off course for simplicity prototypes and some function are omitted, but the point is that if you want to create a completely unsafe dining philosopher, the solution is a think like this:

  #define N 5

  void philosopher(int i){
    while(TRUE){
      think();
      take_fork(i);
      take_fork((i+1)%N);
      eat();
      put_fork(i);
      put_fork((i+1)%N);
    }
  }

explanaiton:
This program will produce pretty easly a race condition, infact two philosopher will take the same fork, this because we don't use semaphores for wait our turn for eat and it will also produce a starvation because we don't use test() for check if some one were using already our fork, so if you want to modify your program for have this problems you should remove the test() and all the pieces of code where you have used semaphores and any kind of test.


来源: stackexchange

问:
Data.frame from list of rows
A rather simple answer.

Given a named named json-like list of data.frame rows, how would one transform this into a proper data.frame in a concise manner while keeping the column classes and row names intact.

```<code>df_list <- lapply(1:10, function(x)list(a = 1, b = 'hello', c = 3 - 1i))
names(df_list) <- LETTERS[1:10]
</code>```

desired result

```<code>data.frame(a = rep(1, 10), b = rep('hello', 10), c = rep(3 - 1i, 10))
</code>```

答:
An option with unnest_wider

```<code>library(dplyr)
library(tidyr)
tibble(col1 = df_list) %>%
      unnest_wider(c(col1))
</code>```

Or with bind_rows

```<code>bind_rows(df_list)
</code>```

Or with rbindlist from data.table

```<code>library(data.table)
rbindlist(df_list)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Data.frame from list of rows

Body:
A rather simple answer.

Given a named named json-like list of data.frame rows, how would one transform this into a proper data.frame in a concise manner while keeping the column classes and row names intact.

df_list <- lapply(1:10, function(x)list(a = 1, b = 'hello', c = 3 - 1i))
names(df_list) <- LETTERS[1:10]

desired result

data.frame(a = rep(1, 10), b = rep('hello', 10), c = rep(3 - 1i, 10))

Body:
An option with unnest_wider

library(dplyr)
library(tidyr)
tibble(col1 = df_list) %>%
      unnest_wider(c(col1))

Or with bind_rows

bind_rows(df_list)

Or with rbindlist from data.table

library(data.table)
rbindlist(df_list)


问:
Make kubernetes mount point only to azure files
I have a kubernetes volume mount pointing to azure files. How do I restrict files present in azure files to my container?

My requirement is to push the files only to azure files but I shouldn't load the files back to the container.

```<code>      volumeMounts:
        - name: testlog
          mountPath: /app/testlog/
  volumes:
    - name: testlog
      azureFile:
        secretName: testlog-secret
        shareName: testlog
        readOnly: false
</code>```

答:
To manage the content within an Azure File PVC, you should

1) create the Storage Account before hand
https://learn.microsoft.com/en-us/rest/api/storagerp/storage-sample-create-account

2) manage its content using the API directly within your container/application code
https://learn.microsoft.com/en-us/rest/api/storageservices/file-service-rest-api

for example to create a directly
https://learn.microsoft.com/en-us/rest/api/storageservices/create-directory
and files within that directory
https://learn.microsoft.com/en-us/rest/api/storageservices/create-file

If you have a specific language and you do not want to use the http API directly, MSFT have created a few SKDs to manage Storage accounts

Here's an example in GO

https://github.com/Azure/azure-storage-file-go

Body:
I have a kubernetes volume mount pointing to azure files. How do I restrict files present in azure files to my container?

My requirement is to push the files only to azure files but I shouldn't load the files back to the container.

      volumeMounts:
        - name: testlog
          mountPath: /app/testlog/
  volumes:
    - name: testlog
      azureFile:
        secretName: testlog-secret
        shareName: testlog
        readOnly: false


问:
command handler not showing properly
i tried to add a command handler, but command files are showing incorrect values, for example the bot's ping is showing up as NaN and uptime/users/servers are all showing as zeros. the command was working fine until i moved it into it's own command file. i'm not sure what the problem is as no errors occur in the console. please help, the code to my index.js and one command file is below

my best guess as to where the issue is:
module.exports = {
    name: bot,
    description: displays bot information.,
    execute(message, args) {
//code
}

https://pastebin.com/hJ4nessW

答:
It looks like your bot.js file has some lines without using Discord.js's Embed class...

At the first part where's

const Discord = require(`discord.js`);
const bot = new Discord.Client(); // <- here
```

<p>isn't necessary because it's defined in index.js, so should be use from index.js</p>

<pre class="lang-js prettyprint-override"><code>    switch (args[0]) {

        case `ping`:
            bot.commands.get(`ping`).execute(message, args, bot /* use it */ );
            break;

        case `bot`:
            bot.commands.get(`bot`).execute(message, args, bot /* use it */ );
            break;

    }
</code>```

and bot.js

 execute(message, args, bot) {
  // You can use bot variable
  // ...
```

I recommend to avoid spaghetti code, because it looks worse and spends a lot of time... I made the shorten, less lines and working code version ->  https://pastebin.com/sRNacWYt

Title: command handler not showing properly

Body:
It looks like your bot.js file has some lines without using Discord.js's Embed class...

At the first part where's

const Discord = require(`discord.js`);
const bot = new Discord.Client(); // <- here

isn't necessary because it's defined in index.js, so should be use from index.js

    switch (args[0]) {

        case `ping`:
            bot.commands.get(`ping`).execute(message, args, bot /* use it */ );
            break;

        case `bot`:
            bot.commands.get(`bot`).execute(message, args, bot /* use it */ );
            break;

    }

and bot.js

 execute(message, args, bot) {
  // You can use bot variable
  // ...

I recommend to avoid spaghetti code, because it looks worse and spends a lot of time... I made the shorten, less lines and working code version ->  https://pastebin.com/sRNacWYt


问:
Uncaught TypeError: ((x.event.special[i.origType] || (intermediate value)).handle || i.handler).apply is not a function
Please help me. This is an error when I use jQuery in ASP.NET MVC.

Uncaught TypeError: ((x.event.special[i.origType] || (intermediate
  value)).handle || i.handler).apply is not a function Uncaught
  TypeError: ((x.event.special[i.origType] || (intermediate
  value)).handle || i.handler).apply is not a function

The code that causes this is:

```<code>$('#btnClick').click(function(){   //code })
</code>```

答:
It may help some newbie like me so pasting what I was doing wrong:

Wrong:

```<code>$(function(){
$('#submitButton').click($(function(){
    ......
}));
</code>```

Right:

```<code>$(function(){
$('#submitButton').click(function(){
  .........
 });
</code>```

Notice I removed the $ sign before the function.
I am new to jQuery so I do not know why it did not work.

I will update this answer once I find out.

ContentLicense: CC BY-SA 3.0

Body:
Please help me. This is an error when I use jQuery in ASP.NET MVC.

Uncaught TypeError: ((x.event.special[i.origType] || (intermediate
  value)).handle || i.handler).apply is not a function Uncaught
  TypeError: ((x.event.special[i.origType] || (intermediate
  value)).handle || i.handler).apply is not a function

The code that causes this is:

$('#btnClick').click(function(){   //code })

Body:
It may help some newbie like me so pasting what I was doing wrong:

Wrong:

$(function(){
$('#submitButton').click($(function(){
    ......
}));

Right:

$(function(){
$('#submitButton').click(function(){
  .........
 });

Notice I removed the $ sign before the function.
I am new to jQuery so I do not know why it did not work.

I will update this answer once I find out.


问:
High latency with Web Application Proxy
Using fresh Windows Server 2019 installs for AD FS, Web Application Proxy and Exchange 2019, I have been getting high (120000ms+) latency loading ECP and any site that requests a large number of files.  Downloading a single file of large size works flawlessly.

Exchange ECP takes nearly two minutes to load and then doesn't work -- the same goes for other complex sites requiring many image/CSS/JS GETs -- see example timing from Firefox:

I have spent many days trying to debug this with numerous reinstalls of AD FS and WAP servers and finding no answer in the MS forums or Googling the issue!

答:
Disable HTTP/2 in IIS manager.

Such a simple solution.  I hope this can save someone else the days that I have wasted.

Title: High latency with Web Application Proxy


问:
Yesterday's date (validation)
I am stuck with my code. So, I want to create a validation for my dates. For example, today we are on 2020-05-31, if the user enters a previous date to today, for example -> 2020-05-30.

I should to get an error message.

My problem is that my error message isn't display.

Do have you an idea please?

I would like to stay faithful my code please. (I am beginner)

Thank you for your help and your time.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start).getDate();
    const today = new Date().getDate();

    if (inputDate < today || !inputDate.valueOf()) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" onsubmit="return validation()" >
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form></code>```

答:
It works fine for me if you just append a "}" at the end. You always need a opening and closing curly bracket for functions (not only functions, actually everything that uses them) in your code, otherwise you get errors like these. I recommend vs-code as a code editor, so you can see if you wrote valid js or not.

The function should look like this:

```<code>function validation() {
        const date_start = document.getElementById('date_start').value;

        if (!date_start) {
            document.getElementById('date_startError').innerHTML = " ** Empty ! ";
            return false;
        }

        const inputDate = new Date(date_start).getDate();
        const today = new Date().getDate();

        if (inputDate < today || !inputDate.valueOf()) {
            document.getElementById('date_startError').innerHTML = " ** Error date ! ";
            return false;
        }
}
</code>```

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start).getDate();
    const today = new Date().getDate();

    if (inputDate < today || !inputDate.valueOf()) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
}
} // <-----```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" onsubmit="return validation()" >
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form></code>```

Title: Yesterday's date (validation)

Body:
I am stuck with my code. So, I want to create a validation for my dates. For example, today we are on 2020-05-31, if the user enters a previous date to today, for example -> 2020-05-30.

I should to get an error message.

My problem is that my error message isn't display.

Do have you an idea please?

I would like to stay faithful my code please. (I am beginner)

Thank you for your help and your time.

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start).getDate();
    const today = new Date().getDate();

    if (inputDate < today || !inputDate.valueOf()) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
}

<form action="#" onsubmit="return validation()" >

  Date start :

  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">

  <input type="submit" value="ok">
</form>

Body:
It works fine for me if you just append a "}" at the end. You always need a opening and closing curly bracket for functions (not only functions, actually everything that uses them) in your code, otherwise you get errors like these. I recommend vs-code as a code editor, so you can see if you wrote valid js or not.

The function should look like this:

function validation() {
        const date_start = document.getElementById('date_start').value;

        if (!date_start) {
            document.getElementById('date_startError').innerHTML = " ** Empty ! ";
            return false;
        }

        const inputDate = new Date(date_start).getDate();
        const today = new Date().getDate();

        if (inputDate < today || !inputDate.valueOf()) {
            document.getElementById('date_startError').innerHTML = " ** Error date ! ";
            return false;
        }
}

function validation()
{
    const date_start = document.getElementById('date_start').value;

    if(!date_start){
        document.getElementById('date_startError').innerHTML = " ** Empty ! ";
        return false;
    }

    const inputDate = new Date(date_start).getDate();
    const today = new Date().getDate();

    if (inputDate < today || !inputDate.valueOf()) {
        document.getElementById('date_startError').innerHTML = " ** Error date ! ";
        return false;
}
} // <-----

<form action="#" onsubmit="return validation()" >
  <br>
  <label>Date start : </label>
  <br>
  <input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
  <br>
  <span id="date_startError"></span>
  <br>
  <input type="submit" value="ok">
</form>


问:
How to convert ProxyObject in python multiprocessing manager to normal python object
I'm using the multiprocessing library in python 3.7.

In my use case, I start with a normal list of dicts - I use this to create a ListProxy object from a SyncManager which I then use in a pool to syncronise the list (created as below).

```<code>data = [{...},{...},{...}] # arbitrary list of dicts that I want to sync in a pool

with Manager() as manager:

  list_proxy = manager.list()
  for row in data:
    list_proxy.append(manager.dict(row))

  # ... list_proxy used in pool.starmap later
</code>```

My question: is there a pythonic way to change my ListProxy back into a normal list once the pool has finished running? I looked through the docs and even into the source code and it seems the only way might be to use the _getvalue() method from the BaseProxy class - but this seems hacky, and I will also have to recursively 'un-proxy' any nested proxy objects.

I need to return the normal list to serialise it to json later in the code, ProxyObjects are not easily serialised.

答:
I believe you can just call the "real" object function on the proxy object and turn it into the "real" object. See this example of a proxy dict which I share across instances and later turn into a "real" dict in order to serialize it.

```<code>def main(state):
    # Do something to input
    dict_proxy['state'] = state

if __name__ == '__main__':
    manager = Manager()
    dict_proxy = manager.dict()

    num_cores = int(2)
    with Pool(num_cores) as p:
       p.map(main, ['AK', 'HI'])

    dict_real = dict(dict_proxy)
</code>```

Body:
I'm using the multiprocessing library in python 3.7.

In my use case, I start with a normal list of dicts - I use this to create a ListProxy object from a SyncManager which I then use in a pool to syncronise the list (created as below).

data = [{...},{...},{...}] # arbitrary list of dicts that I want to sync in a pool

with Manager() as manager:

  list_proxy = manager.list()
  for row in data:
    list_proxy.append(manager.dict(row))

  # ... list_proxy used in pool.starmap later

My question: is there a pythonic way to change my ListProxy back into a normal list once the pool has finished running? I looked through the docs and even into the source code and it seems the only way might be to use the _getvalue() method from the BaseProxy class - but this seems hacky, and I will also have to recursively 'un-proxy' any nested proxy objects.

I need to return the normal list to serialise it to json later in the code, ProxyObjects are not easily serialised.

Body:
I believe you can just call the "real" object function on the proxy object and turn it into the "real" object. See this example of a proxy dict which I share across instances and later turn into a "real" dict in order to serialize it.

def main(state):
    # Do something to input
    dict_proxy['state'] = state

if __name__ == '__main__':
    manager = Manager()
    dict_proxy = manager.dict()

    num_cores = int(2)
    with Pool(num_cores) as p:
       p.map(main, ['AK', 'HI'])

    dict_real = dict(dict_proxy)


问:
Python cv2.imread returns 'NoneType' object has no attribute 'shape'
I'm trying to read my pictures with cv2.imread from a folder named "Bilder", but I always get None returned. When I put my pictures in the folder "Straßenverkehr Projekt" (the folder, where my code [module.py] is also saved) it works.

Folder path of the pictures : C:\Users\ramif\Desktop\Straßenverkehr Projekt\Bilder

Folder path of the code: C:/Users/ramif/Desktop/Straßenverkehr Projekt/module.py

Traceback (most recent call):

File "c:/Users/ramif/Desktop/Straßenverkehr Projekt/module.py", line
  12, in read_image   print(img.shape)

AttributeError: 'NoneType' object has no attribute 'shape'

```<code>import cv2
import matplotlib.pyplot as plt
import numpy as np
import os

def read_image():
    'reading the images'
    folder = os.path.join(os.path.dirname(__file__),"Bilder")
    for i in os.listdir(folder):
        img = cv2.imread(i)
        print(img.shape)

read_image()
</code>```

答:
The problem is that os.listdir is giving you just the file names inside of the Bilder folder. To make this example work, you need to append the directory to the file name so that you have the complete path to the image.

import cv2
import matplotlib.pyplot as plt
import numpy as np
import os

def read_image():
    'reading the images'
    folder = os.path.join(os.path.dirname(__file__),"Bilder")
    for i in os.listdir(folder):
        img = cv2.imread(folder + '/' + i)
        print(img.shape)

read_image()
```

Body:
I'm trying to read my pictures with cv2.imread from a folder named "Bilder", but I always get None returned. When I put my pictures in the folder "Straßenverkehr Projekt" (the folder, where my code [module.py] is also saved) it works.

Folder path of the pictures : C:\Users\ramif\Desktop\Straßenverkehr Projekt\Bilder

Folder path of the code: C:/Users/ramif/Desktop/Straßenverkehr Projekt/module.py

Traceback (most recent call):

File "c:/Users/ramif/Desktop/Straßenverkehr Projekt/module.py", line
  12, in read_image   print(img.shape)

AttributeError: 'NoneType' object has no attribute 'shape'

import cv2
import matplotlib.pyplot as plt
import numpy as np
import os

def read_image():
    'reading the images'
    folder = os.path.join(os.path.dirname(__file__),"Bilder")
    for i in os.listdir(folder):
        img = cv2.imread(i)
        print(img.shape)

read_image()


问:
Google Chrome form onChange not firing
How do I get Google Chrome (9.0.597.98 on Windows 7 64-bit) to fire a form's onchange? If you play around with the following example, nothing gets consoled out. It's working fine in Firefox 3.6.13.</p>

```<code><form onchange="console.info('form changed')">
 <select>
  <option>uno</option>
  <option>dos</option>
 </select>
 <input type="radio" name="videoDevice" value="tres" checked="checked" />
 <input type="radio" name="videoDevice" value="cuatro" checked="checked" />
</form>
</code>```

答:
```<code>     var button = document.form.adet;
        if (button.addEventListener) {  // all browsers except IE before version 9
            button.addEventListener ("change", function () { alert('1'); }, false);
        }
        else {
            if (button.attachEvent) {   // IE before version 9
                button.attachEvent ("onchange", function () { alert('2'); });
            }
        }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Google Chrome form onChange not firing

Body:
How do I get Google Chrome (9.0.597.98 on Windows 7 64-bit) to fire a form's onchange? If you play around with the following example, nothing gets consoled out. It's working fine in Firefox 3.6.13.

<form onchange="console.info('form changed')">
 <select>
  <option>uno</option>
  <option>dos</option>
 </select>
 <input type="radio" name="videoDevice" value="tres" checked="checked" />
 <input type="radio" name="videoDevice" value="cuatro" checked="checked" />
</form>


问:
Set GOOGLE_APPLICATION_CREDENTIALS environment variable in VSCode debugger
I'm testing Google Cloud Pub/Sub on my Django project using VSCode on my Mac, and I'm having some problems setting GCP environment variables during debugging tests, specifically the GOOGLE_APPLICATION_CREDENTIALS environment variable.

I am able to set the GOOGLE_APPLICATION_CREDENTIALS for running server and/or tests locally with export GOOGLE_APPLICATION_CREDENTIALS="path/to/json_credential_file.json" in a shell, but as the VSCode debugger runs in a separate shell the env variable is not set when debugging tests. I tried adding the same value to the env key in launch.json:

```<code>"env": {
    "GOOGLE_APPLICATION_CREDENTIALS": "path/to/json_credential_file.json"
}
</code>```

But it still complains about GOOGLE_APPLICATION_CREDENTIALS not being set:

```<code>oauth2client.client.ApplicationDefaultCredentialsError: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
</code>```

Any ideas?

答:
Here is an example

```<code>"env": {
        "GOOGLE_APPLICATION_CREDENTIALS": "./secret.do.not.commit/serviceAccountTasks.privateKey.json"
      }
</code>```

and here is the reference https://code.visualstudio.com/docs/editor/debugging#_launch-configurations

Body:
I'm testing Google Cloud Pub/Sub on my Django project using VSCode on my Mac, and I'm having some problems setting GCP environment variables during debugging tests, specifically the GOOGLE_APPLICATION_CREDENTIALS environment variable.

I am able to set the GOOGLE_APPLICATION_CREDENTIALS for running server and/or tests locally with export GOOGLE_APPLICATION_CREDENTIALS="path/to/json_credential_file.json" in a shell, but as the VSCode debugger runs in a separate shell the env variable is not set when debugging tests. I tried adding the same value to the env key in launch.json:

"env": {
    "GOOGLE_APPLICATION_CREDENTIALS": "path/to/json_credential_file.json"
}

But it still complains about GOOGLE_APPLICATION_CREDENTIALS not being set:

oauth2client.client.ApplicationDefaultCredentialsError: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

Any ideas?

Body:
Here is an example

"env": {
        "GOOGLE_APPLICATION_CREDENTIALS": "./secret.do.not.commit/serviceAccountTasks.privateKey.json"
      }

and here is the reference https://code.visualstudio.com/docs/editor/debugging#_launch-configurations


问:
Macro produces negative font.colorindex values
Clues to possible reason at the end of this initial discussion.....

A simple VBA macro code line like:

```<code>FontCol = Cells(K, AmntCol).Font.ColorIndex
</code>```

reports, with the cursor hovering over "FontCol", the value "1"
- which is the index value for black.

yet when this value is "published" to the relevant (active) Excel spreadsheet with:

```<code>Cells(RowRef, ColRef) = FontCol
</code>```

the Cell addressed as above shows -5 instead of 1 (as one example of the problem)

"1" is what you expect to see for black, and I cannot even work out what "-5" relates to
let alone why it is also not what seems to be in play in the VBA code.
- and if I write "-5" into some code logic, no useful result would come from it, which confirms that the real underlying value is 1 and not -5.

It seems that no amount of formatting of the (landing) cell or changing the "Dimension as statement" for FontCol, to "integer" or "string" or "variant" changes what is published to the cell.

I've not been able to source any information on this issue. The closest was something about long numbers wrapping around shorter numbers in the index space and a residual driving things...whatever that is supposed to mean.

I really would to resolve this as I was intending to use ColorIndex values as a way of editing cell values safely.

Any wisdom would be greatly appreciated.

Additional to above - in response.

Changing Dim of variable/s from "integer" to "long" makes no difference.

In preparing to provide sample code as below I have determined part of the problem - its seems its speed related. But first the code.

''''
    Sub FontMacroIssue()

```<code>Dim I As Long
Dim FontCol As Long

For I = 36 To 51
    FontCol = Cells(I, 10).Font.ColorIndex
    If FontCol = 3 Then
        Cells(I, 18) = "Red"
        Cells(I, 19) = FontCol
    Else
        Cells(I, 18) = "Not Red"
        Cells(I, 19) = FontCol
    End If
Next I

End Sub
''''
</code>```

The above is being run on a Windows 10 64 bit machine (that dual boots into Linux)...this should not be relevant.

If the above is run as is then the output is mostly/all "not red" and the string of FontCol values print out as,

1 -5 -5 -5 -5 -7 -7 -7 -7 -7 -7 -7 -7 -7 -5 -7 - and if it is slowed, as
1  3  3  3  3  1  1  1  1  1  1  1  1  1  3  1

By slowed, I mean running the macro in debug mode with a break point at "Next I" or in a similar place, and then keying the F5 button (say) twice a second. The output for the full speed case is mostly/all "not red" but is the correct reporting of "red" and "not red" when slowed for the font being assessed.

So my question/s now are more, "is this behaviour normal", "how can I best slow things down to get a correct result" OR "what code is more effective" ?
edit...

I am inclined to agree with Fun Thomas as even 2 cycles/sec brings up the problem.
I do not have an answer but some comments that might help.
1.  My hard drive is a 2 TB SSD
2.  The spreadsheet concerned has over 46000 lines.
3.  It surely is more than coincidence that:
    8 -7 = 1  with both 1 and -7 being reported for black font, and
    8 -5 = 3  with both 3 and -5 being reported for red font.
Thanks

答:
Possible Event Procedure Issue

You might have an event procedure that is messing with your results.

Workbook Download (Google Drive)

The following event procedure sort of replicates your issue. The first code goes into a standard module (Module1) and the second goes into the sheet module (e.g. Sheet1).

You only run the first code and it will return the right values in ranges R36:R51 and T36:T51 and it will 'randomly' return the right or wrong values in range S36:S51.

Additionally when you input values manually in the range S36:S51
and if they are numbers, after confirming by e.g. pressing ENTER, the
entered values will 'randomly' either be decreased by 8 or not.

Module1

```<code>Option Explicit

Sub FontMacroIssue()

    Dim i As Long
    Dim FontCol As Long

    For i = 36 To 51
        FontCol = Cells(i, 10).Font.ColorIndex
        If FontCol = 3 Then
            Cells(i, 18).Value = "Red"
        Else
            Cells(i, 18).Value = "Not Red"
        End If
        Cells(i, 19).Value = FontCol
        Cells(i, 20).Value = FontCol
    Next i

End Sub
</code>```

Sheet1

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Const TargetCol As Long = 19
    Const TargetRows As String = "36:51"
    Const Offset As Long = 8

    Dim rng As Range
    Set rng = Intersect(Target, Columns(TargetCol))
    If rng Is Nothing Then Exit Sub
    Set rng = Intersect(rng, Rows(TargetRows))
    If rng Is Nothing Then Exit Sub

    On Error GoTo CleanExit

    Dim cel As Range
    For Each cel In rng
        If Round(Rnd()) = 0 Then
            Application.EnableEvents = False
            cel.Value = cel.Value - Offset
            Application.EnableEvents = True
        End If
    Next cel

    Exit Sub

CleanExit:
    Application.EnableEvents = True

End Sub
</code>```

Body:
Clues to possible reason at the end of this initial discussion.....

A simple VBA macro code line like:

FontCol = Cells(K, AmntCol).Font.ColorIndex

reports, with the cursor hovering over "FontCol", the value "1"
- which is the index value for black.

yet when this value is "published" to the relevant (active) Excel spreadsheet with:

Cells(RowRef, ColRef) = FontCol

the Cell addressed as above shows -5 instead of 1 (as one example of the problem)

"1" is what you expect to see for black, and I cannot even work out what "-5" relates to
let alone why it is also not what seems to be in play in the VBA code.
- and if I write "-5" into some code logic, no useful result would come from it, which confirms that the real underlying value is 1 and not -5.

It seems that no amount of formatting of the (landing) cell or changing the "Dimension as statement" for FontCol, to "integer" or "string" or "variant" changes what is published to the cell.

I've not been able to source any information on this issue. The closest was something about long numbers wrapping around shorter numbers in the index space and a residual driving things...whatever that is supposed to mean.

I really would to resolve this as I was intending to use ColorIndex values as a way of editing cell values safely.

Any wisdom would be greatly appreciated.

Additional to above - in response.

Changing Dim of variable/s from "integer" to "long" makes no difference.

In preparing to provide sample code as below I have determined part of the problem - its seems its speed related. But first the code.

''''
    Sub FontMacroIssue()

Dim I As Long
Dim FontCol As Long

For I = 36 To 51
    FontCol = Cells(I, 10).Font.ColorIndex
    If FontCol = 3 Then
        Cells(I, 18) = "Red"
        Cells(I, 19) = FontCol
    Else
        Cells(I, 18) = "Not Red"
        Cells(I, 19) = FontCol
    End If
Next I

End Sub
''''

The above is being run on a Windows 10 64 bit machine (that dual boots into Linux)...this should not be relevant.

If the above is run as is then the output is mostly/all "not red" and the string of FontCol values print out as,

1 -5 -5 -5 -5 -7 -7 -7 -7 -7 -7 -7 -7 -7 -5 -7 - and if it is slowed, as
1  3  3  3  3  1  1  1  1  1  1  1  1  1  3  1

By slowed, I mean running the macro in debug mode with a break point at "Next I" or in a similar place, and then keying the F5 button (say) twice a second. The output for the full speed case is mostly/all "not red" but is the correct reporting of "red" and "not red" when slowed for the font being assessed.

So my question/s now are more, "is this behaviour normal", "how can I best slow things down to get a correct result" OR "what code is more effective" ?
edit...

I am inclined to agree with Fun Thomas as even 2 cycles/sec brings up the problem.
I do not have an answer but some comments that might help.
1.  My hard drive is a 2 TB SSD
2.  The spreadsheet concerned has over 46000 lines.
3.  It surely is more than coincidence that:
    8 -7 = 1  with both 1 and -7 being reported for black font, and
    8 -5 = 3  with both 3 and -5 being reported for red font.
Thanks

Body:
Possible Event Procedure Issue

You might have an event procedure that is messing with your results.

Workbook Download (Google Drive)

The following event procedure sort of replicates your issue. The first code goes into a standard module (Module1) and the second goes into the sheet module (e.g. Sheet1).

You only run the first code and it will return the right values in ranges R36:R51 and T36:T51 and it will 'randomly' return the right or wrong values in range S36:S51.

Additionally when you input values manually in the range S36:S51
and if they are numbers, after confirming by e.g. pressing ENTER, the
entered values will 'randomly' either be decreased by 8 or not.

Module1

Option Explicit

Sub FontMacroIssue()

    Dim i As Long
    Dim FontCol As Long

    For i = 36 To 51
        FontCol = Cells(i, 10).Font.ColorIndex
        If FontCol = 3 Then
            Cells(i, 18).Value = "Red"
        Else
            Cells(i, 18).Value = "Not Red"
        End If
        Cells(i, 19).Value = FontCol
        Cells(i, 20).Value = FontCol
    Next i

End Sub

Sheet1

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Const TargetCol As Long = 19
    Const TargetRows As String = "36:51"
    Const Offset As Long = 8

    Dim rng As Range
    Set rng = Intersect(Target, Columns(TargetCol))
    If rng Is Nothing Then Exit Sub
    Set rng = Intersect(rng, Rows(TargetRows))
    If rng Is Nothing Then Exit Sub

    On Error GoTo CleanExit

    Dim cel As Range
    For Each cel In rng
        If Round(Rnd()) = 0 Then
            Application.EnableEvents = False
            cel.Value = cel.Value - Offset
            Application.EnableEvents = True
        End If
    Next cel

    Exit Sub

CleanExit:
    Application.EnableEvents = True

End Sub


问:
How do I make python read a value after a string, then comparing and outputting the value?
For example, say I have a set of data.txt:

```<code>Name1 | Points:100
Name2 | Points:150
Name3 | Points:200
</code>```

I want python to read the value after "Points:", compare it to a variable "j" and output the line only if the value is less than the variable "j".

I'm a complete beginner to Python, so apologies if this seems very easy. Thanks for any replies :)

答:
file1 = open('data.txt', 'r')
file_lines = file1.readlines()
for line in file_lines:
    points = (int)(line.split(':')[1])
    if points < j:
        print(points)

file1.close()
```

First you read the file. This is what lines 1 and 2 are doing. Line 3 allows you to iterate through the file, one line at the time.

Now we can move to next part which "read" the points in every line. To do that I used split method.It separates the line into a list by the char ':'. Taking it [1] argument means "take whatever is after the first ':' and before the next ':'" (which does not exist in our case).. An hidden assumption is that there is only one ':' in each row, and points follows by it.
Then you have in points the value of current line, you can compare it as you want.

For next time: when asking a question in stackoverflow, give a code example of what you already tried, what and did not work and concrete examples of input and output.

Body:
For example, say I have a set of data.txt:

Name1 | Points:100
Name2 | Points:150
Name3 | Points:200

I want python to read the value after "Points:", compare it to a variable "j" and output the line only if the value is less than the variable "j".

I'm a complete beginner to Python, so apologies if this seems very easy. Thanks for any replies :)

Body:
file1 = open('data.txt', 'r')
file_lines = file1.readlines()
for line in file_lines:
    points = (int)(line.split(':')[1])
    if points < j:
        print(points)

file1.close()

First you read the file. This is what lines 1 and 2 are doing. Line 3 allows you to iterate through the file, one line at the time.

Now we can move to next part which "read" the points in every line. To do that I used split method.It separates the line into a list by the char ':'. Taking it [1] argument means "take whatever is after the first ':' and before the next ':'" (which does not exist in our case).. An hidden assumption is that there is only one ':' in each row, and points follows by it.
Then you have in points the value of current line, you can compare it as you want.

For next time: when asking a question in stackoverflow, give a code example of what you already tried, what and did not work and concrete examples of input and output.


问:
Why the need to redefine properties when implementing an interface in TypeScript?
I'm getting into classes and interfaces. And I got one thing about it that annoys me, this is the first time I work with these kind of things so bear with me here..

Let's say I got this interface:

```<code>// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}
</code>```

When I implement it in a class I do the following:

```<code>// FooModel.ts
import IFoo from './IFoo';

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}
</code>```

Why do I have to implement the same properties all over again?

This is basically the same as copy-paste but with a strict convention. Also, I have to type foo and bar a total of 6 times each to get it properly assigned with default optional values, based on an interface.

Is there a more efficient way to do this too?

Edit; I'm trying to achieve the following:

A class with the properties, from which the properties can be used for typescript's checking, like this:
interface

```<code>export default interface FooDTO {
  foo: string;
  bar: number;
}
</code>```

model

```<code>export interface IFoo {
  foo: string;
  bar: number;
}

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}
</code>```

controller

```<code>export default class FooController {
   public static async readAll(): Array<FooDTO> {
      // some model stuff which maps query to dto
      return Array<FooDTO>result;
   }
}
</code>```

答:
If you define an interface with only properties you basically defined a data structure type that you can then use to type objects.

For example you could now do this:

```<code>const fooObj: IFoo = { foo: "test", bar: 12 };
</code>```

In other programming languages (eg. Java) it is illegal to define properties on an interface. An interface "normally" defines a way you can interact with an object (meaning methods you can invoke on it). But TypeScript is an exception to this.

Body:
I'm getting into classes and interfaces. And I got one thing about it that annoys me, this is the first time I work with these kind of things so bear with me here..

Let's say I got this interface:

// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}

When I implement it in a class I do the following:

// FooModel.ts
import IFoo from './IFoo';

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}

Why do I have to implement the same properties all over again?

This is basically the same as copy-paste but with a strict convention. Also, I have to type foo and bar a total of 6 times each to get it properly assigned with default optional values, based on an interface.

Is there a more efficient way to do this too?

Edit; I'm trying to achieve the following:

A class with the properties, from which the properties can be used for typescript's checking, like this:
interface

export default interface FooDTO {
  foo: string;
  bar: number;
}

model

export interface IFoo {
  foo: string;
  bar: number;
}

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}

controller

export default class FooController {
   public static async readAll(): Array<FooDTO> {
      // some model stuff which maps query to dto
      return Array<FooDTO>result;
   }
}

Body:
If you define an interface with only properties you basically defined a data structure type that you can then use to type objects.

For example you could now do this:

const fooObj: IFoo = { foo: "test", bar: 12 };

In other programming languages (eg. Java) it is illegal to define properties on an interface. An interface "normally" defines a way you can interact with an object (meaning methods you can invoke on it). But TypeScript is an exception to this.


问:
Javascript use single await in ternary operator
I have a situation I want to use await in a ternary operator. I want to set a value to either a literal value or the resolve value of a promise, depending on a condition. Hopefully the code below will help describe what I want to do, but I am pretty sure it is not correct so consider it pseudo code.

```<code>const val = checkCondition ? "literal value" : await promiseGetValue();
</code>```

Where promiseGetValue() returns a promise which resolves to a literal value. What is the correct way to do this?

答:
The conditional operator expects expressions as operands, and await value is a valid expression.

So, if used inside an async function or in the top-level of a module that supports top-level await (where await is valid), your code is completely valid.

I can't say anything else about that.

Body:
I have a situation I want to use await in a ternary operator. I want to set a value to either a literal value or the resolve value of a promise, depending on a condition. Hopefully the code below will help describe what I want to do, but I am pretty sure it is not correct so consider it pseudo code.

const val = checkCondition ? "literal value" : await promiseGetValue();

Where promiseGetValue() returns a promise which resolves to a literal value. What is the correct way to do this?


问:
How to generate a non square matrix m*n in python? Given length L and if L is not a perfect square m > n
I am trying to generate a grid symmetric or asymmetric based on the given length L

when L is a perfect square

L = 4, m=n=2

L = 9, m=n=3

but if L is not a perfect square

L = 6, m=3,n=2

L = 7, m=4,n=2

I have the following code, if it helps others or if one could suggest improvements:

```<code>def get_rows_cols(self):
    sr = math.sqrt(len(self._data.columns))
    numberOfCols = math.floor(sr)
    numberOfRows = 0
    if ((sr - math.floor(sr)) == 0):
        numberOfRows = math.floor(sr)
    else:
        diff = (len(self._data.columns)-1) - pow(numberOfCols,2)
        numberOfRows = (diff / numberOfCols) + 1 + numberOfCols
    n = numberOfCols
    m = int(numberOfRows)
</code>```

答:
So, you have determined your numberOfCols and numberOfRows. If all you want to do is make a grid, you could do it in a pandas dataframe (I'll let you look that one up), or go old-school and just have a list of lists:

```<code>rows = []
one_row = [0] * numberOfCols
for i in range(numberOfRows):
    rows.append(one_row)
</code>```

This will give you a list of lists, where you can access a cell by using the row index and the col index: row[desired_row][desired_col]

Hope that helps, happy coding!

Body:
I am trying to generate a grid symmetric or asymmetric based on the given length L

when L is a perfect square

L = 4, m=n=2

L = 9, m=n=3

but if L is not a perfect square

L = 6, m=3,n=2

L = 7, m=4,n=2

I have the following code, if it helps others or if one could suggest improvements:

def get_rows_cols(self):
    sr = math.sqrt(len(self._data.columns))
    numberOfCols = math.floor(sr)
    numberOfRows = 0
    if ((sr - math.floor(sr)) == 0):
        numberOfRows = math.floor(sr)
    else:
        diff = (len(self._data.columns)-1) - pow(numberOfCols,2)
        numberOfRows = (diff / numberOfCols) + 1 + numberOfCols
    n = numberOfCols
    m = int(numberOfRows)

Body:
So, you have determined your numberOfCols and numberOfRows. If all you want to do is make a grid, you could do it in a pandas dataframe (I'll let you look that one up), or go old-school and just have a list of lists:

rows = []
one_row = [0] * numberOfCols
for i in range(numberOfRows):
    rows.append(one_row)

This will give you a list of lists, where you can access a cell by using the row index and the col index: row[desired_row][desired_col]

Hope that helps, happy coding!


问:
Download .xls file using Angular: Unexpected token P in JSON at position 0 at JSON.parse (<anonymous>)
I have the following server method for returning an byte[] for an xls document stored in Azure Blob Storage.

```<code>[FunctionName("ReadBatchFile")]
        public async static Task<HttpResponseMessage> ReadBatchFile([HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Get, Route = "Agreements/ReadBatchFile")]HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                var fileName = req.GetQueryNameValuePairs()
                   .FirstOrDefault(q => string.Compare(q.Key, "fileName", true) == 0)
                   .Value;
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(await AzureHelpers.ReadFromBlobStorage(fileName));  //returns byte[]
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName };
                response.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
                return response;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                req.CreateResponse(HttpStatusCode.InternalServerError);
            }
            return req.CreateResponse(HttpStatusCode.BadRequest);
        }
</code>```

As can be seen from the above, the response.Content is set an ByteArrayContent and my contentType is application/octet-stream.

In Angular, I have the following method in my service to call the above function.

```<code>readBatchFile(fileName: string): Observable<Blob> {
    let endpoint = environment.endpoints.agreement.baseUrl + environment.endpoints.agreement.readBatchFile + "&fileName=" + fileName;
    const httpOptions = {
      headers: new HttpHeaders({ contentType: 'application/octet-stream' })}; //application/vnd.ms-excel   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    return this.http.get<Blob>(endpoint, httpOptions);
  }
</code>```

Although I am specifying that the contentType is application/octet-stream, and that my get method should return a Blob type, I still get the following error:

Unexpected token P in JSON at position 0↵    at JSON.parse
  ()

Why is Angular still seeing the response from the server as JSON?

Update

Here is my request headers:

```<code>Accept: application/json, text/plain, */*
Authorization: Bearer ...
Origin: http://localhost:4200
Referer: http://localhost:4200/batches
responseType: application/octet-stream
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
</code>```

Response Headers:

```<code>Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Disposition: attachment; filename=B4debe034-efc6-416f-8082-422a4122a857_MTN_Upgrade_20181017_T065548.xls
Content-Length: 3011
Content-Type: application/octet-stream
Date: Wed, 17 Oct 2018 06:55:48 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
</code>```

And the Response:

```<code>PKø6QMäH¯3[Content_Types].xmlµÏJ1Æ_eÉU´D¤ÛªU°>ÀÌvCóÌ´¶oo6+"¥z$ßÌ÷ý3_¼köÉÆÐÆM+ÞÖ[ÑC0àbÀVÄr1_RSfµ¢gNwJîÑÉ0¥ÙkÞ¨zT×ÓéÒ10ðà!ó{ì`ç¸Yïu+ %g5pÁRÅL4"Ã]ýanÌ    ÌäDftµzèê4 ¨4$<ÉÖà¿"b×Y&ê/#RF0Ô#²w²VéÁ1ô2?/®êàÔGÌÛ÷·²j"êù·ü*ªevAâ£C:G1*î!£yå\ü<ÁÏoU~ñ   PKäH¯3PKø6QMÚë®'_rels/.relsÏÁ0àWYzc1ájðæVÖe
oïb<xlú÷ûÓ²^æ=Ñ¬"Ë¡U¤kÜÚËî,DiµÈ¢ÔUyÅIÆtúÁô1ºçAõ8ËC6ùYÆ4zÃT£4È÷y~àþÓÉ-À7ºÖ®ÿ±©ëgRmüQñH²ô£eâ/òãhÌ
¼*ùæÁê
PKÚë®'PKø6QMæl($×Sxl/workbook.xmlO½NÄ0~È;ÂpBUÛ`9    é{Hkt]9)åÝx$^ôª
F&ö÷cûûó«9|Ä ÞQgjávWB²Ü{:·0ews®Y.oÌUÔjiaÈy¬µNvÀhÒG¤Â9hriå¬Ù9oñí²¾«ª½&Miðc5í?Yi4}skT4 k«^=Îé÷È¥UºkôîjÝª"±$Muûò>(©}rì^26£5Á>rSèÍêXTÛêîPKæl($×SPKø6QMb¢Ö4xl/_rels/workbook.xml.relsÏjÃ0_Åè¾8é`Q·1èµ@ØJØÆÒÚåík6VR(cdôý>¬åúkÔ2÷1hª]:ýÇÓ+(ÈÀDëÕrKJYaß'VØIoZ³õ4"W1Q(/mÌ#Jis§Ú#v¤uý¢ó·LµqòÆ5 öS¢ÿ°cÛöÞ£ý)È}ùÈH
sGbà:bý]ªPAßY<ReÊ_^M~ú¿âï1ÛI.[ÌÇ¿2úæÚ«PKb¢Ö4PKø6QMÄÎ«hïxl/worksheets/sheet1.xmlËr0F_a_Ðýâ±Iã:ñ®ÓE»¦¶äpwë¢ÔW¨ÀÄ7 Ðù~I
ðïÏßùÃG~Þ±.!@¨b«wYñºOåþó³6o6Uª^ØYiYgql·©Êé£*\ß^<)Ý¥yõ~mÕJoO¹*ÊÀb£Ié²iv´á¥Ú=µìÑ¨dWO!?\JåIVËù.sÕ«ÙFíá#mHÄËy
ÿÌÔÙÞ´j%¿µ~«.6»Ej6öàu=øwìÔ>9Êúü¢²×´thÙêAUêÂ O>êó9Û©k¡!Â\ÇödKÿjºÃø&8jã<J±LFã¸ãÛÑ!Å  $ÆI'·q! ¥
Î)<mâôÇe!8ÀÑÑ8kâìÀ
/³Ñ8oâüg#&¥ «M\\ã p½Clâò§nòHp¡tÒñeóÔ;mÉrnô90U¯+]5q[oO·ã¬»û¾óø½6ÄW]âÉ'PXùîß|tµOÐ.ñì¬K¼øï-;{BÔ*D^DöúìY~@zWH-c    "$§C"z6§«ÞS{@zíezeQ¤£·Jñ¤Rð }¥ø~¥ÓÕÖH_éÒW:½²Í(ÒQJZ¥dR©OxJ¾Rr¿Òéjë¤¯té+^Ùf¹(oÞ£©ûMPfu©Lýeo]ÿPKÄÎ«hïPKø6QM"tÛ4SÎ
xl/styles.xmlR½nÃ ~ÄÞGjUU¶3T²Ô%K:tÅ6ØHp ÀÝWëÐGê+°8Q¥Lw|þ~ð?_ßù~TuBC³Í#nt<xÆû2w~ìØ3æQà+pï½y!Ä5=SÔm´a¾pmõáh;âe´uQ¤$Ùm·ODQ¸ÌaPò5z_àIÊk¸@üNT$K, ÍÀ+¢¶"¡dæ¦âRHy¶Úá(sC½gªp@Kÿ>V`ÐÀD¼Cï,²ÝãZJH®µmÃ,×¿1Ce.÷QaE×§ÆkK½×*v *ïliwÃ¤<Æ=|ð«£y omeÂÒF£µl6¹£§ÆÈé0¨Ù*3ÒÖ®PéYF~vÎI©WQgÅ=øýåÊ£ôþ»~0mG~óhÈåa¿PK"tÛ4SÎPKø6QMPùûxl/sharedStrings.xmlm]k0ÿJÈ}h][Z2è2Ðþ ÇfsÛ¿_ÆØÖË<ÏÄ=±wp8Zð`/9ÓØv4}ÂoõóîÌ2¬rvIcDbþªÁDó£Ø îíÆÎ:È]/pv ZHO"ò(´
g]ù²gßÈþ/1¦1¥Euò2ÆâüÐêZ°Ò®ijÇ2ÛÂRtÇ^TóªzØÌÿºZ¹±ë6#O
ù¥1¾o$h×¾¨Kû¥mñÌj
píä)ÑÃñt^WdT6p åNkq{§þ!ü¦_PKPùûPK-ø6QMäH¯3[Content_Types].xmlPK-ø6QMÚë®'Y_rels/.relsPK-ø6QMæl($×S@xl/workbook.xmlPK-ø6QMb¢Ö4Txl/_rels/workbook.xml.relsPK-ø6QMÄÎ«hïrxl/worksheets/sheet1.xmlPK-ø6QM"tÛ4SÎ
 xl/styles.xmlPK-ø6QMPùû®xl/sharedStrings.xmlPKÂë
</code>```

答:
I resolve this On angular 9.1.0 with following code:</p>

```<code>result = this._httpClient.get(url,
{
  responseType: 'blob',
  headers: headers
});
</code>```

Body:
I have the following server method for returning an byte[] for an xls document stored in Azure Blob Storage.

[FunctionName("ReadBatchFile")]
        public async static Task<HttpResponseMessage> ReadBatchFile([HttpTrigger(AuthorizationLevel.Function, WebRequestMethods.Http.Get, Route = "Agreements/ReadBatchFile")]HttpRequestMessage req, TraceWriter log)
        {
            try
            {
                var fileName = req.GetQueryNameValuePairs()
                   .FirstOrDefault(q => string.Compare(q.Key, "fileName", true) == 0)
                   .Value;
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(await AzureHelpers.ReadFromBlobStorage(fileName));  //returns byte[]
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName };
                response.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");
                return response;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                req.CreateResponse(HttpStatusCode.InternalServerError);
            }
            return req.CreateResponse(HttpStatusCode.BadRequest);
        }

As can be seen from the above, the response.Content is set an ByteArrayContent and my contentType is application/octet-stream.

In Angular, I have the following method in my service to call the above function.

readBatchFile(fileName: string): Observable<Blob> {
    let endpoint = environment.endpoints.agreement.baseUrl + environment.endpoints.agreement.readBatchFile + "&fileName=" + fileName;
    const httpOptions = {
      headers: new HttpHeaders({ contentType: 'application/octet-stream' })}; //application/vnd.ms-excel   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    return this.http.get<Blob>(endpoint, httpOptions);
  }

Although I am specifying that the contentType is application/octet-stream, and that my get method should return a Blob type, I still get the following error:

Unexpected token P in JSON at position 0↵    at JSON.parse
  ()

Why is Angular still seeing the response from the server as JSON?

Update

Here is my request headers:

Accept: application/json, text/plain, */*
Authorization: Bearer ...
Origin: http://localhost:4200
Referer: http://localhost:4200/batches
responseType: application/octet-stream
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36

Response Headers:

Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Disposition: attachment; filename=B4debe034-efc6-416f-8082-422a4122a857_MTN_Upgrade_20181017_T065548.xls
Content-Length: 3011
Content-Type: application/octet-stream
Date: Wed, 17 Oct 2018 06:55:48 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET

And the Response:

PKø6QMäH¯3[Content_Types].xmlµÏJ1Æ_eÉU´D¤ÛªU°>ÀÌvCóÌ´¶oo6+"¥z$ßÌ÷ý3_¼köÉÆÐÆM+ÞÖ[ÑC0àbÀVÄr1_RSfµ¢gNwJîÑÉ0¥ÙkÞ¨zT×ÓéÒ10ðà!ó{ì`ç¸Yïu+ %g5pÁRÅL4"Ã]ýanÌ    ÌäDftµzèê4 ¨4$<ÉÖà¿"b×Y&ê/#RF0Ô#²w²VéÁ1ô2?/®êàÔGÌÛ÷·²j"êù·ü*ªevAâ£C:G1*î!£yå\ü<ÁÏoU~ñ   PKäH¯3PKø6QMÚë®'_rels/.relsÏÁ0àWYzc1ájðæVÖe
oïb<xlú÷ûÓ²^æ=Ñ¬"Ë¡U¤kÜÚËî,DiµÈ¢ÔUyÅIÆtúÁô1ºçAõ8ËC6ùYÆ4zÃT£4È÷y~àþÓÉ-À7ºÖ®ÿ±©ëgRmüQñH²ô£eâ/òãhÌ
¼*ùæÁê
PKÚë®'PKø6QMæl($×Sxl/workbook.xmlO½NÄ0~È;ÂpBUÛ`9    é{Hkt]9)åÝx$^ôª
F&ö÷cûûó«9|Ä ÞQgjávWB²Ü{:·0ews®Y.oÌUÔjiaÈy¬µNvÀhÒG¤Â9hriå¬Ù9oñí²¾«ª½&Miðc5í?Yi4}skT4 k«^=Îé÷È¥UºkôîjÝª"±$Muûò>(©}rì^26£5Á>rSèÍêXTÛêîPKæl($×SPKø6QMb¢Ö4xl/_rels/workbook.xml.relsÏjÃ0_Åè¾8é`Q·1èµ@ØJØÆÒÚåík6VR(cdôý>¬åúkÔ2÷1hª]:ýÇÓ+(ÈÀDëÕrKJYaß'VØIoZ³õ4"W1Q(/mÌ#Jis§Ú#v¤uý¢ó·LµqòÆ5 öS¢ÿ°cÛöÞ£ý)È}ùÈH
sGbà:bý]ªPAßY<ReÊ_^M~ú¿âï1ÛI.[ÌÇ¿2úæÚ«PKb¢Ö4PKø6QMÄÎ«hïxl/worksheets/sheet1.xmlËr0F_a_Ðýâ±Iã:ñ®ÓE»¦¶äpwë¢ÔW¨ÀÄ7 Ðù~I
ðïÏßùÃG~Þ±.!@¨b«wYñºOåþó³6o6Uª^ØYiYgql·©Êé£*\ß^<)Ý¥yõ~mÕJoO¹*ÊÀb£Ié²iv´á¥Ú=µìÑ¨dWO!?\JåIVËù.sÕ«ÙFíá#mHÄËy
ÿÌÔÙÞ´j%¿µ~«.6»Ej6öàu=øwìÔ>9Êúü¢²×´thÙêAUêÂ O>êó9Û©k¡!Â\ÇödKÿjºÃø&8jã<J±LFã¸ãÛÑ!Å  $ÆI'·q! ¥
Î)<mâôÇe!8ÀÑÑ8kâìÀ
/³Ñ8oâüg#&¥ «M\\ã p½Clâò§nòHp¡tÒñeóÔ;mÉrnô90U¯+]5q[oO·ã¬»û¾óø½6ÄW]âÉ'PXùîß|tµOÐ.ñì¬K¼øï-;{BÔ*D^DöúìY~@zWH-c    "$§C"z6§«ÞS{@zíezeQ¤£·Jñ¤Rð }¥ø~¥ÓÕÖH_éÒW:½²Í(ÒQJZ¥dR©OxJ¾Rr¿Òéjë¤¯té+^Ùf¹(oÞ£©ûMPfu©Lýeo]ÿPKÄÎ«hïPKø6QM"tÛ4SÎ
xl/styles.xmlR½nÃ ~ÄÞGjUU¶3T²Ô%K:tÅ6ØHp ÀÝWëÐGê+°8Q¥Lw|þ~ð?_ßù~TuBC³Í#nt<xÆû2w~ìØ3æQà+pï½y!Ä5=SÔm´a¾pmõáh;âe´uQ¤$Ùm·ODQ¸ÌaPò5z_àIÊk¸@üNT$K, ÍÀ+¢¶"¡dæ¦âRHy¶Úá(sC½gªp@Kÿ>V`ÐÀD¼Cï,²ÝãZJH®µmÃ,×¿1Ce.÷QaE×§ÆkK½×*v *ïliwÃ¤<Æ=|ð«£y omeÂÒF£µl6¹£§ÆÈé0¨Ù*3ÒÖ®PéYF~vÎI©WQgÅ=øýåÊ£ôþ»~0mG~óhÈåa¿PK"tÛ4SÎPKø6QMPùûxl/sharedStrings.xmlm]k0ÿJÈ}h][Z2è2Ðþ ÇfsÛ¿_ÆØÖË<ÏÄ=±wp8Zð`/9ÓØv4}ÂoõóîÌ2¬rvIcDbþªÁDó£Ø îíÆÎ:È]/pv ZHO"ò(´
g]ù²gßÈþ/1¦1¥Euò2ÆâüÐêZ°Ò®ijÇ2ÛÂRtÇ^TóªzØÌÿºZ¹±ë6#O
ù¥1¾o$h×¾¨Kû¥mñÌj
píä)ÑÃñt^WdT6p åNkq{§þ!ü¦_PKPùûPK-ø6QMäH¯3[Content_Types].xmlPK-ø6QMÚë®'Y_rels/.relsPK-ø6QMæl($×S@xl/workbook.xmlPK-ø6QMb¢Ö4Txl/_rels/workbook.xml.relsPK-ø6QMÄÎ«hïrxl/worksheets/sheet1.xmlPK-ø6QM"tÛ4SÎ
 xl/styles.xmlPK-ø6QMPùû®xl/sharedStrings.xmlPKÂë

Body:
I resolve this On angular 9.1.0 with following code:

result = this._httpClient.get(url,
{
  responseType: 'blob',
  headers: headers
});


问:
How to get content on the right of a card to position under the image using bootstrap?
I am having trouble getting the content on the right of an image in a card to the be below the image using bootstrap and CSS. I have tried looking for solutions online and on the bootstrap documentation but I could not find anything that solves my problem. When I go below a certain responsive size I just want to position the AppName, Description and AppDescription below the image. Thanks for the help.

Html Below

```<code>    <div class="card">
        <div class="row no-gutters">
           <div class="col-auto col-md-6">
               <img src="img/image.jpg" class="img-fluid image" alt="PayCloud App Demo" width="620" height="465">
           </div>
           <div class="col">
             <div class="card-block px-2">
                <p class="card-title AppName">AppName</p>
                <p class="card-title Description">Restaurant Payment Service - January 2020</p>
                <p class="card-text AppDescription">App Description.</p>
                <a href="link.html"><span class="button">View Project</span></a>
             </div>
          </div>
       </div>
</div>
</code>```

CSS Below

```<code>.AppName{
    font-family: itc-avant-garde-gothic-pro,sans-serif; /* ITC Bold */
    font-weight: 700;
    font-style: normal;
    font-size: 42px;
    margin-top: 10%;
    margin-bottom: 0;
    text-align: left;
    font-size: 42px;
    width: 50%;
    margin-left: 5%;
    opacity: 80%;
}

.Description{
    color: #869FC9;
    width: 60%;
    margin-left: 5%;
    margin-top: 0;
    margin-bottom: 5%;
}

.AppDescription{
    opacity: 87%;
    width: 90%;
    margin: auto;
    font-family: realist, sans-serif;
    font-weight: 400;
    font-style: normal;
    font-size: 18px;
    margin-bottom: 2%;
}
</code>```

答:
Bootstrap has an example of the horizontal card and the image goes on top when it gets to a certain size.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>

AppName

Restaurant Payment Service - January 2020

App Description.

        Go somewhere

```

Body:
I am having trouble getting the content on the right of an image in a card to the be below the image using bootstrap and CSS. I have tried looking for solutions online and on the bootstrap documentation but I could not find anything that solves my problem. When I go below a certain responsive size I just want to position the AppName, Description and AppDescription below the image. Thanks for the help.

Html Below

AppName

Restaurant Payment Service - January 2020

App Description.

                View Project

CSS Below

.AppName{
    font-family: itc-avant-garde-gothic-pro,sans-serif; /* ITC Bold */
    font-weight: 700;
    font-style: normal;
    font-size: 42px;
    margin-top: 10%;
    margin-bottom: 0;
    text-align: left;
    font-size: 42px;
    width: 50%;
    margin-left: 5%;
    opacity: 80%;
}

.Description{
    color: #869FC9;
    width: 60%;
    margin-left: 5%;
    margin-top: 0;
    margin-bottom: 5%;
}

.AppDescription{
    opacity: 87%;
    width: 90%;
    margin: auto;
    font-family: realist, sans-serif;
    font-weight: 400;
    font-style: normal;
    font-size: 18px;
    margin-bottom: 2%;
}

Body:
Bootstrap has an example of the horizontal card and the image goes on top when it gets to a certain size.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="card mb-3" style="max-width: 540px;">
  <div class="row no-gutters">
    <div class="col-md-4">
      <img src="..." class="card-img" alt="...">
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <h5 class="card-title">AppName</h5>
        <p class="card-text">Restaurant Payment Service - January 2020</p>
        <p class="card-text AppDescription">App Description.</p>
        <a href="#" class="btn btn-primary">Go somewhere</a>
      </div>
    </div>
  </div>
</div>


问:
PHP: Loading content based on POST / GET user input
thank you for looking into my question. It's purely related to PHP POST / GET functions.

Here is my code :

index.php

```<code><html>
<body>
 <p>
<center>
<form action="story_get.php" method="post">
<label for="name">Name:</label> <input type="text" name="name">
<label for="age">Age:</label><input type="number" size=2 name="age"><p>
<label for="place">Place:</label> <input type="text" name="place"><p>

 <label for="storys">Choose a story:</label>
  <select name="story" id="story">
    <option value="sea">Sea side</option>
    <option value="mount">Mountain</option>
  </select>

<p>

<input type="submit" value="Enter">
<button type="reset" value="Reset">Reset</button>
</form>

</body>
</html>
</code>```

story_get.php

```<code><html>
<body>

<center>
<h1>Welcome <font color=red><i><?php echo $_POST["name"]; ?></i></font>, age of <font color=red><i><?php echo $_POST["age"]; ?></i></font><br>
to the wonderfull land of <br><font color=red><i><?php echo $_POST["place"]; ?></i></font>
<?php echo $_POST["story"]; ?>

 <p><a href=index.php>Edit</a>
</body>
</html>
</code>```

My code is working fine, but instead of <?php echo $_POST["story"]; ?> I want to print 200+ words story relating to what User has chosen. I hope You understand what I'm trying to achieve, and be able to suggest easy solutions. Thanks in advance

答:
You need to get that story from somewhere. A couple of ways to get there.

If you want to load it from a text file:

```<code>// Here we sanitize the story ID to avoid getting hacked:
$story_id = preg_replace('#[^a-zA-Z0-9_ -]#', '', $_POST['story']);

// Then we load the text file containing the story:

$path = 'stories/' . $story_id . '.txt';
$story_text = is_file($path) ? file_get_contents($path) : 'No such story!';
</code>```

If you want to load it from database:

```<code>$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT * FROM stories WHERE story_id = ? LIMIT 1");
$stmt->bind_param("s", $_POST['story']);
$stmt->execute();
$result = $stmt->get_result();
$story = $result->fetch_assoc();
$story_text = !empty($story['story_text']) ? $story['story_text'] : 'No such story!';
</code>```

This assumes you have a table called stories with fields story_id and story_text.

You could also have a separate file with all your stories assigned into variables (assuming you really just have a few, the performance impact of loading unused stories is minimal):

```<code>$stories['Seaside'] = <<<EOL
Here is the seaside story.
EOL;

$stories['Mountain'] = <<<EOL
Here is the mountain story.
EOL;
</code>```

And then in your story-telling file, you "load" it:

```<code>$story_text = !empty($stories[$_POST['story']) ? $stories[$_POST['story']] : 'No such story!';
</code>```

Then (with any of the above options), simply:

```<code><?php echo $story_text; ?>
</code>```

Of the options above, I would choose the text-file loading for sourcing your story text, if you're looking for something simple and easy to maintain. Good luck in telling your stories. :)

Assuming you want to use the form variables inside your stories. You'll want to use tokens, something like {{ place }}, and replace them before you output the story text:

```<code>$story_text = str_replace('{{ name }}', $_POST['name'], $story_text);
$story_text = str_replace('{{ place }}', $_POST['place'], $story_text);
</code>```

This would turn "once upon a time there was {{ name }} exploring {{ place }}..." into "once upon a time there was Светослав exploring Kamchatka Peninsula...", etc.

Body:
thank you for looking into my question. It's purely related to PHP POST / GET functions.

Here is my code :

index.php

<form action="story_get.php" method="post">
Name: <input type="text" name="name">
Age:<input type="number" size=2 name="age">

Place: <input type="text" name="place">

 Choose a story:
  <select name="story" id="story">
    <option value="sea">Sea side</option>
    <option value="mount">Mountain</option>
  </select>

<input type="submit" value="Enter">
<button type="reset" value="Reset">Reset</button>
</form>

story_get.php

Welcome <?php echo $_POST["name"]; ?>, age of <?php echo $_POST["age"]; ?>

to the wonderfull land of
<?php echo $_POST["place"]; ?>
<?php echo $_POST["story"]; ?>

Edit

My code is working fine, but instead of <?php echo $_POST["story"]; ?> I want to print 200+ words story relating to what User has chosen. I hope You understand what I'm trying to achieve, and be able to suggest easy solutions. Thanks in advance

Body:
You need to get that story from somewhere. A couple of ways to get there.

If you want to load it from a text file:

// Here we sanitize the story ID to avoid getting hacked:
$story_id = preg_replace('#[^a-zA-Z0-9_ -]#', '', $_POST['story']);

// Then we load the text file containing the story:

$path = 'stories/' . $story_id . '.txt';
$story_text = is_file($path) ? file_get_contents($path) : 'No such story!';

If you want to load it from database:

$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("SELECT * FROM stories WHERE story_id = ? LIMIT 1");
$stmt->bind_param("s", $_POST['story']);
$stmt->execute();
$result = $stmt->get_result();
$story = $result->fetch_assoc();
$story_text = !empty($story['story_text']) ? $story['story_text'] : 'No such story!';

This assumes you have a table called stories with fields story_id and story_text.

You could also have a separate file with all your stories assigned into variables (assuming you really just have a few, the performance impact of loading unused stories is minimal):

$stories['Seaside'] = <<<EOL
Here is the seaside story.
EOL;

$stories['Mountain'] = <<<EOL
Here is the mountain story.
EOL;

And then in your story-telling file, you "load" it:

$story_text = !empty($stories[$_POST['story']) ? $stories[$_POST['story']] : 'No such story!';

Then (with any of the above options), simply:

<?php echo $story_text; ?>

Of the options above, I would choose the text-file loading for sourcing your story text, if you're looking for something simple and easy to maintain. Good luck in telling your stories. :)

Assuming you want to use the form variables inside your stories. You'll want to use tokens, something like {{ place }}, and replace them before you output the story text:

$story_text = str_replace('{{ name }}', $_POST['name'], $story_text);
$story_text = str_replace('{{ place }}', $_POST['place'], $story_text);

This would turn "once upon a time there was {{ name }} exploring {{ place }}..." into "once upon a time there was Светослав exploring Kamchatka Peninsula...", etc.


问:
Split a list into N parts
Given a list, how can I split it into N sub-lists? They don't have necessarily have to be of the equal size. For instance, given 9 elements and split it into N = 3 sub-lists => 3x3. Or into N = 4 sub-lists => 2, 2, 2 and 1.

How can I do that? Isn't there a function in Elixir library?

Enum.split splits a list into 2 parts

update:

If I have 7 elements and I want to split them into 3 sub-lists, there should be created 3 sublists:

```<code>[[3 elements], [2 elements], [2 elements]]
</code>```

Namely, I want to preserve all the elements

答:
Found this question, but none of the current answers worked for my use case, for which I wanted the group sizes to be as uniform as possible. For example:

Enum.to_list(1..100) |> chunk_uniformly(6) |> Enum.map(&length/1)

# desired result is [17, 17, 17, 17, 16, 16]
# current accepted answer returns [20, 16, 16, 16, 16, 16]
```

<p>Here's my eventual solution:</p>

<pre class="lang-rb prettyprint-override"><code>def chunk_uniformly(list, number_of_chunks) do
  len = length(list)

  optimal_chunk_size = div(len + number_of_chunks - 1, number_of_chunks)

  overspill = optimal_chunk_size * number_of_chunks - len

  {full_chunks, partial_chunks} =
    list
    |> Enum.split((number_of_chunks - overspill) * optimal_chunk_size)

  Enum.concat(
    full_chunks |> Enum.chunk_every(optimal_chunk_size),
    case partial_chunks do
      [] -> List.duplicate([], overspill)
      ls -> ls |> Enum.chunk_every(optimal_chunk_size - 1)
    end
  )
end
</code>```

If, like in my use case, you're actually working from a maximum chunk size, you can get the number of chunks like this:

number_of_chunks = div(length(list) + max_chunk_size - 1, max_chunk_size)
```

Title: Split a list into N parts

Body:
Given a list, how can I split it into N sub-lists? They don't have necessarily have to be of the equal size. For instance, given 9 elements and split it into N = 3 sub-lists => 3x3. Or into N = 4 sub-lists => 2, 2, 2 and 1.

How can I do that? Isn't there a function in Elixir library?

Enum.split splits a list into 2 parts

update:

If I have 7 elements and I want to split them into 3 sub-lists, there should be created 3 sublists:

[[3 elements], [2 elements], [2 elements]]

Namely, I want to preserve all the elements

Body:
Found this question, but none of the current answers worked for my use case, for which I wanted the group sizes to be as uniform as possible. For example:

Enum.to_list(1..100) |> chunk_uniformly(6) |> Enum.map(&length/1)

# desired result is [17, 17, 17, 17, 16, 16]
# current accepted answer returns [20, 16, 16, 16, 16, 16]

Here's my eventual solution:

def chunk_uniformly(list, number_of_chunks) do
  len = length(list)

  optimal_chunk_size = div(len + number_of_chunks - 1, number_of_chunks)

  overspill = optimal_chunk_size * number_of_chunks - len

  {full_chunks, partial_chunks} =
    list
    |> Enum.split((number_of_chunks - overspill) * optimal_chunk_size)

  Enum.concat(
    full_chunks |> Enum.chunk_every(optimal_chunk_size),
    case partial_chunks do
      [] -> List.duplicate([], overspill)
      ls -> ls |> Enum.chunk_every(optimal_chunk_size - 1)
    end
  )
end

If, like in my use case, you're actually working from a maximum chunk size, you can get the number of chunks like this:

number_of_chunks = div(length(list) + max_chunk_size - 1, max_chunk_size)


问:
Unable to format binding value for (mengxiong10 / vue2-datepicker)
Unable to set binding value, coded as per documentation.

JsFiddle Example:
$[https://jsfiddle.net/zarpio/8stw7rvc/13/

OR

Full Code:

```<code><!DOCTYPE html>
<html>

<head>
  <title>Vue2 Datepicker</title>
</head>

<body>
  <div id="app">
    <section>
      <p>format</p>
      <date-picker v-model="value1" value-type="format" format="YYYY-MM-DD"></date-picker>
      <p>
        <code>v-model = {{ value1 }}</code>
      </p>
    </section>
    <section>
      <p>date (Date Object)</p>
      <date-picker v-model="value2" value-type="date"></date-picker>
      <p>
        <code>v-model = {{ value2 }}</code>
      </p>
    </section>
    <section>
      <p>timestamp</p>
      <date-picker v-model="value3" value-type="timestamp"></date-picker>
      <p>
        <code>v-model = {{ value3 }}</code>
      </p>
    </section>
    <section>
      <p>DD/MM/YYYY</p>
      <date-picker v-model="value4" value-type="DD/MM/YYYY" format="YYYY-MM-DD"></date-picker>
      <p>
        <code>v-model = {{ value4 }}</code>
      </p>
    </section>
  </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue2-datepicker@1.9.6/dist/build.min.js"></script>
    <script type="text/javascript">
    Vue.use(DatePicker.default);

    new Vue({
      el: '#app',

      data: {
        value1: '',
        value2: '',
        value3: '',
        value4: '',
        lang: {
          formatLocale: {
            firstDayOfWeek: 1,
          },
          monthBeforeYear: false,
        },
      },

      methods: {

      },

      computed: {

      }
    });
    </script>
</body>
</html>
</code>```

Problem:
As you can see it outputs in string format (Thu May 28 2020 00:00:00), but I need in format="2020-05-28"

答:
The package being used in the question is old, the following is working fine.</p>

```<code><html>
<head>
  <title>Vue2 Datepicker</title>
  <link href="http://p3backend.test/frontend/default/assets/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://unpkg.com/vue2-datepicker/index.css">
</head>
<body>
  <div id="app">
    <section>
      <p>format</p>
      <date-picker v-model="value1" value-type="format" format="YYYY-MM-DD"></date-picker>
      <p>
        <code>v-model = {{ value1 }}</code>
      </p>
    </section>
    <section>
      <p>date (Date Object)</p>
      <date-picker v-model="value2" value-type="date"></date-picker>
      <p>
        <code>v-model = {{ value2 }}</code>
      </p>
    </section>
    <section>
      <p>timestamp</p>
      <date-picker v-model="value3" value-type="timestamp"></date-picker>
      <p>
        <code>v-model = {{ value3 }}</code>
      </p>
    </section>
    <section>
      <p>DD/MM/YYYY</p>
      <date-picker v-model="value4" value-type="DD/MM/YYYY" format="YYYY-MM-DD"></date-picker>
      <p>
        <code>v-model = {{ value4 }}</code>
      </p>
    </section>
  </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue2-datepicker/index.min.js"></script>
    <script type="text/javascript">
    new Vue({
      el: '#app',
      data: {
        value1: '',
        value2: '',
        value3: '',
        value4: '',
      },
    });
    </script>
</body>
</html>```
</code>```

Body:
Unable to set binding value, coded as per documentation.

JsFiddle Example:
$[https://jsfiddle.net/zarpio/8stw7rvc/13/

OR

Full Code:

<!DOCTYPE html>

  <title>Vue2 Datepicker</title>

format

      <date-picker v-model="value1" value-type="format" format="YYYY-MM-DD"></date-picker>

        v-model = {{ value1 }}

date (Date Object)

      <date-picker v-model="value2" value-type="date"></date-picker>

        v-model = {{ value2 }}

timestamp

      <date-picker v-model="value3" value-type="timestamp"></date-picker>

        v-model = {{ value3 }}

DD/MM/YYYY

      <date-picker v-model="value4" value-type="DD/MM/YYYY" format="YYYY-MM-DD"></date-picker>

        v-model = {{ value4 }}

Problem:
As you can see it outputs in string format (Thu May 28 2020 00:00:00), but I need in format="2020-05-28"

Body:
The package being used in the question is old, the following is working fine.

<html>
<head>
  <title>Vue2 Datepicker</title>
  <link href="http://p3backend.test/frontend/default/assets/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://unpkg.com/vue2-datepicker/index.css">
</head>
<body>
  <div id="app">
    <section>
      <p>format</p>
      <date-picker v-model="value1" value-type="format" format="YYYY-MM-DD"></date-picker>
      <p>
        <code>v-model = {{ value1 }}</code>
      </p>
    </section>
    <section>
      <p>date (Date Object)</p>
      <date-picker v-model="value2" value-type="date"></date-picker>
      <p>
        <code>v-model = {{ value2 }}</code>
      </p>
    </section>
    <section>
      <p>timestamp</p>
      <date-picker v-model="value3" value-type="timestamp"></date-picker>
      <p>
        <code>v-model = {{ value3 }}</code>
      </p>
    </section>
    <section>
      <p>DD/MM/YYYY</p>
      <date-picker v-model="value4" value-type="DD/MM/YYYY" format="YYYY-MM-DD"></date-picker>
      <p>
        <code>v-model = {{ value4 }}</code>
      </p>
    </section>
  </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/vue2-datepicker/index.min.js"></script>
    <script type="text/javascript">
    new Vue({
      el: '#app',
      data: {
        value1: '',
        value2: '',
        value3: '',
        value4: '',
      },
    });
    </script>
</body>
</html>```


问:
Setting becomeFirstResponder on viewController nested in PageViewController
I have a pageViewController that has two child view controllers that you can swipe between. One of them has a textView that I want to be the first responder when you scroll onto that page, then lose focus when you scroll away. Right now I have this:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    composeTextView.delegate = self
    composeTextView.becomeFirstResponder()
}
</code>```

The keyboard shows up as soon as you start to scroll onto the view. But as soon as the scrolling finishes, the keyboard disappears.

Any ideas why this is happening?

答:
It works ok transition style Page Curl but not with Scroll.

I think the problem is immediately after viewDidAppear the old page resigns first responder and a new one is chosen thus whatever you set as firstResponder is lost. This is caused by the old and new view being repeatedly added and removed from the window which affects the responder chain. I think that after the old view scrolls off screen it is added back to the window for some reason because when you scroll back to it, it's ready to go.

As you can see in this log, after viewDidAppear there are many odd changes to both view's window. The new view is 0x7fd87fa24160 so why is the old view 0x7fd87fa059a0 being removed and added to the window multiple times?

```<code>2020-06-01 10:22:14.093911+0100 Paging2[45575:3540067] DetailViewController 0x7fd87fa15850 viewDidAppear: 0x7fd87fa24160
2020-06-01 10:22:14.094973+0100 Paging2[45575:3540067] MyView 0x7fd87fa059a0 didMoveToWindow 0x0
2020-06-01 10:22:14.095358+0100 Paging2[45575:3540067] MyView 0x7fd87fa24160 didMoveToWindow 0x0
2020-06-01 10:22:14.096090+0100 Paging2[45575:3540067] MyView 0x7fd87fa059a0 didMoveToWindow 0x7fd87f80f3d0
2020-06-01 10:22:14.096511+0100 Paging2[45575:3540067] MyView 0x7fd87fa24160 didMoveToWindow 0x7fd87f80f3d0
2020-06-01 10:22:14.099019+0100 Paging2[45575:3540067] MyView 0x7fd87fa059a0 didMoveToWindow 0x0
2020-06-01 10:22:14.099318+0100 Paging2[45575:3540067] MyView 0x7fd87fa24160 didMoveToWindow 0x0
2020-06-01 10:22:14.099812+0100 Paging2[45575:3540067] MyView 0x7fd87fa059a0 didMoveToWindow 0x7fd87f80f3d0
2020-06-01 10:22:14.100306+0100 Paging2[45575:3540067] MyView 0x7fd87fa24160 didMoveToWindow 0x7fd87f80f3d0
</code>```

For comparison here is UINavigationController when pushing. I learned in this question that the extra move to window is for the transition, turning on slow animations helps:

```<code>2020-06-01 10:49:16.786872+0100 NavWindowTest[45792:3560379] View 0x7fbfba608090 didMoveToWindow 0x0 (current view removed from window)
2020-06-01 10:49:16.787170+0100 NavWindowTest[45792:3560379] View 0x7fbfba608090 didMoveToWindow 0x7fbfba50c150 (current view added to window for transition)
2020-06-01 10:49:16.787577+0100 NavWindowTest[45792:3560379] View 0x7fbfba5124d0 didMoveToWindow 0x7fbfba50c150 (new view added)
2020-06-01 10:49:21.801791+0100 NavWindowTest[45792:3560379] View 0x7fbfba608090 didMoveToWindow 0x0 (old view removed from transition)
2020-06-01 10:49:21.803690+0100 NavWindowTest[45792:3560379] ViewController 0x7fbfbd005dd0 viewDidAppear: 0x7fbfba5124d0
</code>```

The fact that viewDidAppear is called last when navigating but first in paging makes me think there is a problem.

Body:
I have a pageViewController that has two child view controllers that you can swipe between. One of them has a textView that I want to be the first responder when you scroll onto that page, then lose focus when you scroll away. Right now I have this:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    composeTextView.delegate = self
    composeTextView.becomeFirstResponder()
}

The keyboard shows up as soon as you start to scroll onto the view. But as soon as the scrolling finishes, the keyboard disappears.

Any ideas why this is happening?

Body:
It works ok transition style Page Curl but not with Scroll.

I think the problem is immediately after viewDidAppear the old page resigns first responder and a new one is chosen thus whatever you set as firstResponder is lost. This is caused by the old and new view being repeatedly added and removed from the window which affects the responder chain. I think that after the old view scrolls off screen it is added back to the window for some reason because when you scroll back to it, it's ready to go.

As you can see in this log, after viewDidAppear there are many odd changes to both view's window. The new view is 0x7fd87fa24160 so why is the old view 0x7fd87fa059a0 being removed and added to the window multiple times?

2020-06-01 10:22:14.093911+0100 Paging2[45575:3540067] DetailViewController 0x7fd87fa15850 viewDidAppear: 0x7fd87fa24160
2020-06-01 10:22:14.094973+0100 Paging2[45575:3540067] MyView 0x7fd87fa059a0 didMoveToWindow 0x0
2020-06-01 10:22:14.095358+0100 Paging2[45575:3540067] MyView 0x7fd87fa24160 didMoveToWindow 0x0
2020-06-01 10:22:14.096090+0100 Paging2[45575:3540067] MyView 0x7fd87fa059a0 didMoveToWindow 0x7fd87f80f3d0
2020-06-01 10:22:14.096511+0100 Paging2[45575:3540067] MyView 0x7fd87fa24160 didMoveToWindow 0x7fd87f80f3d0
2020-06-01 10:22:14.099019+0100 Paging2[45575:3540067] MyView 0x7fd87fa059a0 didMoveToWindow 0x0
2020-06-01 10:22:14.099318+0100 Paging2[45575:3540067] MyView 0x7fd87fa24160 didMoveToWindow 0x0
2020-06-01 10:22:14.099812+0100 Paging2[45575:3540067] MyView 0x7fd87fa059a0 didMoveToWindow 0x7fd87f80f3d0
2020-06-01 10:22:14.100306+0100 Paging2[45575:3540067] MyView 0x7fd87fa24160 didMoveToWindow 0x7fd87f80f3d0

For comparison here is UINavigationController when pushing. I learned in this question that the extra move to window is for the transition, turning on slow animations helps:

2020-06-01 10:49:16.786872+0100 NavWindowTest[45792:3560379] View 0x7fbfba608090 didMoveToWindow 0x0 (current view removed from window)
2020-06-01 10:49:16.787170+0100 NavWindowTest[45792:3560379] View 0x7fbfba608090 didMoveToWindow 0x7fbfba50c150 (current view added to window for transition)
2020-06-01 10:49:16.787577+0100 NavWindowTest[45792:3560379] View 0x7fbfba5124d0 didMoveToWindow 0x7fbfba50c150 (new view added)
2020-06-01 10:49:21.801791+0100 NavWindowTest[45792:3560379] View 0x7fbfba608090 didMoveToWindow 0x0 (old view removed from transition)
2020-06-01 10:49:21.803690+0100 NavWindowTest[45792:3560379] ViewController 0x7fbfbd005dd0 viewDidAppear: 0x7fbfba5124d0

The fact that viewDidAppear is called last when navigating but first in paging makes me think there is a problem.


问:
QR report of size A5 to be repeated on an A4 paper sheet
BDS2006, QR4.

I have an A5 size report and I want(well, the customer does :)) to print it twice on an A4 paper sheet. This is because they need to cut the two halves and keep one "for the record" while handing out the other one.

Anybody knows a trick to do this without having to add yet another repo?

Thank you!

Andrea

答:
Ok, I will post the answer since no one has come up with a better idea... yet!
What I had to do is using a composite report and then just adding the reports on the AddReports event.

I added two times the same report and QR didn't complain.

Last, just use the preview to see it on screen et voila'!

Andrea