问:
Adding input variable inside regex
I'm trying to make a code that finds all preferred file extension and then moves them to designed folder. Code is working but I need to enter file extensions manually inside the file. What I'm trying to do is add an input variable and place it into re.compile(), therefore I don't need to edit the file whenever I need it for different file types.

This part I need to edit:

```<code># Go through the listFiles and find specific file types.
picRegex = re.compile(r'.*\.jpg|.*\.png')
fileMatches = list(filter(picRegex.match, listFiles)
</code>```

This works for the filetypes already there in my code but as I said I want it to be more flexible. Is there any way I can improve this? Thanks!

答:
Regular expressions are just strings you pass to re.compile and friends. The full palette of Python string formatting is at your disposal.

Perhaps something like this, then?

picPegex = re.compile('|'.join([r'.*\.{0}'.format(x) for x in ('jpg', 'png')]))
```

<p>If you always need these at the end of line, though, maybe simply</p>

```if thing.endswith(tuple(['.{0}' for x in ('jpg', 'png')])):
    print('yowza')
```

Title: Adding input variable inside regex

Body:
I'm trying to make a code that finds all preferred file extension and then moves them to designed folder. Code is working but I need to enter file extensions manually inside the file. What I'm trying to do is add an input variable and place it into re.compile(), therefore I don't need to edit the file whenever I need it for different file types.

This part I need to edit:

# Go through the listFiles and find specific file types.
picRegex = re.compile(r'.*\.jpg|.*\.png')
fileMatches = list(filter(picRegex.match, listFiles)

This works for the filetypes already there in my code but as I said I want it to be more flexible. Is there any way I can improve this? Thanks!

Body:
Regular expressions are just strings you pass to re.compile and friends. The full palette of Python string formatting is at your disposal.

Perhaps something like this, then?

picPegex = re.compile('|'.join([r'.*\.{0}'.format(x) for x in ('jpg', 'png')]))

If you always need these at the end of line, though, maybe simply

if thing.endswith(tuple(['.{0}' for x in ('jpg', 'png')])):
    print('yowza')


来源: stackexchange

答:
Generate the regular expression with string methods:

```<code>file_extensions = ['.png','.jpg']
regex = '.*(%s)' % '|'.join(map(re.escape, file_extensions))
filename_matches = list(filter(re.compile(regex).fullmatch, filenames)
</code>```

Better, don't use regular expressions at all, but endswith:

```<code>file_extensions = tuple(['.png','.jpg'])
filename_matches = [f for f in filenames if f.endswith(file_extensions)]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Adding input variable inside regex

Body:
Generate the regular expression with string methods:

file_extensions = ['.png','.jpg']
regex = '.*(%s)' % '|'.join(map(re.escape, file_extensions))
filename_matches = list(filter(re.compile(regex).fullmatch, filenames)

Better, don't use regular expressions at all, but endswith:

file_extensions = tuple(['.png','.jpg'])
filename_matches = [f for f in filenames if f.endswith(file_extensions)]


问:
test whether k elements of a set add up to a certain number
Is there a way to determine if k elements of a set add up to a certain number in polynomial time?</p>

答:
How big is the number?

This is a variation on the subset sum problem, which is well-known and NP-complete.  However dynamic programming techniques will make it polynomial if the set of possible values that the subsets can take grows polynomially.  Which with general integers, isn't true.  But with numbers picked from a restricted range happens surprisingly often.

ContentLicense: CC BY-SA 3.0


问:
React JS - Get the top of the page after refreshing the same page
I'm pretty new on React JS. I saw a lot of similar questions about getting the top of the page with React Router, etc. But my question is not about React Router, it's just about React JS itself.

I'm working on a one page, and I'm wondering how can I get the top of my page every time I refresh this page. I mean, when I refresh the page, I'm still at the same place.
I tried this :

```<code>componentDidMount(){
  window.scrollTo(0, 0);
}
</code>```

But it does not working. Of course, I tried all things people recommended on similar subjects.

Any other ideas ?

答:
you can use it like this</p>

```<code>import React,{Component} from 'react';

class App extends Component{
    componentDidMount(){
        this.wrapperNode.current.scrollTo(0,0)
    }
    render(){
        return <div ref={node=>this.wrapperNode = node}>Your Content</div>
    }
}
</code>```

Body:
I'm pretty new on React JS. I saw a lot of similar questions about getting the top of the page with React Router, etc. But my question is not about React Router, it's just about React JS itself.

I'm working on a one page, and I'm wondering how can I get the top of my page every time I refresh this page. I mean, when I refresh the page, I'm still at the same place.
I tried this :

componentDidMount(){
  window.scrollTo(0, 0);
}

But it does not working. Of course, I tried all things people recommended on similar subjects.

Any other ideas ?

Body:
you can use it like this

import React,{Component} from 'react';

class App extends Component{
    componentDidMount(){
        this.wrapperNode.current.scrollTo(0,0)
    }
    render(){
        return <div ref={node=>this.wrapperNode = node}>Your Content</div>
    }
}


问:
PDI MongoDB Input and Output steps
I recently installed PDI 8.2 CE - doesn't look like it comes with the Mongo input and output steps...

I found it here https://github.com/pentaho/pentaho-mongodb-plugin I unzipped that and put the entire folder in to the ../data-integration/plugins directory and restarted PDI but still no mongo input/output.

What am I doing wrong?

答: you do not need to add any additional plugins because it's under big data section you will find both input and output for mongodb.

Title: PDI MongoDB Input and Output steps


问:
dplyr - recode several columns at once
Suppose you have a dataframe with variables named X1 - X30 and Y1 - Y30. Each of these variables holds integers 1 - 5. We wish to recode some of the variables starting with X like this:

```<code>df %<>%
   mutate_at(vars(starts_with("X") &
                  ends_with("5", "8", "16", "22", "28")),
             recode, "1" = 5, "2" = 4, "4" = 2, "5" = 1)
</code>```

This will, however, return the following error:

```<code>Error in UseMethod("recode") :
  no applicable method for 'recode' applied to an object of class "c('tbl_df', 'tbl', 'data.frame')"
</code>```

This is because recode needs to take a vector as an argument. So what is the way to bypass this?

Title: dplyr - recode several columns at once

Body:
Suppose you have a dataframe with variables named X1 - X30 and Y1 - Y30. Each of these variables holds integers 1 - 5. We wish to recode some of the variables starting with X like this:

df %<>%
   mutate_at(vars(starts_with("X") &
                  ends_with("5", "8", "16", "22", "28")),
             recode, "1" = 5, "2" = 4, "4" = 2, "5" = 1)

This will, however, return the following error:

Error in UseMethod("recode") :
  no applicable method for 'recode' applied to an object of class "c('tbl_df', 'tbl', 'data.frame')"

This is because recode needs to take a vector as an argument. So what is the way to bypass this?

Body:
One option is to substring the colnames, and then do mutate_if:

set.seed(111)
df = data.frame(matrix(round(runif(60*4,min=1,max=5)),ncol=60))
colnames(df) = c(paste0("X",1:30),paste0("Y",1:30))

start_X = substr(colnames(df),1,1) == "X"
ends_w = substr(colnames(df),2,nchar(colnames(df))) %in% c("5", "8", "16", "22", "28")

df %>%
mutate_if(start_X & ends_w,
recode, "1" = 5, "2" = 4, "4" = 2, "5" = 1) %>%
select(c("X5","X8","X16","X22","X28"))

  X5 X8 X16 X22 X28
1  4  2   5   5   3
2  1  3   3   4   1
3  4  5   4   2   4
4  3  3   4   2   2

df %>% select(c("X5","X8","X16","X22","X28"))
  X5 X8 X16 X22 X28
1  2  4   1   1   3
2  5  3   3   2   5
3  2  1   2   4   2
4  3  3   2   4   4


问:
Ansible get_url is timing out
I have troubles downloading a jar file from Artifactory on a CentOs7 instance with Ansible. It is the first time i do that on a Linux instance.

I am using the win_get_url module on every Windows instance and it is working normaly

```<code>   - name: download artifacts
     win_get_url:
       url: '{{ some_url }}'
       username: '{{ jfrog_username }}'
       password: '{{ jfrog_password }}'
       dest: '{{ some_dest }}'
       force: no
       proxy_url: {{ some_proxy }}
</code>```

When i use the get_url module it is timeing out. I have noticed that the Linux module doen't support the parameter "proxy_url". so i have tried to run the tasks with some other parameters like

```<code>   - name: download artifacts
     get_url:
       url: '{{ some_url }}'
       username: '{{ jfrog_username }}'
       password: '{{ jfrog_password }}'
       dest: '{{ some_dest }}'
       force: no
       use_proxy: yes
       http_agent"{{ proxy }}
       checksum: {{ checksum }}
</code>```

But it gives me always this error:

```<code>  "status": -1,
  "url": "https://some_url/installer.jar",
  "msg": "Failed to connect to www.jfrog.io at port 443: [Errno 110] Connection timed out",
  "invocation": {
</code>```

I have checked the Firewall setting and https is open from/into this server.

Any help would be appreciated.

UPDATE:

If i use curl, based on the tip mentioned by Zeitounator it works! i can download the file with:

```<code>     curl -O -u --user user:password 'https://some_url/installer.jar'
</code>```

I am not using proxy password. When curl asked voor proxy password i just pressed enter and curl downloaded the file without any issues.

But with Ansible still no luck.

答:
if proxy is configured @Zeitounator answered it correctly.

But still can try adding below:

```<code>- name: download artifacts
 get_url:
   url: '{{ some_url }}'
   username: '{{ jfrog_username }}'
   password: '{{ jfrog_password }}'
   dest: '{{ some_dest }}'
   force: no
   use_proxy: yes
   http_agent"{{ proxy }}
   checksum: {{ checksum }}
   timeout: 30
</code>```

As default timeout for get_url module is 10 seconds

Title: Ansible get_url is timing out

Body:
I have troubles downloading a jar file from Artifactory on a CentOs7 instance with Ansible. It is the first time i do that on a Linux instance.

I am using the win_get_url module on every Windows instance and it is working normaly

   - name: download artifacts
     win_get_url:
       url: '{{ some_url }}'
       username: '{{ jfrog_username }}'
       password: '{{ jfrog_password }}'
       dest: '{{ some_dest }}'
       force: no
       proxy_url: {{ some_proxy }}

When i use the get_url module it is timeing out. I have noticed that the Linux module doen't support the parameter "proxy_url". so i have tried to run the tasks with some other parameters like

   - name: download artifacts
     get_url:
       url: '{{ some_url }}'
       username: '{{ jfrog_username }}'
       password: '{{ jfrog_password }}'
       dest: '{{ some_dest }}'
       force: no
       use_proxy: yes
       http_agent"{{ proxy }}
       checksum: {{ checksum }}

But it gives me always this error:

  "status": -1,
  "url": "https://some_url/installer.jar",
  "msg": "Failed to connect to www.jfrog.io at port 443: [Errno 110] Connection timed out",
  "invocation": {

I have checked the Firewall setting and https is open from/into this server.

Any help would be appreciated.

UPDATE:

If i use curl, based on the tip mentioned by Zeitounator it works! i can download the file with:

     curl -O -u --user user:password 'https://some_url/installer.jar'

I am not using proxy password. When curl asked voor proxy password i just pressed enter and curl downloaded the file without any issues.

But with Ansible still no luck.

Body:
if proxy is configured @Zeitounator answered it correctly.

But still can try adding below:

- name: download artifacts
 get_url:
   url: '{{ some_url }}'
   username: '{{ jfrog_username }}'
   password: '{{ jfrog_password }}'
   dest: '{{ some_dest }}'
   force: no
   use_proxy: yes
   http_agent"{{ proxy }}
   checksum: {{ checksum }}
   timeout: 30

As default timeout for get_url module is 10 seconds


问:
What do I link in to define boost::thread_specific_ptr and related?
I want to use boost::thread_specific_ptr but need to know what to add to my gcc v3.4.6 link line to define what it uses:

```<code>/usr/include/boost/thread/tss.hpp:35: undefined reference to `boost::thread_resource_error::thread_resource_error()'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0x5b):/usr/include/boost/thread/tss.hpp:35: undefined reference to `boost::thread_resource_error::~thread_resource_error()'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0x60):/usr/include/boost/thread/tss.hpp:35: undefined reference to `typeinfo for boost::thread_resource_error'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0x76):/usr/include/boost/thread/tss.hpp:38: undefined reference to `boost::detail::tss::init(boost::function1<void, void*, std::allocator<boost::function_base> >*)'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0xd2):/usr/include/boost/thread/tss.hpp:43: undefined reference to `boost::thread_resource_error::thread_resource_error()'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0xf8):/usr/include/boost/thread/tss.hpp:43: undefined reference to `boost::thread_resource_error::~thread_resource_error()'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0xfd):/usr/include/boost/thread/tss.hpp:43: undefined reference to `typeinfo for boost::thread_resource_error'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZNK5boost19thread_specific_ptrIN5Botan14AutoSeeded_RNGEE3getEv+0x11): In function `boost::thread_specific_ptr<Botan::AutoSeeded_RNG>::get() const':
/usr/include/boost/thread/tss.hpp:89: undefined reference to `boost::detail::tss::get() const'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost19thread_specific_ptrIN5Botan14AutoSeeded_RNGEE5resetEPS2_+0x2f): In function `boost::thread_specific_ptr<Botan::AutoSeeded_RNG>::reset(Botan::AutoSeeded_RNG*)':
/usr/include/boost/thread/tss.hpp:97: undefined reference to `boost::detail::tss::set(void*)'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost19thread_specific_ptrIN5Botan14AutoSeeded_RNGEE5resetEPS2_+0x4a):/usr/include/boost/thread/tss.hpp:98: undefined reference to `boost::detail::tss::cleanup(void*)'
</code>```

What should I be linking in to define all of these?

答: On my Ubuntu system I use -lboost_thread (since libboost_thread.so is already in my /usr/lib I don't need any -L options).

Body:
I want to use boost::thread_specific_ptr but need to know what to add to my gcc v3.4.6 link line to define what it uses:

/usr/include/boost/thread/tss.hpp:35: undefined reference to `boost::thread_resource_error::thread_resource_error()'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0x5b):/usr/include/boost/thread/tss.hpp:35: undefined reference to `boost::thread_resource_error::~thread_resource_error()'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0x60):/usr/include/boost/thread/tss.hpp:35: undefined reference to `typeinfo for boost::thread_resource_error'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0x76):/usr/include/boost/thread/tss.hpp:38: undefined reference to `boost::detail::tss::init(boost::function1<void, void*, std::allocator<boost::function_base> >*)'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0xd2):/usr/include/boost/thread/tss.hpp:43: undefined reference to `boost::thread_resource_error::thread_resource_error()'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0xf8):/usr/include/boost/thread/tss.hpp:43: undefined reference to `boost::thread_resource_error::~thread_resource_error()'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost6detail3tssC1EPNS_9function1IvPvSaINS_13function_baseEEEE+0xfd):/usr/include/boost/thread/tss.hpp:43: undefined reference to `typeinfo for boost::thread_resource_error'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZNK5boost19thread_specific_ptrIN5Botan14AutoSeeded_RNGEE3getEv+0x11): In function `boost::thread_specific_ptr<Botan::AutoSeeded_RNG>::get() const':
/usr/include/boost/thread/tss.hpp:89: undefined reference to `boost::detail::tss::get() const'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost19thread_specific_ptrIN5Botan14AutoSeeded_RNGEE5resetEPS2_+0x2f): In function `boost::thread_specific_ptr<Botan::AutoSeeded_RNG>::reset(Botan::AutoSeeded_RNG*)':
/usr/include/boost/thread/tss.hpp:97: undefined reference to `boost::detail::tss::set(void*)'
../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN5boost19thread_specific_ptrIN5Botan14AutoSeeded_RNGEE5resetEPS2_+0x4a):/usr/include/boost/thread/tss.hpp:98: undefined reference to `boost::detail::tss::cleanup(void*)'

