问:
Can I have multiple POSIX FIFOs in a single process?
I am creating three FIFO pipes for a single process where multiple writer threads write to a single reader thread.  The goal is a separate file descriptor for each writer thread with a corresponding reader file descriptor for each writer file descriptor so that I know which writer thread belongs to each record.  My setup works fine with one writer file descriptor shared among all writer threads and a single reader file descriptor.

The multiple reader/writer setup works successfully to set up three writer fds (6, 7, 8) and three reader fds (9, 10 and 11).  All writer threads successfully send data, BUT the reader fds do not successfully read the data (return zero bytes read).

When I open the fd on the writer side, I get the error message "open: Bad file descriptor" but it still returns a unique fd, and that fd is used successfully to write, but not to read.

I call the C programs from NASM in a loop, one iteration for each writer thread:

```<code>xor r12,r12
mov r13,[Number_Of_Cores_Calc]
Setup_pipe:
lea rdi,[fifo_base_name]
mov rax,r12
add rax,48
mov byte[rdi+11],al
call fifo_delete wrt ..plt
call fifo_setup wrt ..plt
push rdi
call fifo_close wrt ..plt
pop rdi
Open_FIFO_Write:
mov rsi,1
call fifo_open wrt ..plt
lea rbp,[fifo_write_fds]
mov [rbp+r12*8],rax
add r12,1
cmp r12,r13
jl Setup_pipe
</code>```

The corresponding C programs:

```<code>int64_t fifo_setup(char * fifo_name)
{

    remove(fifo_name);

    if (mkfifo(fifo_name, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE); }

        return 0;
}

int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_CREAT | O_RDWR);} //O_WRONLY
    if (read_write == 2) {
        c = open(fifo_name, O_CREAT | O_RDWR);} //O_RDONLY

    perror("open");

    return (c);
}

int64_t fifo_read(int fd, void *buf, size_t count) {

    int status_read = read(fd, buf, count);
    return status_read;
}

int64_t fifo_write(int fd, const void *buf, size_t count) {

    int status_write = write(fd, buf, count);
    return status_write; }

int64_t fifo_close(int fifo_fdes) {

    close(fifo_fdes);

    return 0; }

// Delete pre-existing file
int64_t fifo_delete(char * fifo_name) {

    if( access( fifo_name, F_OK ) != -1 ) {
        if (remove(fifo_name) == 0)
        printf("File deleted successfully");
    else
        printf("Unable to delete the file");
    }

    return 0; }
</code>```

So my questions are:

Can I write from multiple threads to a single reader thread using separate fds for each thread on both the write and read sides?

If I can, what did I do wrong above -- especially why am I getting "open: Bad file descriptor" but I still get what looks like a valid file descriptor.

If I can't use POSIX FIFOs, what IPC methods can I use so each writer thread has its own unique fd on both writer and reader sides?  Datagram sockets?

Thanks for any help on this.

答:
perror("open");

You cannot simply call perror() as it can return the previous error.
You have to check whether your syscall indeed generated an error. In case of open() you should do:

```<code>if (c < 0) {
   perror("open");
}
</code>```

Body:
I am creating three FIFO pipes for a single process where multiple writer threads write to a single reader thread.  The goal is a separate file descriptor for each writer thread with a corresponding reader file descriptor for each writer file descriptor so that I know which writer thread belongs to each record.  My setup works fine with one writer file descriptor shared among all writer threads and a single reader file descriptor.

The multiple reader/writer setup works successfully to set up three writer fds (6, 7, 8) and three reader fds (9, 10 and 11).  All writer threads successfully send data, BUT the reader fds do not successfully read the data (return zero bytes read).

When I open the fd on the writer side, I get the error message "open: Bad file descriptor" but it still returns a unique fd, and that fd is used successfully to write, but not to read.

I call the C programs from NASM in a loop, one iteration for each writer thread:

xor r12,r12
mov r13,[Number_Of_Cores_Calc]
Setup_pipe:
lea rdi,[fifo_base_name]
mov rax,r12
add rax,48
mov byte[rdi+11],al
call fifo_delete wrt ..plt
call fifo_setup wrt ..plt
push rdi
call fifo_close wrt ..plt
pop rdi
Open_FIFO_Write:
mov rsi,1
call fifo_open wrt ..plt
lea rbp,[fifo_write_fds]
mov [rbp+r12*8],rax
add r12,1
cmp r12,r13
jl Setup_pipe

The corresponding C programs:

int64_t fifo_setup(char * fifo_name)
{

    remove(fifo_name);

    if (mkfifo(fifo_name, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE); }

        return 0;
}

int64_t fifo_open(char * fifo_name, int64_t read_write) {

    int c;

    if (read_write == 1) {
        c = open(fifo_name, O_CREAT | O_RDWR);} //O_WRONLY
    if (read_write == 2) {
        c = open(fifo_name, O_CREAT | O_RDWR);} //O_RDONLY

    perror("open");

    return (c);
}

int64_t fifo_read(int fd, void *buf, size_t count) {

    int status_read = read(fd, buf, count);
    return status_read;
}

int64_t fifo_write(int fd, const void *buf, size_t count) {

    int status_write = write(fd, buf, count);
    return status_write; }

int64_t fifo_close(int fifo_fdes) {

    close(fifo_fdes);

    return 0; }

// Delete pre-existing file
int64_t fifo_delete(char * fifo_name) {

    if( access( fifo_name, F_OK ) != -1 ) {
        if (remove(fifo_name) == 0)
        printf("File deleted successfully");
    else
        printf("Unable to delete the file");
    }

    return 0; }

So my questions are:

Can I write from multiple threads to a single reader thread using separate fds for each thread on both the write and read sides?

If I can, what did I do wrong above -- especially why am I getting "open: Bad file descriptor" but I still get what looks like a valid file descriptor.

If I can't use POSIX FIFOs, what IPC methods can I use so each writer thread has its own unique fd on both writer and reader sides?  Datagram sockets?

Thanks for any help on this.

Body:
perror("open");

You cannot simply call perror() as it can return the previous error.
You have to check whether your syscall indeed generated an error. In case of open() you should do:

if (c < 0) {
   perror("open");
}


来源: stackexchange

问:
Is there a way to get a schema of a database from within python?
I'm trying to find out a way to find the names of tables in a database(if any exist).  I find that from a sqlite cli I can use:

```<code>>.tables
</code>```

Then for the fields:

```<code>>PRAGMA TABLE_INFO(table_name)
</code>```

This obviously doesn't work within python.  Is there even a way to do this with python or should I just be using the sqlite command-line?

答:
make the connection to the database

```<code>connection = connect_db('./database_name.db')
</code>```

print the table names

```<code>table_names = [t[0] for t in connection.execute("SELECT name FROM sqlite_master WHERE type='table';")]
print(table_names)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find out a way to find the names of tables in a database(if any exist).  I find that from a sqlite cli I can use:

>.tables

Then for the fields:

>PRAGMA TABLE_INFO(table_name)

This obviously doesn't work within python.  Is there even a way to do this with python or should I just be using the sqlite command-line?

Body:
make the connection to the database

connection = connect_db('./database_name.db')

print the table names

table_names = [t[0] for t in connection.execute("SELECT name FROM sqlite_master WHERE type='table';")]
print(table_names)

ContentLicense: CC BY-SA 4.0


问:
array.push() method is not adding anything to array and working weirdly
I am new to programming and also stackoverflow.
My problem is related to array.push() method in JavaScript.
See the code first

```<code>var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern = gamePattern.push(nextSequence());

function nextSequence(){
        var randomNumber = Math.floor( Math.random() * 4);
        var randomChosenColor = buttonColors[randomNumber];
        return randomChosenColor;
}
</code>```

Kindly check this image too...
This is chrome console output

The problem is that the randomNumber is being generated properly and randomChosenColor is also getting the color properly but it is not being pushed in gamePattern array at line number 3. Also help me if there is some alternative to this method.

答:
push() mutates the original array (and returns the new length), so you don't need to assign a new value to gamePattern. Try something like this:

```<code>var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern.push(nextSequence());

function nextSequence(){
  var randomNumber = Math.floor(Math.random() * 4);
  var randomChosenColor = buttonColors[randomNumber];
  return randomChosenColor;
}
</code>```

Body:
I am new to programming and also stackoverflow.
My problem is related to array.push() method in JavaScript.
See the code first

var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern = gamePattern.push(nextSequence());

function nextSequence(){
        var randomNumber = Math.floor( Math.random() * 4);
        var randomChosenColor = buttonColors[randomNumber];
        return randomChosenColor;
}

Kindly check this image too...
This is chrome console output

The problem is that the randomNumber is being generated properly and randomChosenColor is also getting the color properly but it is not being pushed in gamePattern array at line number 3. Also help me if there is some alternative to this method.

Body:
push() mutates the original array (and returns the new length), so you don't need to assign a new value to gamePattern. Try something like this:

var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
gamePattern.push(nextSequence());

function nextSequence(){
  var randomNumber = Math.floor(Math.random() * 4);
  var randomChosenColor = buttonColors[randomNumber];
  return randomChosenColor;
}


问:
Dataframe ValueError: could not convert string to float:
I have a dataframe as follows:

```<code>     Score
0   16-1/4
1        9
2        5
3    3-1/2
4        4
</code>```

I would like to change it to float, such that:

```<code>     Score
0    16.25
1      9.0
2      5.0
3      3.5
4      4.0
</code>```

To make it, I have developed my code:

```<code>import pandas as pd

def to_float(value):
    if '-' in value:
        return float(value.split("-")[0].strip('\t')) + (float((value.split("-")[1]).split("/")[0].strip('\t')) / float((value.split("-")[1]).split("/")[1].strip('\t')))
    else:
        return value