What should I be linking in to define all of these?


问:
Why does termcolor output control characters instead of colored text in the Windows console?
I just installed termcolor for Python 2.7 on Windows. When I try to print colored text, I get the color codes instead.

```<code>from termcolor import colored
print colored('Text text text', 'red')
</code>```

Here is the result:

I obtain the same results on Far Manager and when I tried to run the script as a standalone application.

答:
Here is a simple function I find useful to print in color. You do not need to make any imports and you do not have to remember complex ANSI codes. The function uses standard RGB tuples to define the foreground and background color.You can find a RGB color picker at https://www.google.com/search?q=rgb+color+picker&oq=rgb+color+picker&aqs=chrome..69i57j0l7.5967j0j8&sourceid=chrome&ie=UTF-8</p>

```<code>def print_in_color(txt_msg,fore_tupple,back_tupple,):
    #prints the text_msg in the foreground color specified by fore_tupple with the background specified by back_tupple
    #text_msg is the text, fore_tupple is foregroud color tupple (r,g,b), back_tupple is background tupple (r,g,b)
    rf,gf,bf=fore_tupple
    rb,gb,bb=back_tupple
    msg='{0}' + txt_msg
    mat='\33[38;2;' + str(rf) +';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) +'m'
    print(msg .format(mat))
    print('\33[0m') # returns default print color to back to black

# example of use using a message with variables
fore_color='cyan'
back_color='dark green'
msg='foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255),(0,127,127))

</code>```

Body:
I just installed termcolor for Python 2.7 on Windows. When I try to print colored text, I get the color codes instead.

from termcolor import colored
print colored('Text text text', 'red')

Here is the result:

I obtain the same results on Far Manager and when I tried to run the script as a standalone application.

Body:
Here is a simple function I find useful to print in color. You do not need to make any imports and you do not have to remember complex ANSI codes. The function uses standard RGB tuples to define the foreground and background color.You can find a RGB color picker at https://www.google.com/search?q=rgb+color+picker&oq=rgb+color+picker&aqs=chrome..69i57j0l7.5967j0j8&sourceid=chrome&ie=UTF-8

def print_in_color(txt_msg,fore_tupple,back_tupple,):
    #prints the text_msg in the foreground color specified by fore_tupple with the background specified by back_tupple
    #text_msg is the text, fore_tupple is foregroud color tupple (r,g,b), back_tupple is background tupple (r,g,b)
    rf,gf,bf=fore_tupple
    rb,gb,bb=back_tupple
    msg='{0}' + txt_msg
    mat='\33[38;2;' + str(rf) +';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) +'m'
    print(msg .format(mat))
    print('\33[0m') # returns default print color to back to black

# example of use using a message with variables
fore_color='cyan'
back_color='dark green'
msg='foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255),(0,127,127))