df['Score'] = df['Score'].map(to_float)
</code>```

But it turns out an error: ValueError: could not convert string to float:

答:
Use eval in Series.apply only if need subtract values:

```<code>df['Score'] = df['Score'].apply(pd.eval)
print (df)
  Score
0  15.75
1   9.00
2   5.00
3   2.50
4   4.00
</code>```

If want sum values:

```<code>df['Score'] = df['Score'].replace('-','+', regex=True).apply(pd.eval)
print (df)
   Score
0  16.25
1   9.00
2   5.00
3   3.50
4   4.00
</code>```

Body:
I have a dataframe as follows:

     Score
0   16-1/4
1        9
2        5
3    3-1/2
4        4

I would like to change it to float, such that:

     Score
0    16.25
1      9.0
2      5.0
3      3.5
4      4.0

To make it, I have developed my code:

import pandas as pd

def to_float(value):
    if '-' in value:
        return float(value.split("-")[0].strip('\t')) + (float((value.split("-")[1]).split("/")[0].strip('\t')) / float((value.split("-")[1]).split("/")[1].strip('\t')))
    else:
        return value

df['Score'] = df['Score'].map(to_float)

But it turns out an error: ValueError: could not convert string to float:

Body:
Use eval in Series.apply only if need subtract values:

df['Score'] = df['Score'].apply(pd.eval)
print (df)
  Score
0  15.75
1   9.00
2   5.00
3   2.50
4   4.00

If want sum values:

df['Score'] = df['Score'].replace('-','+', regex=True).apply(pd.eval)
print (df)
   Score
0  16.25
1   9.00
2   5.00
3   3.50
4   4.00


问:
How to protect a button in disabled mode?
I want to disable a button if user doesnt have rights to access it. I am
                            disabling at Page_Load event

```<code> Page_Load() {
      if(!userhasrights) {
           btn.Enabled=false;
      }
 }
</code>```

but after rendering asp.net just sets its disabled property to disabled which
                        a hacker can easily set to 'true' & can access the button. How can i
                        protect my button in disabled mode?

答:
You cannot protect the html state of the button, since users can always modify it.

You should have server-side validation when the button is pressed, and return error/warning to users who are not authorized to click on it. You can still user the disable state for usability.

The other solution is not to generate the button when the users are not authorized to click on it. If you really need to have the disabled button, add an image instead of a button.

Body:
I want to disable a button if user doesnt have rights to access it. I am
                            disabling at Page_Load event

 Page_Load() {
      if(!userhasrights) {
           btn.Enabled=false;
      }
 }

but after rendering asp.net just sets its disabled property to disabled which
                        a hacker can easily set to 'true' & can access the button. How can i
                        protect my button in disabled mode?


问:
How to check if an array has squared elements of another array (regardless of order)?
a = [121, 144, 19, 161, 19, 144, 19, 11]

b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
returns true, coz b[] has squared values of elements in a[], regardless of order.

Here's what I tried...

```<code>static boolean comp(int a[], int b[]) {
        int x = 0;
        if (a.equals(b)) {
            for (int i : a) {
                for (int j : b) {
                    if (a[i] == b[j] * b[j]) {
                        x++;
                    } else {
                        x--;
                    }
                }
            }
        } else {
            return false;
        }
        if (x == a.length) {
            return true;
        } else {
            return false;
        }
    }
</code>```

答:
```<code>public static Boolean compare(int[] a, int[] b) {
  Arrays.sort(a);
  Arrays.sort(b);
  for (int i = 0; i < a.length; i++) {
    if (a[i] * a[i] != b[i]) {
      return false;
    }
  }
  return true;
}
</code>```

Body:
a = [121, 144, 19, 161, 19, 144, 19, 11]

b = [121, 14641, 20736, 361, 25921, 361, 20736, 361]
returns true, coz b[] has squared values of elements in a[], regardless of order.

Here's what I tried...

static boolean comp(int a[], int b[]) {
        int x = 0;
        if (a.equals(b)) {
            for (int i : a) {
                for (int j : b) {
                    if (a[i] == b[j] * b[j]) {
                        x++;
                    } else {
                        x--;
                    }
                }
            }
        } else {
            return false;
        }
        if (x == a.length) {
            return true;
        } else {
            return false;
        }
    }


问:
readline() code in my python app works not correctly. Why?
I am building an app by python3.8.3 and pyqt5. This is a part of my code:

```<code>def logupd(self):
        users=open('NeveshtarUsers.txt', 'w')
        users.write('Username: ')
        users.write(self.user2.text())
        users.write(' Password: ')
        users.write(self.pass2.text())
        users.write('.\n')
        users.write('Name: ')
        users.write(self.name.text())
        users.write('.\n')
        users.write('....................\n')
        self.no.setText('Loggind up has succesed. Please Login')

        with open('NeveshtarUsers.txt') as file:
            print('salam')
            data = file.readlines()
            print(data)
</code>```

When I call this code, the output is:

```<code>salam
[]
</code>```

Why data is empty? What's the problem?

答:
I think the problem is not closing the file that is open in write mode</p>

```<code>def logupd(self):
        users=open('NeveshtarUsers.txt', 'w')
        users.write('Username: ')
        users.write(self.user2.text())
        users.write(' Password: ')
        users.write(self.pass2.text())
        users.write('.\n')
        users.write('Name: ')
        users.write(self.name.text())
        users.write('.\n')
        users.write('....................\n')
        self.no.setText('Loggind up has succesed. Please Login')
        # close the file that is opened in write , the text will get updated to the system's memory
        # only when the file is closed
        users.close()
        with open('NeveshtarUsers.txt') as file:
            print('salam')
            data = file.readlines()
            print(data)
</code>```

Body:
I am building an app by python3.8.3 and pyqt5. This is a part of my code:

def logupd(self):
        users=open('NeveshtarUsers.txt', 'w')
        users.write('Username: ')
        users.write(self.user2.text())
        users.write(' Password: ')
        users.write(self.pass2.text())
        users.write('.\n')
        users.write('Name: ')
        users.write(self.name.text())
        users.write('.\n')
        users.write('....................\n')
        self.no.setText('Loggind up has succesed. Please Login')

        with open('NeveshtarUsers.txt') as file:
            print('salam')
            data = file.readlines()
            print(data)

When I call this code, the output is:

salam
[]

Why data is empty? What's the problem?

Body:
I think the problem is not closing the file that is open in write mode

def logupd(self):
        users=open('NeveshtarUsers.txt', 'w')
        users.write('Username: ')
        users.write(self.user2.text())
        users.write(' Password: ')
        users.write(self.pass2.text())
        users.write('.\n')
        users.write('Name: ')
        users.write(self.name.text())
        users.write('.\n')
        users.write('....................\n')
        self.no.setText('Loggind up has succesed. Please Login')
        # close the file that is opened in write , the text will get updated to the system's memory
        # only when the file is closed
        users.close()
        with open('NeveshtarUsers.txt') as file:
            print('salam')
            data = file.readlines()
            print(data)


问:
Difference between gatsby-theme-material-ui and gatsby-plugin-material-ui
I am designing a web page with gatsby and I would like to use material UI, but I don't know which plugin to use.

My questions are :

Is there a difference between those two, and how can I implement them in order to have a Theme Customized ?

Where should I put the theme.js and where to put the ThemeProvider wrapper ?

How to configure the project ?

答:
Both packages do the trick: Get Material UI into your project.

The difference is that gatsby-theme-material-ui is more complete and user-friendly for beginners.  For example with the plugin, you have to make sure you load the roboto font or the MUI theme yourself. The theme sets everything you need for Material UI up for you and you can start developing right away.

All the plugin does is to make sure the Material UI styles are properly loaded into your project. This is important because of how Gatsby works with server-side rendering. This can be tricky to get right and understand when starting out. But you still have to get your fonts and the theme provider setup as explained in the docs.

There is a technical comparison what each plugin does:

Theme vs. Plugin

gatsby-plugin-material-ui solves FOUC, auto prefixing and minification.

gatsby-theme-material-ui uses the plugin under the hood, adds web fonts, meta-viewport, CSS baseline and mui theme support and has material ui styled gatsby link components

For new users I would recommend gatsby-theme-material-ui

how can I implement them in order to have a Theme Customized

Follow the documentation. Create the file src/gatsby-theme-material-ui-top-layout/theme.js and use this file to customize your theme as described in the MUI docs.

Where should I put the theme.js and where to put the ThemeProvider wrapper

Follow the documentation. Create a provider in src/gatsby-theme-material-ui-top-layout/components/top-layout.js.

And also how to configure the project

Follow the documentation.

```<code>// with npm
npm install gatsby-theme-material-ui @material-ui/core

// with yarn
yarn add gatsby-theme-material-ui @material-ui/core
</code>```

Edit gatsby-config.js

```<code>module.exports = {
  plugins: [
    // ... other plugins
    `gatsby-theme-material-ui`
  ],
};
</code>```

Your Gatsby configuration is done.

Body:
Both packages do the trick: Get Material UI into your project.

The difference is that gatsby-theme-material-ui is more complete and user-friendly for beginners.  For example with the plugin, you have to make sure you load the roboto font or the MUI theme yourself. The theme sets everything you need for Material UI up for you and you can start developing right away.

All the plugin does is to make sure the Material UI styles are properly loaded into your project. This is important because of how Gatsby works with server-side rendering. This can be tricky to get right and understand when starting out. But you still have to get your fonts and the theme provider setup as explained in the docs.

There is a technical comparison what each plugin does:

Theme vs. Plugin

gatsby-plugin-material-ui solves FOUC, auto prefixing and minification.

gatsby-theme-material-ui uses the plugin under the hood, adds web fonts, meta-viewport, CSS baseline and mui theme support and has material ui styled gatsby link components

For new users I would recommend gatsby-theme-material-ui

how can I implement them in order to have a Theme Customized

Follow the documentation. Create the file src/gatsby-theme-material-ui-top-layout/theme.js and use this file to customize your theme as described in the MUI docs.

Where should I put the theme.js and where to put the ThemeProvider wrapper

Follow the documentation. Create a provider in src/gatsby-theme-material-ui-top-layout/components/top-layout.js.

And also how to configure the project

Follow the documentation.

// with npm
npm install gatsby-theme-material-ui @material-ui/core

// with yarn
yarn add gatsby-theme-material-ui @material-ui/core

Edit gatsby-config.js

module.exports = {
  plugins: [
    // ... other plugins
    `gatsby-theme-material-ui`
  ],
};

Your Gatsby configuration is done.


问:
Efficient atomic bulk refresh operation in MariaDB for many to many relation
I need to keep a list of unique pages in a pages table linked in a many-to-many relation with page_providers table via page_xref_page_provider table. I am having difficulty with devising an efficient atomic bulk refresh operation, consisting of the following:

A new list of pages is received from a page provider. Some pages on that list may be the same as already on record in the database (having the same Url), while some pages may be deleted from the list and some pages may be added.

There are some per-page statistics in the database, so I shouldn't delete an old page (identified by unique Url) if there is at least one page provider for whom this page is still on the list.

If the updated list from the current page provider doesn't contain a page it previously contained, and no other page list provider contains this page on its list, the page should be deleted from the pages table.

Pages that are not on record by the moment I receive the page list, must be added to pages table and cross-referenced in page_xref_page_provider

What I have tried:

```<code>-- We use IGNORE to handle duplicate URLs on the list we received from the current page provider
-- pages_temp is a temporary table whose creation I have omitted
INSERT IGNORE INTO pages_temp (Url, Host, Port) VALUES (?, ?, ?);

BEGIN;

-- In the DB client program, we get the last inserted ID from the following query and the number of
--   rows affected, so to get a range of newly inserted IDs
INSERT IGNORE INTO pages (Url, Host, Port) SELECT Url, Host, Port FROM pages_temp;

-- This doesn't work (wrong syntax), could you correct me here?
-- When preparing this statement, we parameterize it with the current PageProviderID, the
--   last inserted ID (which is actually the first ID in the bulk) and the number of rows inserted
--   plus the first ID in the bulk.
INSERT INTO page_xref_page_provider (PageProviderID, PageID) SELECT ?, i BETWEEN ? AND ?;

-- This query is parametrized with the current page provider ID
DELETE page_xref_page_provider FROM page_xref_page_provider AS pxpp
JOIN pages ON pxpp.PageID = pages.ID AND pxpp.PageProviderID=?
WHERE pages.Url NOT IN (SELECT Url FROM pages_temp);

-- This seems inefficient because the subquery also fetch the relations not affected by the current
--   list of pages / page provider
DELETE FROM pages WHERE pages.ID NOT IN (SELECT DISTINCT PageID FROM page_xref_page_provider);

COMMIT;
</code>```

答:
Avoid NOT IN ( SELECT ... ).  In some situations, its performance is terrible.  LEFT JOIN and EXISTS may work faster.

Are there AUTO_INCREMENT ids in the tables?  If so, beware of IGNORE "burning ids".

Here is a discussion of a high-speed ingestion technique:  http://mysql.rjweb.org/doc.php/staging_table

Performance tips on many-to-many tables:  http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

Body:
I need to keep a list of unique pages in a pages table linked in a many-to-many relation with page_providers table via page_xref_page_provider table. I am having difficulty with devising an efficient atomic bulk refresh operation, consisting of the following:

A new list of pages is received from a page provider. Some pages on that list may be the same as already on record in the database (having the same Url), while some pages may be deleted from the list and some pages may be added.

There are some per-page statistics in the database, so I shouldn't delete an old page (identified by unique Url) if there is at least one page provider for whom this page is still on the list.

If the updated list from the current page provider doesn't contain a page it previously contained, and no other page list provider contains this page on its list, the page should be deleted from the pages table.

Pages that are not on record by the moment I receive the page list, must be added to pages table and cross-referenced in page_xref_page_provider

What I have tried:

-- We use IGNORE to handle duplicate URLs on the list we received from the current page provider
-- pages_temp is a temporary table whose creation I have omitted
INSERT IGNORE INTO pages_temp (Url, Host, Port) VALUES (?, ?, ?);

BEGIN;

-- In the DB client program, we get the last inserted ID from the following query and the number of
--   rows affected, so to get a range of newly inserted IDs
INSERT IGNORE INTO pages (Url, Host, Port) SELECT Url, Host, Port FROM pages_temp;

-- This doesn't work (wrong syntax), could you correct me here?
-- When preparing this statement, we parameterize it with the current PageProviderID, the
--   last inserted ID (which is actually the first ID in the bulk) and the number of rows inserted
--   plus the first ID in the bulk.
INSERT INTO page_xref_page_provider (PageProviderID, PageID) SELECT ?, i BETWEEN ? AND ?;

-- This query is parametrized with the current page provider ID
DELETE page_xref_page_provider FROM page_xref_page_provider AS pxpp
JOIN pages ON pxpp.PageID = pages.ID AND pxpp.PageProviderID=?
WHERE pages.Url NOT IN (SELECT Url FROM pages_temp);

-- This seems inefficient because the subquery also fetch the relations not affected by the current
--   list of pages / page provider
DELETE FROM pages WHERE pages.ID NOT IN (SELECT DISTINCT PageID FROM page_xref_page_provider);

COMMIT;


问:
Ansible synchronize always sets changed
I need to set the contents of a dest folder to be the same as my src folder.  So I am using the synchronize module:

```<code>- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  register: result
</code>```

But this sets "changed" to 'true' in result, even when there was no change.   I need this to be only set to 'true' if there was a something changed because the next task tests for this state.

If I repeat the same synchronize task right after this one it doesn't set 'changed' to 'true'.  But that one always doesn't get set to 'true'.

Subsequent runs of the play with no change to the src ("/data/managedFiles/lib/{{ runtime.version }}/user/") always set result with 'changed'.

答:
You can have some pre-condition like this:

```<code>- name: check dest directory exists
  stat:
     path: {{ mule_directory }}{{ mule_runtime_name }}/lib/user/
  register: exist_dir

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  when: not exist_dir.stat.exists
  register: result
</code>```

or

```<code>- name: Check whether {{ runtime.version }} exists somewhere in one of the file
  command: grep -Fxq "{{ runtime.version }}"    "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
  register: checkversion
  check_mode: no
  ignore_errors: yes
  changed_when: no

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  when: checkversion.rc != 0
</code>```

Title: Ansible synchronize always sets changed

Body:
I need to set the contents of a dest folder to be the same as my src folder.  So I am using the synchronize module:

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  register: result

But this sets "changed" to 'true' in result, even when there was no change.   I need this to be only set to 'true' if there was a something changed because the next task tests for this state.

If I repeat the same synchronize task right after this one it doesn't set 'changed' to 'true'.  But that one always doesn't get set to 'true'.

Subsequent runs of the play with no change to the src ("/data/managedFiles/lib/{{ runtime.version }}/user/") always set result with 'changed'.

Body:
You can have some pre-condition like this:

- name: check dest directory exists
  stat:
     path: {{ mule_directory }}{{ mule_runtime_name }}/lib/user/
  register: exist_dir

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  when: not exist_dir.stat.exists
  register: result

or

- name: Check whether {{ runtime.version }} exists somewhere in one of the file
  command: grep -Fxq "{{ runtime.version }}"    "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
  register: checkversion
  check_mode: no
  ignore_errors: yes
  changed_when: no

- name: files for /lib/user/ based on the Runtime version
  synchronize:
    src: "/data/managedFiles/lib/{{ runtime.version }}/user/"
    dest: "{{ mule_directory }}{{ mule_runtime_name }}/lib/user/"
    delete: yes
  when: checkversion.rc != 0


问:
Editor only view in XCode
I am using swiftUI to write a new app. Every-time I open a new file the Canvas opens up.
I want the default view to be "Only Editor" and I can open the canvas whenever I want to manually.

Is there a way to change the default?

答:
Just uncheck Canvas as shown below and this state will persists and for new files and after Xcode restart. (Tested with Xcode 11.4)

Caution: Without Canvas opened SwiftUI contextual menu items are not available in Editor. Just be aware.

Title: Editor only view in XCode


问:
Filter by multiple topics in rails
I’ve had a look through the form and have been unsuccessful in finding a solution for this. I currently have a page that displays a bunch of posts, with a simple @post = Post.all

I’m trying to create form that can filter by one of the columns, topics that Post have.

So basically on the left side it will have all the posts,
The right side will have all the unique topics of posts. The user can select one or more of the topics, then click submit, and the posts With the selected topics will be shown.

I’m able to show the unique topic, but unsure how to organise it so it filters after submitting. My current thought process is to create a form with all the topics. When the user presses a few topics, then submits, it filters by the selected topics. But I’m unsure on how to do the filtering in the controller as the amount of topics selected is dynamic. For example if it was just one post. It’s a simple @post = Post.where(:topic params[:chosen]) but I’m unsure how to filter it dynamically on different amounts of topics. Like if 2 or more topics are chosen.

Any help would be greatly appreciated.

答:
You can implement the index method of controller something similar to this (Note: The code is not tested)

```<code>class PostsController < ApplicationController
  before_action :construct_filters, only:[:index]

  def index
    @posts  =  Post.where(@query) # => Posts.where({"topic" => ["topic1","topic2"]}) or Post.where({}) in the case of no params passed(return all posts)
    respond_to do |format|
      format.html
      format.js # In case of remote true submit, respond with index.js.erb and update the listing
    end
  end

  private

  # Generic method to construct query for listing
  def construct_filters
    @query = {}
    # Pass the chosen from the form as comma separated string inside filter hash.
    # Example params received: filters: {"topic" => "topic1,topic2"}
    if params["filters"].present?
      params["filters"].each do |k,v|
        # You can modify the below line to suit your needs if you are not passing as comma seperated
        filter_value = filter_value.split(',')
        @query[k] = filter_value if filter_value.present?
      end
    end
    # @query  = {"topic" => ["topic1","topic2"]}
  end