问:
How to replace irregular string prefix using Javascript?
So, I have an array of strings that have irregular, non-sequential prefixes (e.g. 1. Some file name; 2. Some file name; 11. Some file name; 10. Some file name; 1. Some file name; 2. Some file name; 2. Some file name; etc.

How would I go about renaming these sequentially? I'm having a little bit of a mental block, since I'm unclear how replace will affect a variably long first part of the string, while preserving the integrity of the rest of the string (e.g. once the prefix gets to a certain length will it truncate parts of the rest of the string). My second issue is how do consistently identify the changing prefix to get renamed in a for loop? I don't think I can use a fixed substring to grab the prefix, because I will either grab part of or too much of the string. I assume I need to write some sort of function to evaluate and normalize the prefix before using the replace method. I guess in my case I could just grab and replace the first three characters and ignore the "." character, but I'd like to find a more universal and maintainable approach to this.

Here's a snippet that I assume is barking up the wrong tree...

```<code>if(suffix === "txt"){

 prefix = file.charAt(0);
        console.log(prefix);
        if(!isNaN(prefix)){
            newPre = prefix++;
            newFile = file.replace(newPre, prefix);
            console.log(newFile);
            file1 = path.join(directoryPath, file);
            newFile1 = path.join(directoryPath, newFile);
            fs.rename(file1, newFile1, function(err){
                if(err) throw err;
                console.log('it worked, mofo!');
            })

        }
</code>```

Edit:

Desired result is the same order of the array re-prefixed as such:

```<code>[
1. Some file name
2. Some file name
3. Some file name
etc
]
</code>```

Would be nice to find a result that could deal with multiple character long prefix strings or that would ensure the prefix renaming didn't truncate the rest of the string.

Thanks

答:
Regular Expressions can help you with your problem.

I am assuming the prefix you want to get rid of is the number at the beginning of all your example filenames:

```<code>1. Some file name
2. Some file name
11. Some file name
10. Some file name
1. Some file name
2. Some file name
2. Some file name
</code>```

In english we would describe the prefix we want to get rid of as: some numbers, followed by a dot, followed by whitespace.

In regular expressions this is written as:

```<code>   ^      at the beginning of the string
   \d+    match some numbers
   \.     a dot
   \s+    and some whitespace
</code>```

you can try it out online in a regular expression tester,
and then incorporate it in your program.

```<code>newFile = file.replace(/^\d+\.\s+/, prefix);
</code>```

To learn more:

Introduction to Regular Expressions on MDN

P.S. regular expressions are available in all programming languages.
they are hard to learn because they are so compact, but once you
have understood the basics you can use them in many programming languages.

Body:
So, I have an array of strings that have irregular, non-sequential prefixes (e.g. 1. Some file name; 2. Some file name; 11. Some file name; 10. Some file name; 1. Some file name; 2. Some file name; 2. Some file name; etc.

How would I go about renaming these sequentially? I'm having a little bit of a mental block, since I'm unclear how replace will affect a variably long first part of the string, while preserving the integrity of the rest of the string (e.g. once the prefix gets to a certain length will it truncate parts of the rest of the string). My second issue is how do consistently identify the changing prefix to get renamed in a for loop? I don't think I can use a fixed substring to grab the prefix, because I will either grab part of or too much of the string. I assume I need to write some sort of function to evaluate and normalize the prefix before using the replace method. I guess in my case I could just grab and replace the first three characters and ignore the "." character, but I'd like to find a more universal and maintainable approach to this.

Here's a snippet that I assume is barking up the wrong tree...

if(suffix === "txt"){

 prefix = file.charAt(0);
        console.log(prefix);
        if(!isNaN(prefix)){
            newPre = prefix++;
            newFile = file.replace(newPre, prefix);
            console.log(newFile);
            file1 = path.join(directoryPath, file);
            newFile1 = path.join(directoryPath, newFile);
            fs.rename(file1, newFile1, function(err){
                if(err) throw err;
                console.log('it worked, mofo!');
            })

        }

Edit:

Desired result is the same order of the array re-prefixed as such:

[
1. Some file name
2. Some file name
3. Some file name
etc
]

Would be nice to find a result that could deal with multiple character long prefix strings or that would ensure the prefix renaming didn't truncate the rest of the string.

Thanks

Body:
Regular Expressions can help you with your problem.

I am assuming the prefix you want to get rid of is the number at the beginning of all your example filenames:

1. Some file name
2. Some file name
11. Some file name
10. Some file name
1. Some file name
2. Some file name
2. Some file name

In english we would describe the prefix we want to get rid of as: some numbers, followed by a dot, followed by whitespace.

In regular expressions this is written as:

   ^      at the beginning of the string
   \d+    match some numbers
   \.     a dot
   \s+    and some whitespace

you can try it out online in a regular expression tester,
and then incorporate it in your program.

newFile = file.replace(/^\d+\.\s+/, prefix);

To learn more:

Introduction to Regular Expressions on MDN

P.S. regular expressions are available in all programming languages.
they are hard to learn because they are so compact, but once you
have understood the basics you can use them in many programming languages.


问:
Defining and initialize a class property in PHP Laravel controller
I try defined property for some controller and i get error :

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)

Constant expression contains invalid operations

This my controller code :

namespace App\Http\Controllers...;

```<code>use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Customer;
use App\City;
use Illuminate\Database\Eloquent\Builder;
use Carbon\Carbon;

use Illuminate\Support\Facades\Auth;

class CatalogController extends Controller
{
    protected $user = Auth::user();

    function user() {
       $user = optional(Auth::user())->load(['city']);
       return $user;
    }
}
</code>```

In php.net I read this:

Class member variables may be initialized, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

I assume that this rule is not executed in my code. Am I right?

答:
Retrieving the user in a controller method is fine because it is only executed once for the request. There is no need to advantage to storing it as instance property because a new instance of the controllers is made for every request.

You could use the following code:

```<code>public function index()
{
    $user = Auth::user()->with('city')->get();
    $articles = $this->getArticlesForUser($user);

    return view('home', [
        'user' => $user
    ]);
}

public function getArticlesForUser(User $user){
  // Do something with $user
  return [];
}

public function delete()
{
    $user = Auth::user();
    $user->delete();

    return view('home');
}
</code>```

If the goal is to have calculate the values once and use them at various places a singleton can be used:

<?php

class Settings {
    private $accessToken = '';
    private $items = [];

    private static $instance = null;

    protected function __construct(){}

    public static function getInstance(){
        if(static::$instance == null){
            static::$instance = static::buildInstance();
        }

        return static::$instance;
    }

    private static function buildInstance(){
        $instance = new Settings();
        $instance->accessToken = md5(rand(1,1000));
        $instance->items = [1,2,3];

        return $instance;
    }

    public function getToken(){
        return $this->accessToken;
    }
}

$settings = Settings::getInstance();
// Both return the same token because the instance is the same
var_dump($settings->getToken());
var_dump(Settings::getInstance()->getToken());
```

Body:
I try defined property for some controller and i get error :

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)

Constant expression contains invalid operations

This my controller code :

namespace App\Http\Controllers...;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Customer;
use App\City;
use Illuminate\Database\Eloquent\Builder;
use Carbon\Carbon;

use Illuminate\Support\Facades\Auth;

class CatalogController extends Controller
{
    protected $user = Auth::user();

    function user() {
       $user = optional(Auth::user())->load(['city']);
       return $user;
    }
}

In php.net I read this:

Class member variables may be initialized, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

I assume that this rule is not executed in my code. Am I right?

Body:
Retrieving the user in a controller method is fine because it is only executed once for the request. There is no need to advantage to storing it as instance property because a new instance of the controllers is made for every request.

You could use the following code:

public function index()
{
    $user = Auth::user()->with('city')->get();
    $articles = $this->getArticlesForUser($user);

    return view('home', [
        'user' => $user
    ]);
}

public function getArticlesForUser(User $user){
  // Do something with $user
  return [];
}

public function delete()
{
    $user = Auth::user();
    $user->delete();

    return view('home');
}

If the goal is to have calculate the values once and use them at various places a singleton can be used:

<?php

class Settings {
    private $accessToken = '';
    private $items = [];

    private static $instance = null;

    protected function __construct(){}

    public static function getInstance(){
        if(static::$instance == null){
            static::$instance = static::buildInstance();
        }

        return static::$instance;
    }

    private static function buildInstance(){
        $instance = new Settings();
        $instance->accessToken = md5(rand(1,1000));
        $instance->items = [1,2,3];

        return $instance;
    }

    public function getToken(){
        return $this->accessToken;
    }
}

$settings = Settings::getInstance();
// Both return the same token because the instance is the same
var_dump($settings->getToken());
var_dump(Settings::getInstance()->getToken());


问:
Dotless File Yields 404 Error in IIS
I've been successfully using .less files in my dev Cassini server (with dotless) for a few weeks but when I publish to my local IIS server they yield 404 errors. Attaching my debugger to IIS yields no exceptions.  I've restarted my IIS app pool and server as well.

Any ideas?

答:
Looks like you're missing a mime type on IIS.

For IIS7 add the following to your web.config:

```<code><system.webServer>
    <staticContent>
        <mimeMap fileExtension=".less" mimeType="text/css" />
    </staticContent>
</system.webServer>
</code>```

For IIS6 you can do (presuming you have administrator RDP access):

```<code>cscript adsutil.vbs set W3SVC/1/Root/MimeMap ".less, text/css"
</code>```

Where /1/ is the IIS number of the site.

Title: Dotless File Yields 404 Error in IIS

Body:
Looks like you're missing a mime type on IIS.

For IIS7 add the following to your web.config:

<system.webServer>
    <staticContent>
        <mimeMap fileExtension=".less" mimeType="text/css" />
    </staticContent>
</system.webServer>

For IIS6 you can do (presuming you have administrator RDP access):

cscript adsutil.vbs set W3SVC/1/Root/MimeMap ".less, text/css"

Where /1/ is the IIS number of the site.


问:
Can not assign observable data to local variable in angular
My Service

```<code>import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { HttpClient,HttpParams } from '@angular/common/http';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) { }
  isAdmin;
  getLogIn(email:string,password:string):Observable<boolean>{
    let params = new HttpParams().set("userEmail",email).set("userPassword", password);
    return this.http.get<boolean>("http://localhost:8080/user/login",{params: params});
     }
}
</code>```

My Subscribe call

```<code> email:string="";
  password:string="";
  adminFlag:boolean=false;

  login(event: any) {
    console.log(this.adminFlag);
    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
    console.log(this.adminFlag);
    if(this.adminFlag){
      console.log("INSIDE IF")
        this.router.navigate("../../home");
    }
  }
</code>```

When i log in data var in console I am getting raw data as

```<code>true
</code>```

but i couldn't assign it to this boolean "adminFlag" it is changed to undefined

Anything I missed...???

the API is returning a boolean..I need that boolean to be assigned...

答:
HTTP GET is an asynchronous request. Which means you are reading the variable adminFlag before it is being set. Move the routing inside callback to set the value and use it. Its also always good practice to include error callback in HTTP requests. This should work:

```<code>login(event: any) {
  this.userService.getLogIn(this.email,this.password).subscribe(
    data => {
      this.adminFlag = data;
      if (data) {
        this.router.navigate("../../home");
      }
    },
    error => {
      console.error('getLogIn failed');
      // handle error...
    }
  );
}
</code>```

Body:
My Service

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs';
import { HttpClient,HttpParams } from '@angular/common/http';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) { }
  isAdmin;
  getLogIn(email:string,password:string):Observable<boolean>{
    let params = new HttpParams().set("userEmail",email).set("userPassword", password);
    return this.http.get<boolean>("http://localhost:8080/user/login",{params: params});
     }
}

My Subscribe call

 email:string="";
  password:string="";
  adminFlag:boolean=false;

  login(event: any) {
    console.log(this.adminFlag);
    this.userService.getLogIn(this.email,this.password).subscribe(data => this.adminFlag=(data));
    console.log(this.adminFlag);
    if(this.adminFlag){
      console.log("INSIDE IF")
        this.router.navigate("../../home");
    }
  }

When i log in data var in console I am getting raw data as

true

but i couldn't assign it to this boolean "adminFlag" it is changed to undefined

Anything I missed...???

the API is returning a boolean..I need that boolean to be assigned...

Body:
HTTP GET is an asynchronous request. Which means you are reading the variable adminFlag before it is being set. Move the routing inside callback to set the value and use it. Its also always good practice to include error callback in HTTP requests. This should work:

login(event: any) {
  this.userService.getLogIn(this.email,this.password).subscribe(
    data => {
      this.adminFlag = data;
      if (data) {
        this.router.navigate("../../home");
      }
    },
    error => {
      console.error('getLogIn failed');
      // handle error...
    }
  );
}


问:
Field having unique and not null
Suppose a field is in the table of int data type and is declared a unique key and not null.

Can I use it as primary key?

答:
There are three criteria for a primary key:

Non-null

Unique

Only one per table

Declaring a column as a primary key entails all three of these -- you don't need to separate declare a column unique or not null.  You can use such a column as a primary key if no other column(s) are already declared as the primary key for the table.

Title: Field having unique and not null


问:
How to concisely cascade through multiple regex statements in Python
My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on.  The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth.  I could do something like this:

```<code>if re.match('regex1', string):
    match = re.match('regex1', string)
    # Manipulate match.group(n) and return
elif re.match('regex2', string):
    match = re.match('regex2', string)
    # Do second manipulation
[etc.]
</code>```

However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.

Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?

答:
I had the same problem as yours. Here´s my solution:

```<code>import re

regexp = {
    'key1': re.compile(r'regexp1'),
    'key2': re.compile(r'regexp2'),
    'key3': re.compile(r'regexp3'),
    # ...
}

def test_all_regexp(string):
    for key, pattern in regexp.items():
        m = pattern.match(string)
        if m:
            # do what you want
            break
</code>```

It´s a slightly modified solution from the answer of Extracting info from large structured text files

OwnerDisplayName: One Crayon

ContentLicense: CC BY-SA 2.5

Body:
My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on.  The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth.  I could do something like this:

if re.match('regex1', string):
    match = re.match('regex1', string)
    # Manipulate match.group(n) and return
elif re.match('regex2', string):
    match = re.match('regex2', string)
    # Do second manipulation
[etc.]

However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.

Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?

Body:
I had the same problem as yours. Here´s my solution:

import re

regexp = {
    'key1': re.compile(r'regexp1'),
    'key2': re.compile(r'regexp2'),
    'key3': re.compile(r'regexp3'),
    # ...
}

def test_all_regexp(string):
    for key, pattern in regexp.items():
        m = pattern.match(string)
        if m:
            # do what you want
            break

It´s a slightly modified solution from the answer of Extracting info from large structured text files

OwnerDisplayName: Luiz Damim


问:
Configuring distcc for makefiles
I am testing distcc and I found this tutorial very easy to follow, I should say that I am able to compile llvm using CMake + Ninja and CMake + Makefiles using distcc and docker with no problems. Since I am particularly interested in Makefiles, I looked at the files produced by CMake + Ninja and all I saw was that distcc is added as a prefix to the compiler (e.g. distcc /usr/bin/gcc). So I thought that if I create a small project using only Makefiles I could possibly add distcc and things will magically work. Well, looks like I am missing something because all I get is:

```<code>$ ./mk.sh image

make[1]: Entering directory '/home/user/sandbox/distcc-makefiles'
Compiling Lib/Print.c
Compiling Boot/Main.c
distcc[16644] ERROR: compile Boot/Main.c on 172.17.0.2/1 failed
distcc[16644] (dcc_build_somewhere) Warning: remote compilation of 'Boot/Main.c' failed, retrying locally
distcc[16644] Warning: failed to distribute Boot/Main.c to 172.17.0.2/1, running locally instead
distcc[16644] (dcc_please_send_email_after_investigation) Warning: remote compilation of 'Boot/Main.c' failed, retried locally and got a different result.
distcc[16643] ERROR: compile Lib/Print.c on 172.17.0.2/1 failed
distcc[16643] (dcc_build_somewhere) Warning: remote compilation of 'Lib/Print.c' failed, retrying locally
distcc[16643] Warning: failed to distribute Lib/Print.c to 172.17.0.2/1, running locally instead
distcc[16643] (dcc_please_send_email_after_investigation) Warning: remote compilation of 'Lib/Print.c' failed, retried locally and got a different result.
make[1]: Leaving directory '/home/user/sandbox/distcc-makefiles'
</code>```

By running the llvm example I discarded all docker connection and distcc configuration issues, I tried to search for any ideas/examples on the internet but most of the people use CMake which is not my case. Suggestions are welcome, I based my demo project on a real project I am working on, so that's how basically the Makefile look like.

I don't know what I am missing...

Versions:

Just for reference:

```<code>$ distcc --version
distcc 3.1 x86_64-pc-linux-gnu
  (protocols 1, 2 and 3) (default port 3632)
  built Oct 19 2017 11:05:18
Copyright (C) 2002, 2003, 2004 by Martin Pool.
Includes miniLZO (C) 1996-2002 by Markus Franz Xaver Johannes Oberhumer.
Portions Copyright (C) 2007-2008 Google.
</code>```

```<code>$ gcc --version
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.
</code>```

```<code>$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.
</code>```

答:
After enabling debug messages (with $ export DISTCC_VERBOSE=1), I found that distcc actually compiles in the server but the compilation fails and that's why it retries locally.

It fails because I am using external files to keep additional options (see gcc @file) and distcc doesnt interpret that as a file but rather as a string basically. That's why the compilation fails and distcc fallsback.

Log inspection

For reference, the distcc log looks like the following (divided into sections for further explanation):

```<code>... {{ SECTION A }}
distcc[13039] (dcc_spawn_child) forking to execute: gcc -std=c99 -Wall @_out/Release/Boot/Main.o.via -E /home/user/sandbox/distcc-makefiles/Boot/Main.c
distcc[13040] (dcc_get_hostlist) read hosts from environment
distcc[13040] (dcc_parse_hosts) found tcp token "172.17.0.2/1"
distcc[13039] (dcc_spawn_child) child started as pid13041

... {{ SECTION B }}

distcc[13039] (dcc_strip_local_args) result: gcc -std=c99 -Wall @_out/Release/Boot/Main.o.via -c /home/user/sandbox/distcc-makefiles/Boot/Main.c -o _out/Release/Boot/Main.o
distcc[13039] exec on 172.17.0.2/1: gcc -std=c99 -Wall @_out/Release/Boot/Main.o.via -c /home/user/sandbox/distcc-makefiles/Boot/Main.c -o _out/Release/Boot/Main.o
distcc[13039] (dcc_note_state) note state 2, file "Main.c", host "172.17.0.2"
distcc[13039] (dcc_connect_by_name) connecting to 172.17.0.2 port 3632
distcc[13041] (dcc_new_pgrp) entered process group
distcc[13041] (dcc_increment_safeguard) setting safeguard: _DISTCC_SAFEGUARD=1
distcc[13039] (dcc_connect_by_addr) started connecting to 172.17.0.2:3632

... {{ SECTION C }}

distcc[13039] (dcc_select_for_write) select for write on fd6
distcc[13039] (dcc_note_state) note state 4, file "(NULL)", host "(NULL)"
distcc[13039] (dcc_x_token_int) send DIST00000001
distcc[13039] (dcc_x_token_int) send ARGC00000008
distcc[13039] (dcc_x_token_int) send ARGV00000003
distcc[13039] (dcc_x_token_string) send string 'gcc'
distcc[13039] (dcc_x_token_int) send ARGV00000008
distcc[13039] (dcc_x_token_string) send string '-std=c99'
distcc[13039] (dcc_x_token_int) send ARGV00000005
distcc[13039] (dcc_x_token_string) send string '-Wall'
distcc[13039] (dcc_x_token_int) send ARGV0000001d
distcc[13039] (dcc_x_token_string) send string '@_out/Release/Boot/Main.o.via'
distcc[13039] (dcc_x_token_int) send ARGV00000002
distcc[13039] (dcc_x_token_string) send string '-c'
distcc[13039] (dcc_x_token_int) send ARGV0000002f
distcc[13039] (dcc_x_token_string) send string '/home/user/sandbox/distcc-makefiles/Boot/Main.c'
distcc[13039] (dcc_x_token_int) send ARGV00000002
distcc[13039] (dcc_x_token_string) send string '-o'
distcc[13039] (dcc_x_token_int) send ARGV00000018
distcc[13039] (dcc_x_token_string) send string '_out/Release/Boot/Main.o'
distcc[13039] (dcc_note_state) note state 3, file "(NULL)", host "(NULL)"
distcc[13039] (dcc_collect_child) cpp child 13041 terminated with status 0
distcc[13039] (dcc_collect_child) cpp times: user 0.000000s, system 0.000000s, 0 minflt, 0 majflt
distcc[13039] cpp /home/user/sandbox/distcc-makefiles/Boot/Main.c on localhost completed ok

... {{ SECTION D }}

distcc[13039] (dcc_unlock) release lock fd4
distcc[13039] (dcc_x_file) send 14682 byte file /tmp/distcc_cd4d9216.i with token DOTI and compression 69
distcc[13039] (dcc_x_token_int) send DOTI0000395a
distcc[13039] (dcc_compile_remote) client finished sending request to server
distcc[13039] (dcc_note_state) note state 5, file "(NULL)", host "172.17.0.2"
distcc[13039] (dcc_select_for_read) select for read on fd6 for 300s
distcc[13039] (dcc_r_token_int) got DONE00000001
distcc[13039] (dcc_note_state) note state 6, file "(NULL)", host "(NULL)"
distcc[13039] (dcc_r_token_int) got STAT00000100
distcc[13039] (dcc_r_token_int) got SERR00000044
distcc[13039] (dcc_r_file) received 68 bytes to file /tmp/distcc_server_stderr_cd009216.txt
distcc[13039] (dcc_r_token_int) got SOUT00000000
distcc[13039] (dcc_r_token_int) got DOTO00000000

... {{ SECTION E }}