end
</code>```

Having a generic filter method and a constructing parameter as filter hash will allow you to add more filters in future.

You can implement checkbox or multi select dropdown for selecting topics in your views, may be with input name as filters[topic]. Hope this helps!

Title: Filter by multiple topics in rails

Body:
You can implement the index method of controller something similar to this (Note: The code is not tested)

class PostsController < ApplicationController
  before_action :construct_filters, only:[:index]

  def index
    @posts  =  Post.where(@query) # => Posts.where({"topic" => ["topic1","topic2"]}) or Post.where({}) in the case of no params passed(return all posts)
    respond_to do |format|
      format.html
      format.js # In case of remote true submit, respond with index.js.erb and update the listing
    end
  end

  private

  # Generic method to construct query for listing
  def construct_filters
    @query = {}
    # Pass the chosen from the form as comma separated string inside filter hash.
    # Example params received: filters: {"topic" => "topic1,topic2"}
    if params["filters"].present?
      params["filters"].each do |k,v|
        # You can modify the below line to suit your needs if you are not passing as comma seperated
        filter_value = filter_value.split(',')
        @query[k] = filter_value if filter_value.present?
      end
    end
    # @query  = {"topic" => ["topic1","topic2"]}
  end
end

Having a generic filter method and a constructing parameter as filter hash will allow you to add more filters in future.

You can implement checkbox or multi select dropdown for selecting topics in your views, may be with input name as filters[topic]. Hope this helps!


问:
Re-run failed android tests
Is there a way to run only the failed set of tests on Android using Gradle?

At the moment, I run my tests as follows.

```<code>./gradle connectedDebugAndroidTest
</code>```

There are tests that occasionally fail due to environment issues which are difficult to control and what I would like to do is be able to only run those failed tests and merge the result with the previous test results.

So for example, if I have 100 tests and 90 succeed, I would like to re-run the failing 10 tests.  If those 10 pass the second time around, I would like to merge those results with the original test run.

It looks like this has been discussed several times for Gradle but there doesn't seem to be a solution yet.

```<code>https://github.com/gradle/gradle/issues/4068
https://github.com/gradle/gradle/issues/4450
https://github.com/gradle/gradle/issues/1283
</code>```

Thanks!

答:
The reason they don't have a way to only rerun failed tests is because it screws up the way Gradle currently works. This happens because on the first run, Gradle knows 90 tests passed. If you update the code, and then rerun only the 10 failed tests (using this new option you want them to add), then Gradle would think that all the tests have passed. However, this isn't the case because the tests which previously passed might've broken from the update which fixed the failing tests.

Despite this, the problem has been solved. Gradle reruns failed tests first, and provides a --fail-fast flag for the test task. This effectively does what you want (i.e., only reruns failed tests).

Title: Re-run failed android tests

Body:
Is there a way to run only the failed set of tests on Android using Gradle?

At the moment, I run my tests as follows.

./gradle connectedDebugAndroidTest

There are tests that occasionally fail due to environment issues which are difficult to control and what I would like to do is be able to only run those failed tests and merge the result with the previous test results.

So for example, if I have 100 tests and 90 succeed, I would like to re-run the failing 10 tests.  If those 10 pass the second time around, I would like to merge those results with the original test run.

It looks like this has been discussed several times for Gradle but there doesn't seem to be a solution yet.

https://github.com/gradle/gradle/issues/4068
https://github.com/gradle/gradle/issues/4450
https://github.com/gradle/gradle/issues/1283

Thanks!


问:
Using Jquery how do I get dynamically generated checkboxes checked status inside a function called on a button click
Using jquery, coming out of an ajax call I have an 'each' statement that generates checkboxes.  Here is the line that actually does the generation and append inside my script.

```<code>$('<input />', { type: 'checkbox', id: value.rental_accessories_id, value: value.partnumber, class: 'accessories' }).appendTo($('#form_container');
</code>```

On a click of a button I am executing a function in the main HTML code.

```<code><button type="button" onclick="calculate()" id="calc">CALCULATE</button>
</code>```

Inside the function, so back in the script, I need to know if these checkboxes have been selected.  I can grab the elements using this code and verify they are there, but cannot get a checked status:

```<code>    function calculate() {
$('#form_container input, #form_container select').each(
                function(index){
                    var input = $(this);
                    console.log('Id:' + input.attr('id'));
                    console.log('Type: ' + input.attr('type'));
                    console.log('Name: ' + input.attr('name'));
                    console.log('Value: ' + input.val());
                    console.log($('#' + input.attr('id')).checked);
                    if(input.attr('type') == 'checkbox')
                    {
                        checked_status = input.parent().find('input[name="'+input.attr('name')+'"]:checked').val();
                        console.log('Checked Status' + checked_status);
                    }
                }
            );
}
</code>```

The id, type, name, and value are coming through find.  But I am getting a 'undefined' on the checked status request.  I've tried two different methods that are shown here but both of them return undefined.  I'm creating a couple other form field types which is why I am looking for both input and select.  I can find everything else I am looking for except whether or not the checkboxes have been checked.

I've already done some digging on this site looking for an answer.  You might recognize some of the code above as coming from suggestions from other questions that are similar.  I'm not an expert on jquery but a lot of the suggestions mention using .on, but the examples do not seem to apply to what I am doing, or if they do apply I am not sure how to implement them for this specific setup.

答:
JsFiddle : https://jsfiddle.net/sbn9pf6r/

checkbox.js

```<code>var arr = ['A', 'B', 'C'];

for (var i = 0; i < arr.length; i++) {
    $('<input />', {
        type : 'checkbox',
        id: 'id' + i,
        name: 'name' + arr[i],
        value: arr[i],
        class: 'chk'
    })
    .appendTo("#someId");
}

$("#buttonClass").on("click", function() {
  var checkedIds = $(".chk").map(function() {
    return { value: this.value, checked: this.checked};
  }).toArray();
  console.log(checkedIds);
});
</code>```

checkbox.html

```<code><div id="someId"></div>
<button id="buttonClass">get Data</button>
</code>```

Body:
Using jquery, coming out of an ajax call I have an 'each' statement that generates checkboxes.  Here is the line that actually does the generation and append inside my script.

$('<input />', { type: 'checkbox', id: value.rental_accessories_id, value: value.partnumber, class: 'accessories' }).appendTo($('#form_container');

On a click of a button I am executing a function in the main HTML code.

<button type="button" onclick="calculate()" id="calc">CALCULATE</button>

Inside the function, so back in the script, I need to know if these checkboxes have been selected.  I can grab the elements using this code and verify they are there, but cannot get a checked status:

    function calculate() {
$('#form_container input, #form_container select').each(
                function(index){
                    var input = $(this);
                    console.log('Id:' + input.attr('id'));
                    console.log('Type: ' + input.attr('type'));
                    console.log('Name: ' + input.attr('name'));
                    console.log('Value: ' + input.val());
                    console.log($('#' + input.attr('id')).checked);
                    if(input.attr('type') == 'checkbox')
                    {
                        checked_status = input.parent().find('input[name="'+input.attr('name')+'"]:checked').val();
                        console.log('Checked Status' + checked_status);
                    }
                }
            );
}

The id, type, name, and value are coming through find.  But I am getting a 'undefined' on the checked status request.  I've tried two different methods that are shown here but both of them return undefined.  I'm creating a couple other form field types which is why I am looking for both input and select.  I can find everything else I am looking for except whether or not the checkboxes have been checked.

I've already done some digging on this site looking for an answer.  You might recognize some of the code above as coming from suggestions from other questions that are similar.  I'm not an expert on jquery but a lot of the suggestions mention using .on, but the examples do not seem to apply to what I am doing, or if they do apply I am not sure how to implement them for this specific setup.

Body:
JsFiddle : https://jsfiddle.net/sbn9pf6r/

checkbox.js

var arr = ['A', 'B', 'C'];

for (var i = 0; i < arr.length; i++) {
    $('<input />', {
        type : 'checkbox',
        id: 'id' + i,
        name: 'name' + arr[i],
        value: arr[i],
        class: 'chk'
    })
    .appendTo("#someId");
}

$("#buttonClass").on("click", function() {
  var checkedIds = $(".chk").map(function() {
    return { value: this.value, checked: this.checked};
  }).toArray();
  console.log(checkedIds);
});

checkbox.html

<div id="someId"></div>
<button id="buttonClass">get Data</button>


答:
Push changes the original state of the array. So you don't need to re-initialize the array.</p>

```<code> var buttonColors = ["red", "blue", "green", "yellow"];
    let temp=[];
    temp.push(seq());
    console.log(temp);
    function seq(){
        var randomNumber = Math.floor( Math.random() * 4);
        var randomChosenColor = buttonColors[randomNumber];
        return randomChosenColor;
    }
</code>```

Title: array.push() method is not adding anything to array and working weirdly

Body:
Push changes the original state of the array. So you don't need to re-initialize the array.

 var buttonColors = ["red", "blue", "green", "yellow"];
    let temp=[];
    temp.push(seq());
    console.log(temp);
    function seq(){
        var randomNumber = Math.floor( Math.random() * 4);
        var randomChosenColor = buttonColors[randomNumber];
        return randomChosenColor;
    }


问:
Node and Microsoft Teams API
I'm building a Node only application that reads logs in the background and based on an event being read will send a message to a Teams channel directly.

I've been having quite a few issues getting a Graph API access token valid through Username and password.

I have been able to get a Graph API access token with client secret and tenant id which represents access
 "without a user". Now that does not allow me to post a message in a channel as I would need to have access "on behalf of a user".

API => https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/messages .

Would there be another way of achieving this? Webhook/Connectors?

Thank you!

答:
There's a few different ways you can post to a teams channel, you can set up like you said an http webhook, where you could call it to post into a channel https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using

You can use power automate (flow) or logic apps to post messages as the flowbot, or you can write a bot/ use the bot framework to register a bot that can post to teams, called proactive messaging: https://learn.microsoft.com/en-us/microsoftteams/platform/resources/bot-v3/bot-conversations/bots-conv-proactive

As for trying to use graph with application permissions, that's not possible, at least for the moment.

Title: Node and Microsoft Teams API


问:
How can I fix empty space on mobile HTML site?
My HTML website currently has a large empty space on the right side on mobile. The website is pumpkinchugger.github.io/rona20.live how can I get rid of this empty space? I currently have this in my CSS file, and I think it is causing this problem?

```<code>@media all and (max-width:991px){
    .row{
        flex-direction:column;
    }

    .container--wrap{
        width: 98vw!important;
    }
}
</code>```

Is the max width the problem?

答: I don't think max-width is the problem here. Upon inspecting the page, i removed the mentioned CSS, it did not change much and also, the spacing wasn't removed. When the width was set to 145% from 100%, it semeed to fit the page correctly</p>

Body:
My HTML website currently has a large empty space on the right side on mobile. The website is pumpkinchugger.github.io/rona20.live how can I get rid of this empty space? I currently have this in my CSS file, and I think it is causing this problem?

@media all and (max-width:991px){
    .row{
        flex-direction:column;
    }

    .container--wrap{
        width: 98vw!important;
    }
}

Is the max width the problem?


问:
The error "This project is incompatible with the current version of visual studio" displayed
I installed Vs 2010 Express in my PC, and created a poject named myproject with .net 4.0, it works well in  Vs 2010 Express.

Now I installed Vs 2012 Express in my PC, and open the project myproject and upgrade it to .net 4.5, it wells well in  Vs 2012 Express too.

I delete the project myproject all files, then restore it from my old backup file, when I try to open the project from  Vs 2010 Express, I get the following  information.

"This project is incompatible with the current version of visual studio", why?

How can I open the project in  Vs 2010 Express?  I guess the  Vs 2012 Express maybe mark the project as .net 4.5 and stored the information in the somewhere of hard drive. Although I restore the project myproject from old backup file,  Vs 2010 Express still think it is a project of .net 4.5.

Thanks!

答:
I faced out with this problem, the solution was:

Open VS2017

Go to Tools

Go to Extensions and updates

Search for Reporting Services Project and then "Enable"; close your VS.

Open again your project/solution.

--
MT


问:
Uncaught Reference Error when trying to pass a function through a button in JavaScript?
I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?

JS File:

```<code>let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '<div class="topnav">';
for(let count = 0; count < typearray.length; count++){
    str = str +
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '</div>' +
'</div>';
console.log(str);

document.getElementById('navbar').innerHTML = str;
</code>```

HTML File(includes the rest of the program)

```<code><html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">
    <style>
      #map {
        height: 75%;
        width: 75%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script src = getlocation.js></script>
    <!-- this implements the navbar-->
    <div id="navbar"></div>
    <script type = "module" src = navbar.js></script>
    <!-- this implements the map-->
    <div id="map"></div>
    <script src = index.js> </script>
    <!-- this implements the list-->
    <div id="list"></div>
    <script type = "module" src = rankedstores.js></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=000000000000000000
    &callback=initMap"></script>
  </body>
</html>
</code>```

答:
Looks like you just had some errors when building str. Try this</p>

```<code>let typearray = ["supermarkets_and_groceries", "churches", "cafes"];

let str = '<div class="topnav">';

for (let count = 0; count < typearray.length; count++) {
    str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str += "</div>";
console.log(str);
</code>```

Body:
I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?

JS File:

let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '
';
for(let count = 0; count < typearray.length; count++){
    str = str +
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '
' +
'
';
console.log(str);

document.getElementById('navbar').innerHTML = str;

HTML File(includes the rest of the program)

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">

Body:
Looks like you just had some errors when building str. Try this

let typearray = ["supermarkets_and_groceries", "churches", "cafes"];

let str = '<div class="topnav">';

for (let count = 0; count < typearray.length; count++) {
    str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str += "</div>";
console.log(str);


问:
Javascript date countdown with custom date

var timer;

var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));

timer = setInterval(function() {
  timeBetweenDates(compareDate);
}, 1000);

function timeBetweenDates(toDate) {
  var dateEntered = toDate;
  var now = new Date();
  var difference = dateEntered.getTime() - now.getTime();

  if (difference <= 0) {

    // Timer done
    clearInterval(timer);

  } else {

    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);

    hours %= 24;
    minutes %= 60;
    seconds %= 60;

    $("#days").text(days);
    $("#hours").text(hours);
    $("#minutes").text(minutes);
    $("#seconds").text(seconds);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #f5f5f5;
}
#timer {
  font-family: Arial, sans-serif;
  font-size: 20px;
  color: #999;
  letter-spacing: -1px;
}
#timer span {
  font-size: 60px;
  color: #333;
  margin: 0 3px 0 15px;
}
#timer span:first-child {
  margin-left: 0;
}
  </code>```

  days
  hours
  minutes
  seconds

```

答:
Change

```<code>var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));
</code>```

to

```<code>var compareDate = new Date(2020, 05, 2);
</code>```

Body:
var timer;

var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));

timer = setInterval(function() {
  timeBetweenDates(compareDate);
}, 1000);

function timeBetweenDates(toDate) {
  var dateEntered = toDate;
  var now = new Date();
  var difference = dateEntered.getTime() - now.getTime();

  if (difference <= 0) {

    // Timer done
    clearInterval(timer);

  } else {

    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);

    hours %= 24;
    minutes %= 60;
    seconds %= 60;

    $("#days").text(days);
    $("#hours").text(hours);
    $("#minutes").text(minutes);
    $("#seconds").text(seconds);
  }
}

body {
  background: #f5f5f5;
}
#timer {
  font-family: Arial, sans-serif;
  font-size: 20px;
  color: #999;
  letter-spacing: -1px;
}
#timer span {
  font-size: 60px;
  color: #333;
  margin: 0 3px 0 15px;
}
#timer span:first-child {
  margin-left: 0;
}

  days
  hours
  minutes
  seconds

Body:
Change

var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));

to

var compareDate = new Date(2020, 05, 2);


问:
Vue.JS - Property value based on another property + string
I have a re-usable Vue.JS component, DonutChart.

<donut-chart
    :chartName="graphPrefix + 'PerformanceDay'"
/>
```

graphPrefix is a property with value site1 in this case. I use chartName for the div id in DonutChart.

I'm trying to get the value to be site1PerformanceDay. What is the proper approach?

答:
Don't use spaces.

<donut-chart
    :chartName="graphPrefix+'PerformanceDay'"
/>
```

Body:
I have a re-usable Vue.JS component, DonutChart.

<donut-chart
    :chartName="graphPrefix + 'PerformanceDay'"
/>

graphPrefix is a property with value site1 in this case. I use chartName for the div id in DonutChart.

I'm trying to get the value to be site1PerformanceDay. What is the proper approach?


问:
How can i get the links in my navigation bar to be displayed horizontally? Flexbox doesn't seem to be working
Not sure why my setup isn't working. with the links set to display:flex;, shouldn't they be displayed next to each other instead of on top of each other? Right now I have
Test
 on the left, and my links stacked on top of each other to the right.

Here's the html:

```<code><body>
        <div class="nav-wrapper">
                <div class="logo">
                        <p>Test</p>
                </div>
                <div class="link-wrapper">
                        <ul>
                                <li><a href="#"></a>About</li>
                                <li><a href="#"></a>Portfolio</li>
                                <li><a href="#"></a>Styles</li>
                                <li><a href="#"></a>Contact</li>
                        </ul>
                </div>
        </div>
</body>
</code>```

and the css:

```<code> * {
        padding: 0px;
        margin: 0px;
        box-sizing: border-box;
}

.link-wrapper a {
        text-decoration: none;
}

.link-wrapper li {
                list-style: none;
}

.nav-wrapper {
        display:flex;
        justify-content: space-around;
        align-items: center;
        min-height: 8vh;
}

.link-wrapper {
        display: flex;
        width: 30%;
        justify-content: space-around;
}
</code>```

答:
You have provided property flex to link-wrapper class but

 tags are under

 so either give ul a class link-wrapper or do something like this.

* {
        padding: 0px;
        margin: 0px;
        box-sizing: border-box;
}

.link-wrapper a {
        text-decoration: none;
}

.link-wrapper li {
                list-style: none;
}

.nav-wrapper {
        display:flex;
        justify-content: space-around;
        align-items: center;
        min-height: 8vh;
}

.link-wrapper ul {
        display: flex;
        width: 30%;
        justify-content: space-around;
}   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
        <div class="nav-wrapper">
                <div class="logo">
                        <p>Test</p>
                </div>
                <div class="link-wrapper">
                        <ul>
                                <li>About</li>
                                <li>Portfolio</li>
                                <li>Styles</li>
                                <li>Contact</li>
                        </ul>
                </div>
        </div>
</body>

 </code>```

Body:
Not sure why my setup isn't working. with the links set to display:flex;, shouldn't they be displayed next to each other instead of on top of each other? Right now I have
Test
 on the left, and my links stacked on top of each other to the right.

Here's the html:

Test

About

Portfolio

Styles

Contact

and the css:

 * {
        padding: 0px;
        margin: 0px;
        box-sizing: border-box;
}

.link-wrapper a {
        text-decoration: none;
}

.link-wrapper li {
                list-style: none;
}

.nav-wrapper {
        display:flex;
        justify-content: space-around;
        align-items: center;
        min-height: 8vh;
}

.link-wrapper {
        display: flex;
        width: 30%;
        justify-content: space-around;
}

Body:
You have provided property flex to link-wrapper class but <li></li> tags are under <ul><ul> so either give ul a class link-wrapper or do something like this.

* {
        padding: 0px;
        margin: 0px;
        box-sizing: border-box;
}

.link-wrapper a {
        text-decoration: none;
}

.link-wrapper li {
                list-style: none;
}

.nav-wrapper {
        display:flex;
        justify-content: space-around;
        align-items: center;
        min-height: 8vh;
}

.link-wrapper ul {
        display: flex;
        width: 30%;
        justify-content: space-around;
}

<body>
        <div class="nav-wrapper">
                <div class="logo">
                        <p>Test</p>
                </div>
                <div class="link-wrapper">
                        <ul>
                                <li><a href="#"></a>About</li>
                                <li><a href="#"></a>Portfolio</li>
                                <li><a href="#"></a>Styles</li>
                                <li><a href="#"></a>Contact</li>
                        </ul>
                </div>
        </div>
</body>


问:
I've heard i++ isn't thread safe, is ++i thread-safe?
I've heard that i++ isn't a thread-safe statement since in assembly it reduces down to storing the original value as a temp somewhere, incrementing it, and then replacing it, which could be interrupted by a context switch.

However, I'm wondering about ++i. As far as I can tell, this would reduce to a single assembly instruction, such as 'add r1, r1, 1' and since it's only one instruction, it'd be uninterruptable by a context switch.

Can anyone clarify? I'm assuming that an x86 platform is being used.

答:
AFAIK, According to the C++ standard, read/writes to an int are atomic.

However, all that this does is get rid of the undefined behavior that's associated with a data race.

But there still will be a data race if both threads try to increment i.

Imagine the following scenario:

Let i = 0 initially:

Thread A reads the value from memory and stores in its own cache.
Thread A increments the value by 1.

Thread B reads the value from memory and stores in its own cache.
Thread B increments the value by 1.

If this is all a single thread you would get i = 2 in memory.

But with both threads, each thread writes its changes and so Thread A writes i = 1 back to memory, and Thread B writes i = 1 to memory.

It's well defined, there's no partial destruction or construction or any sort of tearing of an object, but it's still a data race.

In order to atomically increment i you can use:

std::atomic<int>::fetch_add(1, std::memory_order_relaxed)

Relaxed ordering can be used because we don't care where this operation takes place all we care about is that the increment operation is atomic.

OwnerDisplayName: samoz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Tim Williscroft


问:
How to append some MP3s in Qt?
How to append some MP3s in Qt by C++?

Assume I have 1.mp3 and 2.mp3, now I want to join them by Qt.

3.mp3 = 1.mp3 + 2.mp3

答:
AFAIK you can not do this simply in Qt. But I suggest you use mp3wrap, a nifty little command line tool to concatenate your mp3s.

So, you create a UI, where you select the files, and then pass the parameters to this command line application and let it do its magic.

You can execute commands using:

```<code>system("command1;command2");
</code>```

This call will block until the commands are finished. In your case the command will be calling mp3wrap with the appropriate parameters

Good luck!

Title: How to append some MP3s in Qt?

Body:
AFAIK you can not do this simply in Qt. But I suggest you use mp3wrap, a nifty little command line tool to concatenate your mp3s.

So, you create a UI, where you select the files, and then pass the parameters to this command line application and let it do its magic.

You can execute commands using:

system("command1;command2");

This call will block until the commands are finished. In your case the command will be calling mp3wrap with the appropriate parameters

Good luck!


问:
How I add an object to an existing array? React
recently I started to work in a proyect and I notice that I need some way to modify a value without losing my previous state. Basically work with an array. However I don't know how to do that.
Can anyone help me by telling me how can I modify an state (I'm using react hooks by the way...) to add more values to the previous state in an array?

Sorry not posting code or something like that, I don't even know how to write that.

Thank you in advance.

答:
You can use the previous value returned from the setState to update the existing Array</p>

```<code>import { useState } from 'react';

    export default function Test() {
      const [state, setstate] = useState([1,2,3,4);
      return <div onClick={() => setstate((prev) => [...prev,99])}>Heyy{state}</div>;
    }
</code>```

Body:
You can use the previous value returned from the setState to update the existing Array

import { useState } from 'react';

    export default function Test() {
      const [state, setstate] = useState([1,2,3,4);
      return <div onClick={() => setstate((prev) => [...prev,99])}>Heyy{state}</div>;
    }


问:
How do I enable a dropdown menu after hovering?
How do I enable a dropdown menu after hovering over the border-radius circle or the text, and move the direction of the dropdown menu so it will be displayed above-right instead of hovering just the button and dropping down horizontally? I would like the button to be covered over the text but stays the same size

html {
    font-size: 62.5%;
}
* {
    font-size: 1.8rem;
}
:root {
    --pri-color: #F8A909;
    --background-color: #FFFAF0;
}

/* Start login */
body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
.dropdown_com {
 position: relative;
 top:75px;
 left:180px;
 transform: translate(0px,0px);
}

.dropdown_com .dropbtn {
    font-size: 16px;
    border: none;
    outline: none;
    padding: 14px 16px;
    background-color: inherit;
    font-family: inherit;
    margin: 0;
}

.navbar a:hover, .dropdown:hover .dropbtn {

}

.dropdown-content {
    display: none;
    position: absolute;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    font-family: 'Lato';font-size: 23px;
    padding: 12px 10px;
    margin: 5px;
    margin-left: -165px;
}

.dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {
    background-color: #C0C0C0;
}

.dropdown_com:hover .dropdown-content {
    display: block;
}
.compliments1{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}
.border-circle1{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}
.border-circle1 li{
    list-style-type: none;
    text-decoration: none;

}
.fa-10x1{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}
.compliments1 p{
    margin: 0;
    position: absolute;
    transform: translate(20px,80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

    <body style="height: 100rem;">

        <!-- navigation bar -->

        <div class="border-circle1">

            <div class="compliments1">
                 <li><span class= " fa fa-thumbs-up fa-10x1"></span></li>
                <p> Facebook Like </p>
                <div class="dropdown_com">
                    <button class="dropbtn">
                        <i class="fa fa-caret-down"></i>
                    </button>
                    <div class="dropdown-content">
                        1 Likes
                        2 Likes
                    </div>
                </div>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

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

答:
There is lots of things in your code which should not be there, I don't know why you have it there, For example there is a span with class fa fa-thumbs-up fa-10x1 in li, and that LI is in a anchor, and ideally it should be in UL, LI should always be the child of UL or OL, not of anchor. For your drop-down problem, just make the display block of your List on hover of circle.

html {
    font-size: 62.5%;
}
* {
    font-size: 1.8rem;
}
:root {
    --pri-color: #F8A909;
    --background-color: #FFFAF0;
}

/* Start login */
body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
.dropdown_com {
 position: relative;
 top:75px;
 left:180px;
 transform: translate(0px,0px);
}

.dropdown_com .dropbtn {
    font-size: 16px;
    border: none;
    outline: none;
    padding: 14px 16px;
    background-color: inherit;
    font-family: inherit;
    margin: 0;
}

.navbar a:hover, .dropdown:hover .dropbtn {

}

.dropdown-content {
    display: none;
    position: absolute;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    font-family: 'Lato';font-size: 23px;
    padding: 12px 10px;
    margin: 5px;
    margin-left: -165px;
        background: #fff;
}

.dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {
    background-color: #C0C0C0;
}

.dropdown_com:hover .dropdown-content {
    display: block;
}
.compliments1{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}
.border-circle1{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}
.border-circle1 li{
    list-style-type: none;
    text-decoration: none;

}
.fa-10x1{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}
.compliments1 p{
    margin: 0;
    position: absolute;
    transform: translate(20px,80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.compliments1:hover .dropdown-content {display: block;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

    <body style="height: 100rem;">

        <!-- navigation bar -->

        <div class="border-circle1">

            <div class="compliments1">
                 <li><span class= " fa fa-thumbs-up fa-10x1"></span></li>
                <p> Facebook Like </p>
                <div class="dropdown_com">
                    <button class="dropbtn">
                        <i class="fa fa-caret-down"></i>
                    </button>
                    <div class="dropdown-content">
                        1 Likes
                        2 Likes
                    </div>
                </div>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

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

Body:
How do I enable a dropdown menu after hovering over the border-radius circle or the text, and move the direction of the dropdown menu so it will be displayed above-right instead of hovering just the button and dropping down horizontally? I would like the button to be covered over the text but stays the same size

html {
    font-size: 62.5%;
}
* {
    font-size: 1.8rem;
}
:root {
    --pri-color: #F8A909;
    --background-color: #FFFAF0;
}

/* Start login */
body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
.dropdown_com {
 position: relative;
 top:75px;
 left:180px;
 transform: translate(0px,0px);
}

.dropdown_com .dropbtn {
    font-size: 16px;
    border: none;
    outline: none;
    padding: 14px 16px;
    background-color: inherit;
    font-family: inherit;
    margin: 0;
}

.navbar a:hover, .dropdown:hover .dropbtn {

}

.dropdown-content {
    display: none;
    position: absolute;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    font-family: 'Lato';font-size: 23px;
    padding: 12px 10px;
    margin: 5px;
    margin-left: -165px;
}

.dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {
    background-color: #C0C0C0;
}

.dropdown_com:hover .dropdown-content {
    display: block;
}
.compliments1{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}
.border-circle1{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}
.border-circle1 li{
    list-style-type: none;
    text-decoration: none;

}
.fa-10x1{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}
.compliments1 p{
    margin: 0;
    position: absolute;
    transform: translate(20px,80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}

<!DOCTYPE html>

    <jsp:include page="../head.html" />

 Facebook Like

                    <button class="dropbtn">

                    </button>

                        1 Likes
                        2 Likes

Body:
There is lots of things in your code which should not be there, I don't know why you have it there, For example there is a span with class fa fa-thumbs-up fa-10x1 in li, and that LI is in a anchor, and ideally it should be in UL, LI should always be the child of UL or OL, not of anchor. For your drop-down problem, just make the display block of your List on hover of circle.

html {
    font-size: 62.5%;
}
* {
    font-size: 1.8rem;
}
:root {
    --pri-color: #F8A909;
    --background-color: #FFFAF0;
}

/* Start login */
body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}
.dropdown_com {
 position: relative;
 top:75px;
 left:180px;
 transform: translate(0px,0px);
}

.dropdown_com .dropbtn {
    font-size: 16px;
    border: none;
    outline: none;
    padding: 14px 16px;
    background-color: inherit;
    font-family: inherit;
    margin: 0;
}

.navbar a:hover, .dropdown:hover .dropbtn {

}

.dropdown-content {
    display: none;
    position: absolute;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    font-family: 'Lato';font-size: 23px;
    padding: 12px 10px;
    margin: 5px;
    margin-left: -165px;
        background: #fff;
}

.dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
}

.dropdown-content a:hover {
    background-color: #C0C0C0;
}

.dropdown_com:hover .dropdown-content {
    display: block;
}
.compliments1{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}
.border-circle1{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}
.border-circle1 li{
    list-style-type: none;
    text-decoration: none;

}
.fa-10x1{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}
.compliments1 p{
    margin: 0;
    position: absolute;
    transform: translate(20px,80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.compliments1:hover .dropdown-content {display: block;}

<!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

    <body style="height: 100rem;">

        <!-- navigation bar -->

        <div class="border-circle1">

            <div class="compliments1">
                <a href="#"> <li><span class= " fa fa-thumbs-up fa-10x1"></span></li></a>
                <p> Facebook Like </p>
                <div class="dropdown_com">
                    <button class="dropbtn">
                        <i class="fa fa-caret-down"></i>
                    </button>
                    <div class="dropdown-content">
                        <a href="#">1 Likes</a>
                        <a href="#">2 Likes</a>
                    </div>
                </div>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    </body>
</html>


问:
Uncaught TypeError: Cannot read property 'req_tanggal' of undefined
i have problem when get record from datatable to input text,when i click record in datatable in error log show this message " datatable.js:2274 Uncaught TypeError: Cannot read property 'req_tanggal' of undefined"

this is my code :

var tpropen;
var tpropen1;

$(document).ready( function ()
{

 tpropen = $('#tpropen').DataTable({
  "columnDefs":[{ "orderable": false,"className": "select-checkbox","targets": [0],"checkboxes": {"selectRow": true}}],
 "select": {"style": "multi"},
 "order": [[0, "asc"]],
 "sAjaxSource": "/HPR_validate",
 "scrollX": "200px",
 "sAjaxDataProp": "",
 "aoColumns":
 [
 { "mData": "id_header_pr", "defaultContent": ""},
 { "mData": "req_tanggal", "defaultContent": ""},
 { "mData": "kode_pr", "defaultContent": ""},
 { "mData": "jenis_pr", "defaultContent": ""},
 { "mData": "status", "defaultContent": ""}
 ]
 });

 tpropen.on('click', function(e)
 {
 var form = this;
 var rows_selected = tpropen.column(0).checkboxes.selected();
 $('#id_header_pr').val(rows_selected.join(","));
    tpropen1 = $('#tpropen').DataTable().row('.selected').data();

 $('#req_tanggal').val(tpropen1 ['req_tanggal']);  // $('#req_tanggal') this is input text////

 });
 //setInterval (tabelhpropen.ajax.reload, 1000);
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tab-pane active" id="tab_1x">
<div >
<div class="panel panel-default">
<table class="table table-striped table-bordered table-hover" id="tpropen" role="grid" style="width: 100%;" width="100%">
<thead>
<tr>
  <th>id_header_pr</th>
  <th>req_tanggal</th>
  <th>kode_pr</th>
  <th>jenis_pr</th>
  <th>status</th>
</tr>
</thead>
</table>
</div>
</div>
</div></code>```

答:
You're trying to use the jQuery #id Selector $('#req_tanggal') but no HTML element has a corresponding id.

Change the th element req_tanggal	 as follows and it should work.

```<code><th id="req_tanggal"></th>
</code>```

Body:
i have problem when get record from datatable to input text,when i click record in datatable in error log show this message " datatable.js:2274 Uncaught TypeError: Cannot read property 'req_tanggal' of undefined"

this is my code :

var tpropen;
var tpropen1;

$(document).ready( function ()
{

 tpropen = $('#tpropen').DataTable({
  "columnDefs":[{ "orderable": false,"className": "select-checkbox","targets": [0],"checkboxes": {"selectRow": true}}],
 "select": {"style": "multi"},
 "order": [[0, "asc"]],
 "sAjaxSource": "/HPR_validate",
 "scrollX": "200px",
 "sAjaxDataProp": "",
 "aoColumns":
 [
 { "mData": "id_header_pr", "defaultContent": ""},
 { "mData": "req_tanggal", "defaultContent": ""},
 { "mData": "kode_pr", "defaultContent": ""},
 { "mData": "jenis_pr", "defaultContent": ""},
 { "mData": "status", "defaultContent": ""}
 ]
 });

 tpropen.on('click', function(e)
 {
 var form = this;
 var rows_selected = tpropen.column(0).checkboxes.selected();
 $('#id_header_pr').val(rows_selected.join(","));
    tpropen1 = $('#tpropen').DataTable().row('.selected').data();

 $('#req_tanggal').val(tpropen1 ['req_tanggal']);  // $('#req_tanggal') this is input text////

 });
 //setInterval (tabelhpropen.ajax.reload, 1000);
 });

  id_header_pr
  req_tanggal
  kode_pr
  jenis_pr
  status

Body:
You're trying to use the jQuery #id Selector $('#req_tanggal') but no HTML element has a corresponding id.

Change the th element <th>req_tanggal</th> as follows and it should work.

<th id="req_tanggal"></th>


问:
Python CSV to Array
Need some help pls. I have a csv file in the following format.
input.csv

```<code>Project1,folder1/file1,data
Project1,folder1/file2,data
Project1,folder1/file3,data
Project1,folder1/file4,data
Project1,folder2/file11,data
Project1,folder2/file42a,data
Project1,folder2/file42b,data
Project1,folder2/file42c,data
Project1,folder2/file42d,data
Project1,folder3/filec,data
Project1,folder3/fileb,data
Project1,folder3/filea,data
</code>```

Basically, ignore all columns except column #2. This column is like a directory tree, in the format <foldername> forwardslash <filename>. There is no header-row.

I wish Python ver 3x, to read this file and make this into an array in the following format. The input csv file is large and hence need an efficient way to this pls.

```<code>print(out_array)

'folder1/file1', 'folder1/file2', 'folder1/file3', 'folder1/file4'
'folder2/file11', 'folder2/file42a', 'folder2/file42b', 'folder2/file42c', 'folder2/file42d'
'folder3/filec', 'folder3/fileb', 'folder3/filea'
</code>```

Each folder is output on a new row. The input csv file, will not have the folder names jumbled up. Hence, all rows for folder1 will be together, and not mixed with others.

答:
Thanks to Danizavtz's revert; I post my solution...</p>

```<code>Bdb = []
lastrowfldr=""
r=-1
with open('input.csv', 'r') as read_obj:
    for row in (reader(read_obj)):
        fldr,x = str(row[1]).split('/')
        if (lastrowfldr!=fldr):
            r=r+1
            Bdb.append([])
        BdB[r].append(row[1])
        lastrowfldr=fldr
</code>```

Title: Python CSV to Array

Body:
Need some help pls. I have a csv file in the following format.
input.csv

Project1,folder1/file1,data
Project1,folder1/file2,data
Project1,folder1/file3,data
Project1,folder1/file4,data
Project1,folder2/file11,data
Project1,folder2/file42a,data
Project1,folder2/file42b,data
Project1,folder2/file42c,data
Project1,folder2/file42d,data
Project1,folder3/filec,data
Project1,folder3/fileb,data
Project1,folder3/filea,data

Basically, ignore all columns except column #2. This column is like a directory tree, in the format <foldername> forwardslash <filename>. There is no header-row.

I wish Python ver 3x, to read this file and make this into an array in the following format. The input csv file is large and hence need an efficient way to this pls.

print(out_array)

'folder1/file1', 'folder1/file2', 'folder1/file3', 'folder1/file4'
'folder2/file11', 'folder2/file42a', 'folder2/file42b', 'folder2/file42c', 'folder2/file42d'
'folder3/filec', 'folder3/fileb', 'folder3/filea'

Each folder is output on a new row. The input csv file, will not have the folder names jumbled up. Hence, all rows for folder1 will be together, and not mixed with others.

Body:
Thanks to Danizavtz's revert; I post my solution...

Bdb = []
lastrowfldr=""
r=-1
with open('input.csv', 'r') as read_obj:
    for row in (reader(read_obj)):
        fldr,x = str(row[1]).split('/')
        if (lastrowfldr!=fldr):
            r=r+1
            Bdb.append([])
        BdB[r].append(row[1])
        lastrowfldr=fldr


问:
How can I implement dynamic Layered ImageView Programmatically?
I want to have layered images as attached below.

Currently, I am doing it like this

layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

      <View
            android:id="@+id/view1"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/images1">
        </View>
        <View
            android:id="@+id/view2"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/images1">
        </View>
        <View
            android:id="@+id/view3"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="20dp"
            android:background="@drawable/images1">
        </View>

</RelativeLayout>
</code>```

But I feel this manual method using XML may vary and react based on different devices and screen types. So, How can I achieve it in the better or best way? How can I make it dynamic?

Thank You.

答:
I used the following to implement the layered imageview programatically. However, this does not feel the best solution.
Hope, it will help others as well.

```<code>class ThumbView extends RelativeLayout {
    private ImageView vLayer1;
    private ImageView vLayer2;
    private ImageView vLayer3;

    public ThumbView(Context context, String pathToFile) {
        super(context);
        LayoutInflater inflater = (LayoutInflater) getContext()
          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.view_thumb, this, true);
        vLayer1 = view.findViewById(R.id.view1);
        vLayer2 = view.findViewById(R.id.view2);
        vLayer3 = view.findViewById(R.id.view3);

        Drawable drawable = Drawable.createFromPath(pathToFile);

        vLayer1.setImageDrawable(drawable);
        vLayer2.setImageDrawable(drawable);
        vLayer3.setImageDrawable(drawable);
    }
}
</code>```

Body:
I want to have layered images as attached below.

Currently, I am doing it like this

layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

      <View
            android:id="@+id/view1"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/images1">
        </View>
        <View
            android:id="@+id/view2"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/images1">
        </View>
        <View
            android:id="@+id/view3"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_marginTop="30dp"
            android:layout_marginLeft="20dp"
            android:background="@drawable/images1">
        </View>

</RelativeLayout>

But I feel this manual method using XML may vary and react based on different devices and screen types. So, How can I achieve it in the better or best way? How can I make it dynamic?

Thank You.

Body:
I used the following to implement the layered imageview programatically. However, this does not feel the best solution.
Hope, it will help others as well.

class ThumbView extends RelativeLayout {
    private ImageView vLayer1;
    private ImageView vLayer2;
    private ImageView vLayer3;

    public ThumbView(Context context, String pathToFile) {
        super(context);
        LayoutInflater inflater = (LayoutInflater) getContext()
          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.view_thumb, this, true);
        vLayer1 = view.findViewById(R.id.view1);
        vLayer2 = view.findViewById(R.id.view2);
        vLayer3 = view.findViewById(R.id.view3);

        Drawable drawable = Drawable.createFromPath(pathToFile);

        vLayer1.setImageDrawable(drawable);
        vLayer2.setImageDrawable(drawable);
        vLayer3.setImageDrawable(drawable);
    }
}


问:
Python UnicodeDecodeError with 'gbk' while using third party libraries
I'm trying the examples in "PyDeepGP" provided by SheffieldML (https://github.com/SheffieldML/PyDeepGP). In the example code, a third-party library pods is used to provide some open datasets.

Once running the example code, I immediately encountered the error message:
"UnicodeDecodeError: 'gbk' codec can't decode byte 0x93 in position 37571: illegal multibyte sequence".
It turns out that the error occurs when the pods trying to open a file called 'data_resources.json' and do file.read() on it.

I manually f = open("...\data_resources.json", encoding="utf8") and then f.read(), everything will be fine. So it's obvious my python choose the 'gbk' to decode an 'utf8' file with unknown reason.

However, it is infeasible for me to add encoding="utf8" to every piece of code in a third-party library. I want to force my python opening file automatically with utf-8.

I checked the sys.getdefaultencoding() and it is 'utf8' as usual.
I have tried to set my vscode with files.autoGuessEncoding turning on and then off.
And I even tried the solution provided by http://www.programmersought.com/article/4189689383/, adding

import _locale
_locale._getdefaultlocale = (lambda *args: ['zh_CN', 'utf8'])
```

<p>to the codes. It will work only when I manually write <code>open(file) as f</code> and then <code>f.read()</code>. However it fails when I run the whole example code, where the file is open by the third-party library.</p>

<p>I am currently using python 3.6.7 on Windows 10 with Anaconda.</p>

<p>Here's the complete error message:</p>

<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
  File "..../SheffieldML-PyDeepGP/examples/example_supervised_learning.py", line 35, in <module>
    import pods
  File "....\lib\site-packages\pods\__init__.py", line 5, in <module>
    from . import datasets
  File "....\lib\site-packages\pods\datasets.py", line 53, in <module>
    json_data=open(path).read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x93 in position 37571: illegal multibyte sequence
</code>```

答:
I got exactly the same error. I got some clue from
https://github.com/rkern/line_profiler/issues/37
and change the datasets.py line 53 as

```<code>json_data=open(path,'rb').read()
</code>```

By using the binary mode, it will probably ignore the codec things.

Body:
I'm trying the examples in "PyDeepGP" provided by SheffieldML (https://github.com/SheffieldML/PyDeepGP). In the example code, a third-party library pods is used to provide some open datasets.

Once running the example code, I immediately encountered the error message:
"UnicodeDecodeError: 'gbk' codec can't decode byte 0x93 in position 37571: illegal multibyte sequence".
It turns out that the error occurs when the pods trying to open a file called 'data_resources.json' and do file.read() on it.

I manually f = open("...\data_resources.json", encoding="utf8") and then f.read(), everything will be fine. So it's obvious my python choose the 'gbk' to decode an 'utf8' file with unknown reason.

However, it is infeasible for me to add encoding="utf8" to every piece of code in a third-party library. I want to force my python opening file automatically with utf-8.

I checked the sys.getdefaultencoding() and it is 'utf8' as usual.
I have tried to set my vscode with files.autoGuessEncoding turning on and then off.
And I even tried the solution provided by http://www.programmersought.com/article/4189689383/, adding

import _locale
_locale._getdefaultlocale = (lambda *args: ['zh_CN', 'utf8'])

to the codes. It will work only when I manually write open(file) as f and then f.read(). However it fails when I run the whole example code, where the file is open by the third-party library.

I am currently using python 3.6.7 on Windows 10 with Anaconda.

Here's the complete error message:

Traceback (most recent call last):
  File "..../SheffieldML-PyDeepGP/examples/example_supervised_learning.py", line 35, in <module>
    import pods
  File "....\lib\site-packages\pods\__init__.py", line 5, in <module>
    from . import datasets
  File "....\lib\site-packages\pods\datasets.py", line 53, in <module>
    json_data=open(path).read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x93 in position 37571: illegal multibyte sequence

Body:
I got exactly the same error. I got some clue from
https://github.com/rkern/line_profiler/issues/37
and change the datasets.py line 53 as

json_data=open(path,'rb').read()

By using the binary mode, it will probably ignore the codec things.


问:
what do i need to do to develope an iphone\android app in vs2010?
we are a .net team that devleoped a full app in c# with web services and services that support it. we now want to develope a Mobile app (Android\Iphone) that will look similiar to the original to allow mobile use of it.
we thought about MonoTouch instead of trying to learn Objective-c and to try to develope a cross platform mobile app.
is anyone tried developing a mobile app in vs 2010 in MonoTouch? is there a simple add in for it? is it possible?</p>

答:
According to the MonoTouch roadmap, they plan to make it possible to use MonoTouch in VisualStudio. You still need a mac, though. You can't get around that.

I guess Android would be easier. There is no platform dependency there


问:
Why am I get a syntax error here when I am equating a variable containing an integer and a variable containing a numerical input from the user?
I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,

```<code>if guess.isdigit():
     guess = int(guess)
</code>```

Please help

```<code>import random
a = random.randint(1,10)

print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")

if question_one == "Yes":
    print("Let's go!")
else:
    print("That sucks!")
    exit()
guess = None
while guess != a:
    guess = (input("Alright, guess a number from 1-10"))
    if guess.isdigit():
        guess = int(guess)

    if guess > a:
        guess = int(input("Guess lower!"))
    elif guess < a:
        guess = int(input("Guess higher!"))
    else guess == a:
        print("you got it!")
</code>```

答:
An else statement contains the block of code that executes if the conditional expression in all your if or elif statements is false. Hence in your case you're supposed to use the elif statement instead of else. See the following:

```<code>elif guess == a:
        print("you got it!")
</code>```

Body:
I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,

if guess.isdigit():
     guess = int(guess)

Please help

import random
a = random.randint(1,10)

print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")

if question_one == "Yes":
    print("Let's go!")
else:
    print("That sucks!")
    exit()
guess = None
while guess != a:
    guess = (input("Alright, guess a number from 1-10"))
    if guess.isdigit():
        guess = int(guess)

    if guess > a:
        guess = int(input("Guess lower!"))
    elif guess < a:
        guess = int(input("Guess higher!"))
    else guess == a:
        print("you got it!")

Body:
An else statement contains the block of code that executes if the conditional expression in all your if or elif statements is false. Hence in your case you're supposed to use the elif statement instead of else. See the following:

elif guess == a:
        print("you got it!")