distcc[13039] 14682 bytes from /home/user/sandbox/distcc-makefiles/Boot/Main.c compiled on 172.17.0.2 in 0.0063s, rate 2274kB/s
distcc[13039] (dcc_unlock) release lock fd3
distcc[13039] ERROR: compile /home/user/sandbox/distcc-makefiles/Boot/Main.c on 172.17.0.2/1 failed
distcc[13039] (dcc_build_somewhere) Warning: remote compilation of '/home/user/sandbox/distcc-makefiles/Boot/Main.c' failed, retrying locally
distcc[13039] (dcc_mark_timefile) mark /home/user/.distcc/lock/backoff_tcp_172.17.0.2_3632_0
distcc[13039] Warning: failed to distribute /home/user/sandbox/distcc-makefiles/Boot/Main.c to 172.17.0.2/1, running locally instead
</code>```

where, to my understanding, SECTION A finds the remote server, SECTION B opens a connection to the server, SECTION C send the command to run in the server (includes the compile options and the file to compile), SECTION D fetches the result, and SECTION E analizes the result and decides what to do next. As you might see, this is the error:

```<code>distcc[13039] (dcc_x_token_string) send string '@_out/Release/Boot/Main.o.via'
distcc[13039] (dcc_x_token_int) send ARGV00000002
</code>```

Title: Configuring distcc for makefiles

Body:
I am testing distcc and I found this tutorial very easy to follow, I should say that I am able to compile llvm using CMake + Ninja and CMake + Makefiles using distcc and docker with no problems. Since I am particularly interested in Makefiles, I looked at the files produced by CMake + Ninja and all I saw was that distcc is added as a prefix to the compiler (e.g. distcc /usr/bin/gcc). So I thought that if I create a small project using only Makefiles I could possibly add distcc and things will magically work. Well, looks like I am missing something because all I get is:

$ ./mk.sh image

make[1]: Entering directory '/home/user/sandbox/distcc-makefiles'
Compiling Lib/Print.c
Compiling Boot/Main.c
distcc[16644] ERROR: compile Boot/Main.c on 172.17.0.2/1 failed
distcc[16644] (dcc_build_somewhere) Warning: remote compilation of 'Boot/Main.c' failed, retrying locally
distcc[16644] Warning: failed to distribute Boot/Main.c to 172.17.0.2/1, running locally instead
distcc[16644] (dcc_please_send_email_after_investigation) Warning: remote compilation of 'Boot/Main.c' failed, retried locally and got a different result.
distcc[16643] ERROR: compile Lib/Print.c on 172.17.0.2/1 failed
distcc[16643] (dcc_build_somewhere) Warning: remote compilation of 'Lib/Print.c' failed, retrying locally
distcc[16643] Warning: failed to distribute Lib/Print.c to 172.17.0.2/1, running locally instead
distcc[16643] (dcc_please_send_email_after_investigation) Warning: remote compilation of 'Lib/Print.c' failed, retried locally and got a different result.
make[1]: Leaving directory '/home/user/sandbox/distcc-makefiles'

By running the llvm example I discarded all docker connection and distcc configuration issues, I tried to search for any ideas/examples on the internet but most of the people use CMake which is not my case. Suggestions are welcome, I based my demo project on a real project I am working on, so that's how basically the Makefile look like.

I don't know what I am missing...

Versions:

Just for reference:

$ distcc --version
distcc 3.1 x86_64-pc-linux-gnu
  (protocols 1, 2 and 3) (default port 3632)
  built Oct 19 2017 11:05:18
Copyright (C) 2002, 2003, 2004 by Martin Pool.
Includes miniLZO (C) 1996-2002 by Markus Franz Xaver Johannes Oberhumer.
Portions Copyright (C) 2007-2008 Google.

$ gcc --version
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.

$ make --version
GNU Make 4.1
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.

Body:
After enabling debug messages (with $ export DISTCC_VERBOSE=1), I found that distcc actually compiles in the server but the compilation fails and that's why it retries locally.

It fails because I am using external files to keep additional options (see gcc @file) and distcc doesnt interpret that as a file but rather as a string basically. That's why the compilation fails and distcc fallsback.

Log inspection

For reference, the distcc log looks like the following (divided into sections for further explanation):

... {{ SECTION A }}
distcc[13039] (dcc_spawn_child) forking to execute: gcc -std=c99 -Wall @_out/Release/Boot/Main.o.via -E /home/user/sandbox/distcc-makefiles/Boot/Main.c
distcc[13040] (dcc_get_hostlist) read hosts from environment
distcc[13040] (dcc_parse_hosts) found tcp token "172.17.0.2/1"
distcc[13039] (dcc_spawn_child) child started as pid13041

... {{ SECTION B }}

distcc[13039] (dcc_strip_local_args) result: gcc -std=c99 -Wall @_out/Release/Boot/Main.o.via -c /home/user/sandbox/distcc-makefiles/Boot/Main.c -o _out/Release/Boot/Main.o
distcc[13039] exec on 172.17.0.2/1: gcc -std=c99 -Wall @_out/Release/Boot/Main.o.via -c /home/user/sandbox/distcc-makefiles/Boot/Main.c -o _out/Release/Boot/Main.o
distcc[13039] (dcc_note_state) note state 2, file "Main.c", host "172.17.0.2"
distcc[13039] (dcc_connect_by_name) connecting to 172.17.0.2 port 3632
distcc[13041] (dcc_new_pgrp) entered process group
distcc[13041] (dcc_increment_safeguard) setting safeguard: _DISTCC_SAFEGUARD=1
distcc[13039] (dcc_connect_by_addr) started connecting to 172.17.0.2:3632

... {{ SECTION C }}

distcc[13039] (dcc_select_for_write) select for write on fd6
distcc[13039] (dcc_note_state) note state 4, file "(NULL)", host "(NULL)"
distcc[13039] (dcc_x_token_int) send DIST00000001
distcc[13039] (dcc_x_token_int) send ARGC00000008
distcc[13039] (dcc_x_token_int) send ARGV00000003
distcc[13039] (dcc_x_token_string) send string 'gcc'
distcc[13039] (dcc_x_token_int) send ARGV00000008
distcc[13039] (dcc_x_token_string) send string '-std=c99'
distcc[13039] (dcc_x_token_int) send ARGV00000005
distcc[13039] (dcc_x_token_string) send string '-Wall'
distcc[13039] (dcc_x_token_int) send ARGV0000001d
distcc[13039] (dcc_x_token_string) send string '@_out/Release/Boot/Main.o.via'
distcc[13039] (dcc_x_token_int) send ARGV00000002
distcc[13039] (dcc_x_token_string) send string '-c'
distcc[13039] (dcc_x_token_int) send ARGV0000002f
distcc[13039] (dcc_x_token_string) send string '/home/user/sandbox/distcc-makefiles/Boot/Main.c'
distcc[13039] (dcc_x_token_int) send ARGV00000002
distcc[13039] (dcc_x_token_string) send string '-o'
distcc[13039] (dcc_x_token_int) send ARGV00000018
distcc[13039] (dcc_x_token_string) send string '_out/Release/Boot/Main.o'
distcc[13039] (dcc_note_state) note state 3, file "(NULL)", host "(NULL)"
distcc[13039] (dcc_collect_child) cpp child 13041 terminated with status 0
distcc[13039] (dcc_collect_child) cpp times: user 0.000000s, system 0.000000s, 0 minflt, 0 majflt
distcc[13039] cpp /home/user/sandbox/distcc-makefiles/Boot/Main.c on localhost completed ok

... {{ SECTION D }}

distcc[13039] (dcc_unlock) release lock fd4
distcc[13039] (dcc_x_file) send 14682 byte file /tmp/distcc_cd4d9216.i with token DOTI and compression 69
distcc[13039] (dcc_x_token_int) send DOTI0000395a
distcc[13039] (dcc_compile_remote) client finished sending request to server
distcc[13039] (dcc_note_state) note state 5, file "(NULL)", host "172.17.0.2"
distcc[13039] (dcc_select_for_read) select for read on fd6 for 300s
distcc[13039] (dcc_r_token_int) got DONE00000001
distcc[13039] (dcc_note_state) note state 6, file "(NULL)", host "(NULL)"
distcc[13039] (dcc_r_token_int) got STAT00000100
distcc[13039] (dcc_r_token_int) got SERR00000044
distcc[13039] (dcc_r_file) received 68 bytes to file /tmp/distcc_server_stderr_cd009216.txt
distcc[13039] (dcc_r_token_int) got SOUT00000000
distcc[13039] (dcc_r_token_int) got DOTO00000000

... {{ SECTION E }}

distcc[13039] 14682 bytes from /home/user/sandbox/distcc-makefiles/Boot/Main.c compiled on 172.17.0.2 in 0.0063s, rate 2274kB/s
distcc[13039] (dcc_unlock) release lock fd3
distcc[13039] ERROR: compile /home/user/sandbox/distcc-makefiles/Boot/Main.c on 172.17.0.2/1 failed
distcc[13039] (dcc_build_somewhere) Warning: remote compilation of '/home/user/sandbox/distcc-makefiles/Boot/Main.c' failed, retrying locally
distcc[13039] (dcc_mark_timefile) mark /home/user/.distcc/lock/backoff_tcp_172.17.0.2_3632_0
distcc[13039] Warning: failed to distribute /home/user/sandbox/distcc-makefiles/Boot/Main.c to 172.17.0.2/1, running locally instead

where, to my understanding, SECTION A finds the remote server, SECTION B opens a connection to the server, SECTION C send the command to run in the server (includes the compile options and the file to compile), SECTION D fetches the result, and SECTION E analizes the result and decides what to do next. As you might see, this is the error:

distcc[13039] (dcc_x_token_string) send string '@_out/Release/Boot/Main.o.via'
distcc[13039] (dcc_x_token_int) send ARGV00000002


问:
How do I get my flexbox footer to take up the entire space at the bottom?

There is a pixel or two of white space between the left, right, and bottom of the screen and my footer (see the red scribbles on the image above. How do I get the footer to take up all of this space?

Some things I've tried:

I created a margin-left: -10; margin-right:-10; - this worked but it messes with scrolling because the user can scroll sideways now, which I do not want.

I created a bottom
 which had height: 1; this worked for the bottom but there has to be a better way than sticking a
 here and it doesn't solve for the sideways white space.

Margins are not applied to the parent element of the footer.

footer {
  background-color: #445077;
  display: flex;
  align-items: center;
  padding: 20;
  color: white;
  font-size: 14;
}

.col {
  display: flex;
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="col">

      <div>Privacy policy</div>

  </div>
  <div class="col" style="justify-content: center;">
    <div class="footer_submit">Subscribe</div>
  </div>
  <div class="col" style="justify-content: flex-end;">
    <i class="fa fa-linkedin-square" style="font-size:24px;"></i
        >
  </div>
</footer></code>```

答:
Have you tried:

```<code>html,
body {
  margin: 0;
  padding: 0;
}
</code>```

You should upload the rest of your code, maybe something else is causing the problem.

Body:
There is a pixel or two of white space between the left, right, and bottom of the screen and my footer (see the red scribbles on the image above. How do I get the footer to take up all of this space?

Some things I've tried:

I created a margin-left: -10; margin-right:-10; - this worked but it messes with scrolling because the user can scroll sideways now, which I do not want.

I created a bottom
 which had height: 1; this worked for the bottom but there has to be a better way than sticking a
 here and it doesn't solve for the sideways white space.

Margins are not applied to the parent element of the footer.

footer {
  background-color: #445077;
  display: flex;
  align-items: center;
  padding: 20;
  color: white;
  font-size: 14;
}

.col {
  display: flex;
  flex: 1;
}

Privacy policy

Subscribe

Body:
Have you tried:

html,
body {
  margin: 0;
  padding: 0;
}

You should upload the rest of your code, maybe something else is causing the problem.


答:
Assuming you have these file names in an array. You could do something like this.

const arr = ["1. Some file name.txt", "2. Some file name.txt", "11. Some file name.pdf", "10. Some file name.txt", "1. Some file name.txt", "2. Some file name.txt", "2. Some file name.txt"];

const newArr = arr.map((item, index) => {
  const splited = item.split(".");
  splited.splice(0, 1); // remove the prefix
  return `${index + 1}. ${splited.join(".")}`;
});
console.log(newArr);```

Title: How to replace irregular string prefix using Javascript?


问:
How to join multiple rows sequentially in a numpy array?
I've a data like this,

```<code>data = [array(['a', 'b', 'c']),
        array([['d', 'e', 'f'], ['g', 'h', 'i']]),
        array([['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r']])]
</code>```

I want to join values in inner list sequentially. This is the desired output that I need.

```<code>[['a', 'b', 'c'], ['d g', 'e h', 'f i'], ['j m p', 'k n q', 'l o r']]
</code>```

I tried using using multiple loops and join but it's not giving me required output.

```<code>for i in data:
    for j in i:
        print(" ".join(j))
</code>```

I'm not really sure on how to achieve this? Need an efficient and faster approach because my original data is really large.

答:
Try:

res=list(map(lambda x: list(map(' '.join, zip(*x))) if isinstance(x[0], list) else x, data))
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>[['a', 'b', 'c'], ['d g', 'e h', 'f i'], ['j m p', 'k n q', 'l o r']]
</code>```

Body:
I've a data like this,

data = [array(['a', 'b', 'c']),
        array([['d', 'e', 'f'], ['g', 'h', 'i']]),
        array([['j', 'k', 'l'], ['m', 'n', 'o'], ['p', 'q', 'r']])]

I want to join values in inner list sequentially. This is the desired output that I need.

[['a', 'b', 'c'], ['d g', 'e h', 'f i'], ['j m p', 'k n q', 'l o r']]

I tried using using multiple loops and join but it's not giving me required output.

for i in data:
    for j in i:
        print(" ".join(j))

I'm not really sure on how to achieve this? Need an efficient and faster approach because my original data is really large.

Body:
Try:

res=list(map(lambda x: list(map(' '.join, zip(*x))) if isinstance(x[0], list) else x, data))

Outputs:

[['a', 'b', 'c'], ['d g', 'e h', 'f i'], ['j m p', 'k n q', 'l o r']]


问:
I have multiple HTML 5 <Audio> tags on one page and I want ALL of them to pause when another is played
I think I need a script that will "get" all the playing HTML5 audio controls and "pause" them apart from the one the user clicks play on. I have seen and can handle simple play, pause, stop with just one audio controls but my skills fall way short of coding something to do what I'm after with multiples. audio controls is a neat solution and integrates well with my current design, I just need help making it work properly. The use case:

https://aberaeronskies.com/ page loads and nothing plays which is desired, user clicks play on a audio controls tag and the track snippet plays which is desired. User clicks on another one (there are 14) and it starts to play, trouble is, the first one is still playing which is not desired; one could click on all of them and they would all play!

The requirement is for a script or a call or whatever (I'm no coder, just doing this as freebie for a mate) that when a user clicks play on any one of the 14 tracks it pauses all other playing tracks.

I thought this was it: Pause all other players besides activated one. jQuery audio plugin for <audio> element and Play selected audio while pausing/resetting others but I'cant make them work.

It may be that this cannot be done and I need to rethink the whole presentation of multiple tracks and if so, further advice on where to look (in addition to above) would also be useful.

Thanks very much...

答:
Ah...
This works</p>

```<code>var curPlaying;
window.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
    window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
$(function () {
$(".playback").click(function (e) {
    e.preventDefault();
    var song = $(this).next('audio')[0];
    if (song.paused) {
        if (curPlaying) {
            $("audio", "#" + curPlaying)[0].pause();
        }
        song.play();
        curPlaying = $(this).parent()[0].id;
    } else {
        song.pause();
        curPlaying = null;
    }
});
});
</code>```

Body:
Ah...
This works

var curPlaying;
window.addEventListener("play", function(evt)
{
if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
{
    window.$_currentlyPlaying.pause();
}
window.$_currentlyPlaying = evt.target;
}, true);
$(function () {
$(".playback").click(function (e) {
    e.preventDefault();
    var song = $(this).next('audio')[0];
    if (song.paused) {
        if (curPlaying) {
            $("audio", "#" + curPlaying)[0].pause();
        }
        song.play();
        curPlaying = $(this).parent()[0].id;
    } else {
        song.pause();
        curPlaying = null;
    }
});
});


问:
Sample specs for cancan
I've created a sets of specs for a controller that I have (Photo) that is a nested resource of a User.
The specs all pass but some of them fail when I introduce CanCan in the Photos contoller:

```<code>load_and_authorize_resource :user
load_and_authorize_resource :photo
</code>```

Here's a failing test case from one of my specs:

```<code>describe "get 'show'" do
   let(:photo) { Factory.stub(:photo) }
   it "searches for the users photo" do
      @user.photos.should_receive(:find).with(:photo.object_id);
      get :show, :user_id => @user.id, :id => :photo.object_id;
   end
   context "when the photo doesn't exist" do
      before do
         @user.photos.stub(:find).with(:photo.object_id).and_raise(ActiveRecord::RecordNotFound);
         get :show, :user_id => @user.id, :id => :photo.object_id;
      end
      it "assigns photo to nil" do
         assigns[:photo].should be_nil;
      end
      it "renders the '404' template" do
         response.status.should eql 404;
         response.should render_template("#{Rails.root.to_s}/public/404.html") end
      end
   end
   ...
 end
</code>```

I've set up the user at the top of the spec file:

```<code>login(:user)

before do
   @user = controller.current_user # this could be any user.
   User.stub!(:find).and_return(@user)
end
</code>```

and the show method in the Photos controller looks like this:

```<code>def show
  # @user = User.find(params[:user_id])
  # @photo = @user.photos.find(params[:id])
end
</code>```

Note that the action is blank because Cancan performs the finds required automatically. Before I introduced Cancan the two lines in the action weren't commented out.

In my test, when I test that the find method is called on a users photos for example, the test fails. Cancan must be using some other technique to find the users photos (other than @users.photos.find()). Would anyone know how to rewrite the above tests for a controller that users Cancan, i.e. to replace the find stubs with something that will work?

What I'm looking for ideally is some sample specs for a RESTful controller that uses Cancan. Even a spec for the show action would be useful.

Thanks for reading!

Eddie

ps - I'm using Rails 3.0.6, Cancan 1.6.4 and Devise 1.3.3

答: there is this answer: Rspec, CanCan and Devise, but i am not really sure I want to patch CanCan. I would much rather understand and spec out the mock in the right way. I know the key issue is that CanCan does not call Contact.new(params[:contact]). Instead it calls contact.attributes = params[:contact] later after it has applied some initial attributes based on the current ability permissions. How to work around that? That is what I'm working now.</p>

Title: Sample specs for cancan

Body:
I've created a sets of specs for a controller that I have (Photo) that is a nested resource of a User.
The specs all pass but some of them fail when I introduce CanCan in the Photos contoller:

load_and_authorize_resource :user
load_and_authorize_resource :photo

Here's a failing test case from one of my specs:

describe "get 'show'" do
   let(:photo) { Factory.stub(:photo) }
   it "searches for the users photo" do
      @user.photos.should_receive(:find).with(:photo.object_id);
      get :show, :user_id => @user.id, :id => :photo.object_id;
   end
   context "when the photo doesn't exist" do
      before do
         @user.photos.stub(:find).with(:photo.object_id).and_raise(ActiveRecord::RecordNotFound);
         get :show, :user_id => @user.id, :id => :photo.object_id;
      end
      it "assigns photo to nil" do
         assigns[:photo].should be_nil;
      end
      it "renders the '404' template" do
         response.status.should eql 404;
         response.should render_template("#{Rails.root.to_s}/public/404.html") end
      end
   end
   ...
 end

I've set up the user at the top of the spec file:

login(:user)

before do
   @user = controller.current_user # this could be any user.
   User.stub!(:find).and_return(@user)
end

and the show method in the Photos controller looks like this:

def show
  # @user = User.find(params[:user_id])
  # @photo = @user.photos.find(params[:id])
end

Note that the action is blank because Cancan performs the finds required automatically. Before I introduced Cancan the two lines in the action weren't commented out.

In my test, when I test that the find method is called on a users photos for example, the test fails. Cancan must be using some other technique to find the users photos (other than @users.photos.find()). Would anyone know how to rewrite the above tests for a controller that users Cancan, i.e. to replace the find stubs with something that will work?

What I'm looking for ideally is some sample specs for a RESTful controller that uses Cancan. Even a spec for the show action would be useful.

Thanks for reading!

Eddie

ps - I'm using Rails 3.0.6, Cancan 1.6.4 and Devise 1.3.3


问:
Count and sum condition greater than something
I have a table.

I want count for those users whose summation of coin is more than 2000. For summation I will take only those rows where transaction_type is debited.

my query is something ===>

```<code>SELECT COUNT(*)  FROM user_coins_log
GROUP BY user_id
HAVING SUM(if(transaction_type = 'Debited',coin,0))>20000
</code>```

But instead of getting one count I am getting lots of rows of count. How to solve this problem.

答:
Use two levels of aggregation:</p>

```<code>SELECT COUNT(*)
FROM (SELECT user_id, SUM(coin) as sum_debits
      FROM user_coins_log
      WHERE transaction_type = 'Debited'
      GROUP BY user_id
      HAVING sum_debits >20000
     ) u;
</code>```

Body:
I have a table.

I want count for those users whose summation of coin is more than 2000. For summation I will take only those rows where transaction_type is debited.

my query is something ===>

SELECT COUNT(*)  FROM user_coins_log
GROUP BY user_id
HAVING SUM(if(transaction_type = 'Debited',coin,0))>20000

But instead of getting one count I am getting lots of rows of count. How to solve this problem.

Body:
Use two levels of aggregation:

SELECT COUNT(*)
FROM (SELECT user_id, SUM(coin) as sum_debits
      FROM user_coins_log
      WHERE transaction_type = 'Debited'
      GROUP BY user_id
      HAVING sum_debits >20000
     ) u;


答:
Do the query to find all indebted users as a subquery, then count.

Doing the filtering by transaction type in a where clause is a bit simpler.

```<code>select count(user_id) from (
  select user_id
  from user_coins_log
  where transaction_type = 'Debited'
  group by user_id
  having sum(coin) > 2000
) indebted
</code>```

Try it.

Title: Count and sum condition greater than something

Body:
Do the query to find all indebted users as a subquery, then count.

Doing the filtering by transaction type in a where clause is a bit simpler.

select count(user_id) from (
  select user_id
  from user_coins_log
  where transaction_type = 'Debited'
  group by user_id
  having sum(coin) > 2000
) indebted

Try it.


问:
Need help determining how to approach building my project
I'd like to create something similar to a family tree online app (like geni.com). I'm unsure what languages I should use to build it with. My IT strong points aren't in programming and this project is going to require me to sit down and learn some languages. My problem right now is that I don't know what languages I should use.

So with the idea of a family tree online app in mind here are some of the specifications.
- I do not want to use flash.
- The app needs to be zoomable and scrollable (sort of like google maps)
- The app needs to be able to add content without reloading the page. Perhaps there's a little "+" sign and when I click it, I can add a tag/title/description/picture
- The app needs to be able to save your work for that user to retrieve later on.
- The layout that a user is able to create in is sort of widget based where the user can add a new bubble and then in that bubble they are able to add text or content.

I started programming this with HTML5 canvas and Javascript, but I'm stuck on creating a connection to the database that isn't directly from Javascript (because that seems very insecure to me). But I'm not just stumped on how to interact securely with the database (I don't even have a database picked out), but also I'm concerned that I won't be able to build out the app with just javascript and may need something else like ajax or something but I'm unfamiliar with what each language does nowadays.

答: You will need server side scripts in a language like PHP or Ruby on Rails to interact with a database.</p>


问:
How to split a string into fixed length rows?
I have a code that asks user to give lines with different amount of words in them, the next line is always given on another row.
I want to split the given text into user inputted lenght in different rows.

Right now I have a piece of code that splits the lines to wanted user inputted length, but since it counts the space (" ") as one "word",some lines start with space. How do i stop that from happening?

```<code>def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

def main():

    print("Enter text rows. Quit by entering an empty row.")
    msg = read_message()
    lines = (i.strip() for i in msg.splitlines())
    get_line = int(input("Enter the number of characters per line: "))
    for line in lines:
        for chunk in chunkstring(line, get_line):
            print(chunk)
``
</code>```

答:
You can use Python strip to eliminate the remaining spaces, check this article or this other one

So just print chunk.strip()

I hope it helps.

Body:
I have a code that asks user to give lines with different amount of words in them, the next line is always given on another row.
I want to split the given text into user inputted lenght in different rows.

Right now I have a piece of code that splits the lines to wanted user inputted length, but since it counts the space (" ") as one "word",some lines start with space. How do i stop that from happening?

def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

def main():

    print("Enter text rows. Quit by entering an empty row.")
    msg = read_message()
    lines = (i.strip() for i in msg.splitlines())
    get_line = int(input("Enter the number of characters per line: "))
    for line in lines:
        for chunk in chunkstring(line, get_line):
            print(chunk)
``


问:
Android Jetpack navigation: One activity with several navigation views
I am considering the new android jetpack navigation best practices where there should only be one activity in each application. I want to use one activity to implement the following menus in fragments, but I'm very insecure about what the best practices are when implementing several menus in the same application.

BottomNavigationView (Reference repo):

<LinearLayout 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:orientation="vertical"
    tools:context="com.example.android.navigationadvancedsample.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:menu="@menu/bottom_nav"/>
</LinearLayout>
```

<p>Screenshot:<br>
<img src="https://i.stack.imgur.com/YZz3Bl.png" alt="BttomNavigationView"></p>

<p><strong>DrawerLayout (Reference repo):</strong></p>

<pre class="lang-xml prettyprint-override"><code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <com.google.android.material.appbar.AppBarLayout
                android:id="@+id/appbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/AppTheme.AppBarOverlay">

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:popupTheme="@style/AppTheme.PopupOverlay"/>

            </com.google.android.material.appbar.AppBarLayout>

            <fragment
                android:id="@+id/garden_nav_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="true"
                app:navGraph="@navigation/nav_garden"/>

        </LinearLayout>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navigation_view"
            style="@style/Widget.MaterialComponents.NavigationView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/menu_navigation"/>

    </androidx.drawerlayout.widget.DrawerLayout>

</layout>
</code>```

Screenshot:

Considering these examples from google there are no clear answers as of how to implement both views in one activity using best practices, because each example only uses one form of navigation view for their app, respectively DrawerLayout, or BottomNavigationView.

The questions are:
1. What are the best practices for making activity with different navigation views for different fragments? For example, several fragments using DrawerLayout, and other fragments using BottomNavigationView.
2. What if one wants to hide both the DrawerLayout and the BottomNavigationView when viewing authentication views and logging in, and display them when authenticated?

答:
With Jetpack Navigation, you can add a Navigation Host and a Navigation Drawer connected with a main nav graph in the main Activity, and another Navigation Host with a Bottom Navigation connected to a second nav graph inside the default starting fragment.
I found this tutorial https://proandroiddev.com/android-jetpack-navigationui-a7c9f17c510e and its example project https://github.com/sagar-viradiya/NavigationUIDemo</p>

Body:
I am considering the new android jetpack navigation best practices where there should only be one activity in each application. I want to use one activity to implement the following menus in fragments, but I'm very insecure about what the best practices are when implementing several menus in the same application.

BottomNavigationView (Reference repo):

<LinearLayout 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:orientation="vertical"
    tools:context="com.example.android.navigationadvancedsample.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_nav"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:menu="@menu/bottom_nav"/>
</LinearLayout>

Screenshot:

DrawerLayout (Reference repo):

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <com.google.android.material.appbar.AppBarLayout
                android:id="@+id/appbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/AppTheme.AppBarOverlay">

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:popupTheme="@style/AppTheme.PopupOverlay"/>

            </com.google.android.material.appbar.AppBarLayout>

            <fragment
                android:id="@+id/garden_nav_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="true"
                app:navGraph="@navigation/nav_garden"/>

        </LinearLayout>

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navigation_view"
            style="@style/Widget.MaterialComponents.NavigationView"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header"
            app:menu="@menu/menu_navigation"/>

    </androidx.drawerlayout.widget.DrawerLayout>

</layout>

Screenshot:

Considering these examples from google there are no clear answers as of how to implement both views in one activity using best practices, because each example only uses one form of navigation view for their app, respectively DrawerLayout, or BottomNavigationView.

The questions are:
1. What are the best practices for making activity with different navigation views for different fragments? For example, several fragments using DrawerLayout, and other fragments using BottomNavigationView.
2. What if one wants to hide both the DrawerLayout and the BottomNavigationView when viewing authentication views and logging in, and display them when authenticated?


问:
RoboCopy.exe switches not working in Powershell script
I'm going to try to make this question very simple. If I run the following, it works without issue:

```<code>$localData = "C:\"
$netData = "\\OtherPC\shared\"
Start-Process "RoboCopy.exe" -argumentlist " `"$localData`" `"$netData`" "
</code>```

However, as soon as I add any switches (see below), it does not work. No errors to be seen.

```<code>$localData = "C:\"
$netData = "\\OtherPC\shared\"
Start-Process "RoboCopy.exe" -argumentlist " `"$localData`" `"$netData`" /copyall"
</code>```

It's been a real pain to try and fix, any help is appreciated.

EDIT:
Fixed, and here is the final working syntax:

```<code>$localFiles = "C:\Users\"
$netFiles = "\\netLocation\migration\Users\"

Start-Process "RoboCopy.exe" -NoNewWindow -argumentlist " `"$localFiles\`" `"$netFiles\`" /s /r:1 /w:5 /mt:16"
</code>```

答:
As an aside: Your use of Start-Process may be intentional to run a lengthy operation asynchronously, in a new window, but the more typical case is to execute console applications such as Robocopy.exe synchronously, in the same window, in which case you need to call them directly (c:\path\to\some.exe ... or & $exePath ...) - see this answer. An alternative to asynchronous execution in a new window is to use a background job.

You have to double a trailing \ in your path arguments if they (end up) enclosed in "..." in the command line (ultimately) submitted:

Simply define your variable values with a trailing \\, which should make your command work:

```<code>$localData = 'C:\\'
$netData = '\\OtherPC\shared\\'
</code>```

Another solution (on Windows) for file paths specifically is to insert a space between the trailing \ and the ". This works, because the file-system WinAPI calls ignore trailing spaces in paths.

The reason that \\ is needed at the end is that RoboCopy.exe (and, indeed, virtually all external programs) interpret sequence \" as an escaped " character rather to be used verbatim rather than having syntactic function.

If you need to append the extra \ programmatically, use the following:

```<code>$localDataEscaped = $localData -replace '\\$', '\\'
$netDataEscaped = $netData -replace '\\$', '\\'
</code>```

Debugging tip for Start-Process calls:

(Temporarily) add -NoNewWindow -Wait to the call, which makes the command output appear in the same window, giving you a chance to inspect it; by default, Start-Process runs the command in a new window (on Windows) that automatically closes when the command finishes, potentially not giving you enough time to see the output.

Body:
I'm going to try to make this question very simple. If I run the following, it works without issue:

$localData = "C:\"
$netData = "\\OtherPC\shared\"
Start-Process "RoboCopy.exe" -argumentlist " `"$localData`" `"$netData`" "

However, as soon as I add any switches (see below), it does not work. No errors to be seen.

$localData = "C:\"
$netData = "\\OtherPC\shared\"
Start-Process "RoboCopy.exe" -argumentlist " `"$localData`" `"$netData`" /copyall"

It's been a real pain to try and fix, any help is appreciated.

EDIT:
Fixed, and here is the final working syntax:

$localFiles = "C:\Users\"
$netFiles = "\\netLocation\migration\Users\"

Start-Process "RoboCopy.exe" -NoNewWindow -argumentlist " `"$localFiles\`" `"$netFiles\`" /s /r:1 /w:5 /mt:16"

Body:
As an aside: Your use of Start-Process may be intentional to run a lengthy operation asynchronously, in a new window, but the more typical case is to execute console applications such as Robocopy.exe synchronously, in the same window, in which case you need to call them directly (c:\path\to\some.exe ... or & $exePath ...) - see this answer. An alternative to asynchronous execution in a new window is to use a background job.

You have to double a trailing \ in your path arguments if they (end up) enclosed in "..." in the command line (ultimately) submitted:

Simply define your variable values with a trailing \\, which should make your command work:

$localData = 'C:\\'
$netData = '\\OtherPC\shared\\'

Another solution (on Windows) for file paths specifically is to insert a space between the trailing \ and the ". This works, because the file-system WinAPI calls ignore trailing spaces in paths.

The reason that \\ is needed at the end is that RoboCopy.exe (and, indeed, virtually all external programs) interpret sequence \" as an escaped " character rather to be used verbatim rather than having syntactic function.

If you need to append the extra \ programmatically, use the following:

$localDataEscaped = $localData -replace '\\$', '\\'
$netDataEscaped = $netData -replace '\\$', '\\'

Debugging tip for Start-Process calls:

(Temporarily) add -NoNewWindow -Wait to the call, which makes the command output appear in the same window, giving you a chance to inspect it; by default, Start-Process runs the command in a new window (on Windows) that automatically closes when the command finishes, potentially not giving you enough time to see the output.


问:
Android Studio Git Push Rejected
I'm trying to uploading my Android Project on github but I get this error when I try to push:

```<code>Push rejected: Push to origin/master was rejected
</code>```

I made this steps:

VCS->Import into version control->Create new repository...

From the git bash in Project folder:

git remote add origin https://github.com/[username]/[project_name].git

Git->Add

Git-> Commit directory

Git-> Push

答:
For Android Studio if your "Push" is rejected, go ahead and try this:

Try to Pull.(Origin/Master).Right after that:

VCS-->Git-->Branches..-->Remote Branches(origin/master)-->Rebase Current onto Selected

This will eradicate all your contradicting configurations.

Title: Android Studio Git Push Rejected

Body:
I'm trying to uploading my Android Project on github but I get this error when I try to push:

Push rejected: Push to origin/master was rejected

I made this steps:

VCS->Import into version control->Create new repository...

From the git bash in Project folder:

git remote add origin https://github.com/[username]/[project_name].git

Git->Add

Git-> Commit directory

Git-> Push


问:
I want to deploy back-end and front-end seperate apps on the same server with nginx
I've created a restful api with nodejs and I'm planning to use sapper/svelte for front-end. In the end, these will be seperate apps and I want to run them on the same server with same domain. Is this approach reasonable? If it is, what should my nginx configuration file look like? If not, what should be my approach? </p>

<p>This my conf for api: </p>

```<code>server {
    server_name domain.name;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
   .
   .
   .
}
</code>```

答:
Since this is your first svelte / sapper project, I would keep things separate and see if you can get started with svelte to hit the API on nginx. Decouple things and ship svelte on gitlab pages or whatever other CI destination you prefer.

If it comes time to run with sapper, my advice remains the same - have it hit your API externally to keep your projects clear and distinct. You already launched the API before the front end - no worries, but I don’t see how your config needs to know where the front end will run or why entwining them would be beneficial.

Body:
I've created a restful api with nodejs and I'm planning to use sapper/svelte for front-end. In the end, these will be seperate apps and I want to run them on the same server with same domain. Is this approach reasonable? If it is, what should my nginx configuration file look like? If not, what should be my approach?

This my conf for api:

server {
    server_name domain.name;

    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
   .
   .
   .
}


问:
correct way to parse a list of params in a url
What is the correct way to pass a lit of values via url parameters.

For instance I am trying to pass something like this

```<code>/sports?country=USA&play=['nba','nfl']
</code>```

In my aws lambda which is in node.js when i do the following
var playList = event.queryStringParameters.play I get back ['nba','nfl'] but it is a string and not a list

Then I tried the following

```<code>/sports?country=USA&play=nba,nfl
</code>```

In my aws lambda I did event.queryStringParameters.play.split(',') and i got a list [nba,nfl] but this is a issue when there is only 1 item passed like /sports?country=USA&play=nba because then i cannot split on ,

Hence i am wondering what is the correct way to pass a list as i feel there maybe a better way.

答:
I don't see anything wrong with using /sports?country=USA&play=nba,nfl and then doing split to get the values. It can handler multiple or single values just fine

console.log("nba,nfl".split(',')); // will result in [nba,nfl]```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log("nba".split(',')); // will result in [nba]</code>```

Body:
What is the correct way to pass a lit of values via url parameters.

For instance I am trying to pass something like this

/sports?country=USA&play=['nba','nfl']

In my aws lambda which is in node.js when i do the following
var playList = event.queryStringParameters.play I get back ['nba','nfl'] but it is a string and not a list

Then I tried the following

/sports?country=USA&play=nba,nfl

In my aws lambda I did event.queryStringParameters.play.split(',') and i got a list [nba,nfl] but this is a issue when there is only 1 item passed like /sports?country=USA&play=nba because then i cannot split on ,

Hence i am wondering what is the correct way to pass a list as i feel there maybe a better way.

Body:
I don't see anything wrong with using /sports?country=USA&play=nba,nfl and then doing split to get the values. It can handler multiple or single values just fine

console.log("nba,nfl".split(',')); // will result in [nba,nfl]

console.log("nba".split(',')); // will result in [nba]


问:
Using an object inside of a class and using the other class' object's methods isn't working
I'm trying to make a clock object by simply making an object called "boundedCounter" which has a value and a limit, the value starts at 0 and keep counting up until it reaches the limit, then it resets to 0 and continues counting. I want to have the clock object use 3 bounded counters for each seconds, minutes and hours and the rest is simple. When I did it in java, it worked pretty good. But now after learning C++, I can't seem to find why making the boundedCounter object inside of the clock class isn't working. I tried making it an inherited class, making methods and such. Here's the code:

```<code>class boundedCounter {
private:
    int value, limit;

public:

    boundedCounter(int boundLimit) {
        value = 0;
        limit = boundLimit;
    }

    void next() {
        if (++value == limit) {
            value = 0;
        }
    }

    void setLimit(int boundLimit) {
        limit = boundLimit;
    }

    int getValue() {
        return value;
    }
};

class Clock : private boundedCounter {
public:
    boundedCounter seconds(60);
    boundedCounter minutes(60);
    boundedCounter hours(24);

    seconds.setLimit(60);
};
</code>```

Errors:

```<code>E0079 expected a type specifier line 35
E0079 expected a type specifier line 36
E0079 expected a type specifier line 37
E0077 this declaration has no storage class or type specifier line 39
E0065 expected a ';'

</code>```

答:
The compiler expected in this case you declare the boundedCounter objects in class Clock following the syntax below:

```<code>boundedCounter seconds = 60;
boundedCounter minutes =60;
boundedCounter hours = 24;
</code>```

The line 'seconds.setLimit(60)' won't work because it is an attempt to execution of seconds' function member on class declaration.

Furthermore, when you declare 'class Clock : private boundedCounter', you create a extended bounderCounter called Clock with the private function members next, setLimit and getValue. I'm sure it is not what you want from the class Clock to be.

Below you can check your code:

```<code>class boundedCounter {
private:
    int value = 0;
    int limit;

public:
    boundedCounter(int boundLimit) : limit(boundLimit) {}

    void next() {
        if (++value == limit)
            value = 0;
    }
    void setLimit(int boundLimit) { limit = boundLimit; }
    int getValue() { return value; }
};

struct Clock {
    boundedCounter seconds = 60;
    boundedCounter minutes = 60;
    boundedCounter hours = 24;
};
</code>```

Body:
I'm trying to make a clock object by simply making an object called "boundedCounter" which has a value and a limit, the value starts at 0 and keep counting up until it reaches the limit, then it resets to 0 and continues counting. I want to have the clock object use 3 bounded counters for each seconds, minutes and hours and the rest is simple. When I did it in java, it worked pretty good. But now after learning C++, I can't seem to find why making the boundedCounter object inside of the clock class isn't working. I tried making it an inherited class, making methods and such. Here's the code:

class boundedCounter {
private:
    int value, limit;

public:

    boundedCounter(int boundLimit) {
        value = 0;
        limit = boundLimit;
    }

    void next() {
        if (++value == limit) {
            value = 0;
        }
    }

    void setLimit(int boundLimit) {
        limit = boundLimit;
    }

    int getValue() {
        return value;
    }
};

class Clock : private boundedCounter {
public:
    boundedCounter seconds(60);
    boundedCounter minutes(60);
    boundedCounter hours(24);

    seconds.setLimit(60);
};

Errors:

E0079 expected a type specifier line 35
E0079 expected a type specifier line 36
E0079 expected a type specifier line 37
E0077 this declaration has no storage class or type specifier line 39
E0065 expected a ';'

Body:
The compiler expected in this case you declare the boundedCounter objects in class Clock following the syntax below:

boundedCounter seconds = 60;
boundedCounter minutes =60;
boundedCounter hours = 24;

The line 'seconds.setLimit(60)' won't work because it is an attempt to execution of seconds' function member on class declaration.

Furthermore, when you declare 'class Clock : private boundedCounter', you create a extended bounderCounter called Clock with the private function members next, setLimit and getValue. I'm sure it is not what you want from the class Clock to be.

Below you can check your code:

class boundedCounter {
private:
    int value = 0;
    int limit;

public:
    boundedCounter(int boundLimit) : limit(boundLimit) {}

    void next() {
        if (++value == limit)
            value = 0;
    }
    void setLimit(int boundLimit) { limit = boundLimit; }
    int getValue() { return value; }
};

struct Clock {
    boundedCounter seconds = 60;
    boundedCounter minutes = 60;
    boundedCounter hours = 24;
};


问:
Hiding a Div till clicked, and not hiding again once clicked again
So, once the button is clicked it reveals the information.

Which is great and what I need to be done, but say the user inputs some other information and wants to get a different set of information, it'll re-hide the info.

Hopefully that is enough context.

Basically I don't want the Jquery to run a second time. Just for the one click and not another..

Jquery:

```<code>$("#userSubmit").click(function() {
    $("#hidden").toggle();
});
</code>```

CSS:

```<code>#hidden {
  display: none;
}
</code>```

答:
Used:

```<code>    $("#userSubmit").one("click", function() {
    $("#hidden").toggle();
});
</code>```

Accomplished what I was trying to get done.

Body:
So, once the button is clicked it reveals the information.

Which is great and what I need to be done, but say the user inputs some other information and wants to get a different set of information, it'll re-hide the info.

Hopefully that is enough context.

Basically I don't want the Jquery to run a second time. Just for the one click and not another..

Jquery:

$("#userSubmit").click(function() {
    $("#hidden").toggle();
});

CSS:

#hidden {
  display: none;
}

Body:
Used:

    $("#userSubmit").one("click", function() {
    $("#hidden").toggle();
});

Accomplished what I was trying to get done.