问:
How can i restrict the request from the unauthorized users (url's)?
Here my problem is that in my spring project totally 3 Jsp pages are available.

home page

register page

register success full page

When i type url for the home page in a browser, i am getting home page.and inside one hyperlink is available to register data. automatically when i click on that link it will go to the register page.then after it will go to the register success full page.

So finally my problem is that when i gave home page url in browser, homepage comes and also if i give register page url it will go to the register page with out touches the home page. but actually i want to access the register page through home page.

答:
You can simply create an authentication filter and specify on which methods you need to call this filter, for example, you want only an authorised user to access the downloadDoc api. Here is the sample code for this:</p>

```<code>@WebFilter(urlPatterns = { "/getDocs", "/downloadDoc", "/updateStatus", "/submitApplication", "/login", "/logout",
    /*"/requestDocuments", "/sendEmailRequest"*/"/getAllApplication", "/getApplicationDetails",
    "/getAccountDetails" })

public class AuthenticationFilter implements Filter {

    private static Logger logger = Logger.getLogger(AuthenticationFilter.class);

    @Autowired
    private UserVerificationService userVerificationService;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        logger.info("checking token in filter");
        HttpServletRequest request = (HttpServletRequest) arg0;
        if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
            DocVerificationRequestWrapper myRequestWrapper = new DocVerificationRequestWrapper(request);
            String body = myRequestWrapper.getBody();
            String serviceName = request.getServletPath();
            logger.info("serviceName = " + serviceName);
            Token token = null;
            try {
                JSONObject jsonObj = new JSONObject(body);
                logger.info(jsonObj);
                if (jsonObj != null) {
                    JSONObject tokenObj = (JSONObject) jsonObj.get("token");
                    Gson gson = new Gson();
                    token = gson.fromJson(tokenObj.toString(), Token.class);

                    String clientName = request.getHeader("clientName");
                    logger.info("clientName = " + clientName);
                    if (null != token) {
                        if (userVerificationService == null) {
                            ServletContext servletContext = request.getServletContext();
                            WebApplicationContext webApplicationContext = WebApplicationContextUtils
                                    .getWebApplicationContext(servletContext);
                            userVerificationService = webApplicationContext.getBean(UserVerificationService.class);
                        }
                        ClientResponse cr = userVerificationService.verifyUser(token, clientName, serviceName);
                        String verStatus = cr != null ? cr.getStatus() : null;
                        logger.info("verStatus = " + verStatus);
                        if (verStatus != null && verStatus.equalsIgnoreCase("success")) {
                            chain.doFilter(myRequestWrapper, response);
                        } else {
                            logger.error("Invalid token");
                            cr.setStatus("failure");
                            cr.setMessage("Invalid Token");
                            cr.setErrorCode("157");
                            cr.setToken(token);
                            response.getOutputStream().write(new ObjectMapper().writeValueAsBytes(cr));

                            // ((HttpServletResponse) response).sendError(157, "Invalid Token");
                        }
                    } else {
                        logger.error("token missing.");
                        ClientResponse cr = new ClientResponse();
                        cr.setStatus("failure");
                        cr.setMessage("Missing Token");
                        cr.setErrorCode("158");
                        response.getOutputStream().write(new ObjectMapper().writeValueAsBytes(cr));
                        // ((HttpServletResponse) response).sendError(158, "Token Missing");
                    }
                }
            } catch (JSONException e) {
                logger.error("exception in authetication filter " + e);
            }
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
</code>```

Body:
You can simply create an authentication filter and specify on which methods you need to call this filter, for example, you want only an authorised user to access the downloadDoc api. Here is the sample code for this:

@WebFilter(urlPatterns = { "/getDocs", "/downloadDoc", "/updateStatus", "/submitApplication", "/login", "/logout",
    /*"/requestDocuments", "/sendEmailRequest"*/"/getAllApplication", "/getApplicationDetails",
    "/getAccountDetails" })

public class AuthenticationFilter implements Filter {

    private static Logger logger = Logger.getLogger(AuthenticationFilter.class);

    @Autowired
    private UserVerificationService userVerificationService;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        logger.info("checking token in filter");
        HttpServletRequest request = (HttpServletRequest) arg0;
        if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
            DocVerificationRequestWrapper myRequestWrapper = new DocVerificationRequestWrapper(request);
            String body = myRequestWrapper.getBody();
            String serviceName = request.getServletPath();
            logger.info("serviceName = " + serviceName);
            Token token = null;
            try {
                JSONObject jsonObj = new JSONObject(body);
                logger.info(jsonObj);
                if (jsonObj != null) {
                    JSONObject tokenObj = (JSONObject) jsonObj.get("token");
                    Gson gson = new Gson();
                    token = gson.fromJson(tokenObj.toString(), Token.class);

                    String clientName = request.getHeader("clientName");
                    logger.info("clientName = " + clientName);
                    if (null != token) {
                        if (userVerificationService == null) {
                            ServletContext servletContext = request.getServletContext();
                            WebApplicationContext webApplicationContext = WebApplicationContextUtils
                                    .getWebApplicationContext(servletContext);
                            userVerificationService = webApplicationContext.getBean(UserVerificationService.class);
                        }
                        ClientResponse cr = userVerificationService.verifyUser(token, clientName, serviceName);
                        String verStatus = cr != null ? cr.getStatus() : null;
                        logger.info("verStatus = " + verStatus);
                        if (verStatus != null && verStatus.equalsIgnoreCase("success")) {
                            chain.doFilter(myRequestWrapper, response);
                        } else {
                            logger.error("Invalid token");
                            cr.setStatus("failure");
                            cr.setMessage("Invalid Token");
                            cr.setErrorCode("157");
                            cr.setToken(token);
                            response.getOutputStream().write(new ObjectMapper().writeValueAsBytes(cr));

                            // ((HttpServletResponse) response).sendError(157, "Invalid Token");
                        }
                    } else {
                        logger.error("token missing.");
                        ClientResponse cr = new ClientResponse();
                        cr.setStatus("failure");
                        cr.setMessage("Missing Token");
                        cr.setErrorCode("158");
                        response.getOutputStream().write(new ObjectMapper().writeValueAsBytes(cr));
                        // ((HttpServletResponse) response).sendError(158, "Token Missing");
                    }
                }
            } catch (JSONException e) {
                logger.error("exception in authetication filter " + e);
            }
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}


来源: stackexchange

问:
Python get unique list items
I have a list of dictionaries with millions items, i want to extract only unique items that doesn't have same key name from the list , is there a faster way using threads or something to check in parallel instead sequential, my code as below

Note: my list is list of dictionaries, each dictionary has different keys but they may have the same value of key ['name'], if this matched I should only take one

for example:
lst = [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foo': 3, 'bar': 5}, {'name':x','bar': 33, 'foo': 10}]
 here there are two dictionaries have same name equal x so i will only save one in new list
new_lst  =  [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foo': 3, 'bar': 5}]

```<code>new_lst  = []
for x in lst:
     flag = False
     for n in new_lst:
          if x['name'] == n['name']:
                  flag = True
                  break
     if not flag:
        new_lst.append(x)
</code>```

答:
Reproducible example:

So I build a reprocible example for a large dict to compute a good benchmark:

```<code>import string
import random
lst = []
for i in range(10000):
    lst.append({'name':random.choice(string.letters)+random.choice(string.letters),
                'foo':random.choice(range(100)),
                'bar':random.choice(range(100))})
</code>```

Your way of doing it:

Then I compile your way in a function:

```<code>def your_fun(lst):
    new_lst  = []
    for x in lst:
         flag = False
         for n in new_lst:
              if x['name'] == n['name']:
                      flag = True
                      break
         if not flag:
            new_lst.append(x)
    return(new_lst)
</code>```

A faster way:

A faster way it to limitate the number of loops (loops are slows) by storing names you have already seen in a list.

```<code>def my_fun(lst):
    new_lst  = []
    seens_names = []
    for x in lst:
         if not x['name'] in seens_names:
            new_lst.append(x)
            seens_names.append(x['name'])
    return(new_lst)
</code>```

Benchmarks:

And I perform benchmarks:

```<code>%timeit your_fun(lst)
1 loop, best of 3: 1.14 s per loop

%timeit my_fun(lst)
10 loops, best of 3: 143 ms per loop
</code>```

So just by supressing one loop, it is possible to divide time cost by 10...

Conclusion:

Before considering multithreading, avoid as much as possible loops it will make your code faster.

There might be some other way to keep improving performance.

Another improvement before looking into multithreading would be to code this task in cython.

ContentLicense: CC BY-SA 3.0

Title: Python get unique list items

Body:
I have a list of dictionaries with millions items, i want to extract only unique items that doesn't have same key name from the list , is there a faster way using threads or something to check in parallel instead sequential, my code as below

Note: my list is list of dictionaries, each dictionary has different keys but they may have the same value of key ['name'], if this matched I should only take one

for example:
lst = [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foo': 3, 'bar': 5}, {'name':x','bar': 33, 'foo': 10}]
 here there are two dictionaries have same name equal x so i will only save one in new list
new_lst  =  [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foo': 3, 'bar': 5}]

new_lst  = []
for x in lst:
     flag = False
     for n in new_lst:
          if x['name'] == n['name']:
                  flag = True
                  break
     if not flag:
        new_lst.append(x)

Body:
Reproducible example:

So I build a reprocible example for a large dict to compute a good benchmark:

import string
import random
lst = []
for i in range(10000):
    lst.append({'name':random.choice(string.letters)+random.choice(string.letters),
                'foo':random.choice(range(100)),
                'bar':random.choice(range(100))})

Your way of doing it:

Then I compile your way in a function:

def your_fun(lst):
    new_lst  = []
    for x in lst:
         flag = False
         for n in new_lst:
              if x['name'] == n['name']:
                      flag = True
                      break
         if not flag:
            new_lst.append(x)
    return(new_lst)

A faster way:

A faster way it to limitate the number of loops (loops are slows) by storing names you have already seen in a list.

def my_fun(lst):
    new_lst  = []
    seens_names = []
    for x in lst:
         if not x['name'] in seens_names:
            new_lst.append(x)
            seens_names.append(x['name'])
    return(new_lst)

Benchmarks:

And I perform benchmarks:

%timeit your_fun(lst)
1 loop, best of 3: 1.14 s per loop

%timeit my_fun(lst)
10 loops, best of 3: 143 ms per loop

So just by supressing one loop, it is possible to divide time cost by 10...

Conclusion:

Before considering multithreading, avoid as much as possible loops it will make your code faster.

There might be some other way to keep improving performance.

Another improvement before looking into multithreading would be to code this task in cython.


问:
Vuex how to pass state/getter in data prop
I retrieved my data from database using axios under my vuex

```<code>const state = {
    giveaways: null
}

const actions = {
    getGiveAways : ({commit}) =>{

        axios({
            url : '/prod/api/thresholds_settings',
            method: 'post',
            data : {
            },
            config: 'JOSN'
        })
        .then(response=>{
            if(response.status == 200){
                //console.log(response.data.total_giveaways);
                commit('SET_GIVEAWAYS', response.data.total_giveaways)
            }
        })
        .catch(error=>{
            if(error.response){
                console.log('something happened')
            }
        });
    }
}

const mutations = {
    SET_GIVEAWAYS : (state, obj)=>{
        state.giveaways = obj
    }

}

const getters = {
    doneGiveAways(state){
        return state.giveaways
    }
}
</code>```

In my Dashboard.vue I have

```<code>import {mapState,mapGetters} from 'vuex'
export default{
    data: () => ({
        cards: [],
        giveaways: ''
    }),
    computed:{
        ...mapState({
            Giveaway: state => state.Threshold.giveaways
        }),
        doneGiveAways(){
            return this.$store.getters.doneGiveAways
        }
    },
    ready(){
        //giveaways: this.Giveaways
        //console.log(this.Giveaways);
    },
    created(){
        const self = this
        this.cards[0].result_val = 2
        this.cards[2].result_val = 2;

    },
    mounted(){
        this.$store.dispatch('getGiveAways');
        console.log(this.giveaways);

    }
}
</code>```

My problem is I need to pass the value from the mapState Giveaway to my returning data giveaways: '' so when page fires I can get the response value using this.giveaways. If I just call {{ Giveaway }} in my html it shows the value. But I need to make something like this.giveaways = this.$store.state.Thresholds.giveaways

答:
Just delete the giveaways property from your data Object and rename the computed doneGiveAways to giveaways and you are done.

There is no need for a local component giveaway data property in this scenario.

Body:
I retrieved my data from database using axios under my vuex

const state = {
    giveaways: null
}

const actions = {
    getGiveAways : ({commit}) =>{

        axios({
            url : '/prod/api/thresholds_settings',
            method: 'post',
            data : {
            },
            config: 'JOSN'
        })
        .then(response=>{
            if(response.status == 200){
                //console.log(response.data.total_giveaways);
                commit('SET_GIVEAWAYS', response.data.total_giveaways)
            }
        })
        .catch(error=>{
            if(error.response){
                console.log('something happened')
            }
        });
    }
}

const mutations = {
    SET_GIVEAWAYS : (state, obj)=>{
        state.giveaways = obj
    }

}

const getters = {
    doneGiveAways(state){
        return state.giveaways
    }
}

In my Dashboard.vue I have

import {mapState,mapGetters} from 'vuex'
export default{
    data: () => ({
        cards: [],
        giveaways: ''
    }),
    computed:{
        ...mapState({
            Giveaway: state => state.Threshold.giveaways
        }),
        doneGiveAways(){
            return this.$store.getters.doneGiveAways
        }
    },
    ready(){
        //giveaways: this.Giveaways
        //console.log(this.Giveaways);
    },
    created(){
        const self = this
        this.cards[0].result_val = 2
        this.cards[2].result_val = 2;

    },
    mounted(){
        this.$store.dispatch('getGiveAways');
        console.log(this.giveaways);

    }
}

My problem is I need to pass the value from the mapState Giveaway to my returning data giveaways: '' so when page fires I can get the response value using this.giveaways. If I just call {{ Giveaway }} in my html it shows the value. But I need to make something like this.giveaways = this.$store.state.Thresholds.giveaways


问:
Swift - RemoveAllAnimations() doesn't work in an UICollectionViewCell class
I currently have the problem that removeAllAnimations() function does not work in my custom UICollectionViewCell class.

The array progressBar[] includes multiple UIProgressViews. I want the progressBar to stop animating when something is called. But right now it just keeps on animating.
How can I fix this?

First function which does the actual animation

```<code>@objc func updateProgress() {
    if visibleCell == "TRUE" {
        DispatchQueue.main.async {
            if self.index < self.imagesTest.count /*images.count*/ {
                CATransaction.begin()
                CATransaction.setCompletionBlock {
                    self.index += 1
                    self.updateProgress()
                }
                UIView.animate(withDuration: self.time, delay: 0, options: .curveLinear, animations: {
                    self.progressBar[self.index].setProgress(1.0, animated: true)
                })
                CATransaction.commit()
            }
        }
    }
}
</code>```

Second function which should stop the ongoing animation

```<code>func stopUpdating() {
    progressBar[index].layer.removeAllAnimations()
}
</code>```

答:
You can achieve that with single line of code

Replace your code

```<code>func stopUpdating() {
    progressBar[index].layer.removeAllAnimations()
}
</code>```

With

```<code>func stopUpdating() {
   progressBar[index].layer.speed = 0
}
</code>```

Hope it is helpful to you

Body:
I currently have the problem that removeAllAnimations() function does not work in my custom UICollectionViewCell class.

The array progressBar[] includes multiple UIProgressViews. I want the progressBar to stop animating when something is called. But right now it just keeps on animating.
How can I fix this?

First function which does the actual animation

@objc func updateProgress() {
    if visibleCell == "TRUE" {
        DispatchQueue.main.async {
            if self.index < self.imagesTest.count /*images.count*/ {
                CATransaction.begin()
                CATransaction.setCompletionBlock {
                    self.index += 1
                    self.updateProgress()
                }
                UIView.animate(withDuration: self.time, delay: 0, options: .curveLinear, animations: {
                    self.progressBar[self.index].setProgress(1.0, animated: true)
                })
                CATransaction.commit()
            }
        }
    }
}

Second function which should stop the ongoing animation

func stopUpdating() {
    progressBar[index].layer.removeAllAnimations()
}

Body:
You can achieve that with single line of code

Replace your code

func stopUpdating() {
    progressBar[index].layer.removeAllAnimations()
}

With

func stopUpdating() {
   progressBar[index].layer.speed = 0
}

Hope it is helpful to you


问:
what it means when javascript console shows a circle with #2
I just wonder what it means when javascript console shows a circle with #2.

答: It means that the output is the same n number of times.


问:
How to pass a string from C to swift?
I am using OpenSSL as a library in swift. Since it's in C, I need to pass some data from C language back to swift. The data was an array, but after some research I have learned that I cannot pass an array from C to swift. One way I can think of it is to change the array into a string, an then pass the string back to swift.
In C I wrote:

```<code>char teststring()
{
    char c[]={"H","E","L","L","O"};
    printf(c);
    return c;
}
</code>```

In Swift I wrote:

```<code>teststring()
</code>```

The result is that it only prints H.
What did I do wrong with it? It there a easier way to pass an array from C back to Swift?

答:
c is an array and when you return c you return first element. You need to return entire array. Check

```<code>printf("%s", c);
return *c;
</code>```

And remember to change signature of your function

Title: How to pass a string from C to swift?

Body:
I am using OpenSSL as a library in swift. Since it's in C, I need to pass some data from C language back to swift. The data was an array, but after some research I have learned that I cannot pass an array from C to swift. One way I can think of it is to change the array into a string, an then pass the string back to swift.
In C I wrote:

char teststring()
{
    char c[]={"H","E","L","L","O"};
    printf(c);
    return c;
}

In Swift I wrote:

teststring()

The result is that it only prints H.
What did I do wrong with it? It there a easier way to pass an array from C back to Swift?

Body:
c is an array and when you return c you return first element. You need to return entire array. Check

printf("%s", c);
return *c;

And remember to change signature of your function


问:
split character data into numbers and letters
I have a vector of character data.  Most of the elements in the vector consist of one or more letters followed by one or more numbers.   I wish to split each element in the vector into the character portion and the number portion.  I found a similar question on Stackoverflow.com here:

split a character from a number with multiple digits

However, the answer given above does not seem to work completely in my case or I am doing something wrong.  An example vector is below:

```<code>my.data <- c("aaa", "b11", "b21", "b101", "b111", "ccc1", "ddd1", "ccc20", "ddd13")

# I can obtain the number portion using:
gsub("[^[:digit:]]", "", my.data)

# However, I cannot obtaining the character portion using:
gsub("[:digit:]", "", my.data)
</code>```

How can I obtain the character portion?  I am using R version 2.14.1 on a Windows 7 64-bit machine.

答:
Late answer, but another option is to use strsplit with a regex pattern which uses lookarounds to find the boundary between numbers and letters:

```<code>var <- "ABC123"
strsplit(var, "(?=[A-Za-z])(?<=[0-9])|(?=[0-9])(?<=[A-Za-z])", perl=TRUE)
[[1]]
[1] "ABC" "123"
</code>```

The above pattern will match (but not consume) when either the previous character is a letter and the following character is a number, or vice-versa.  Note that we use strsplit in Perl mode to access lookarounds.

Demo

Body:
I have a vector of character data.  Most of the elements in the vector consist of one or more letters followed by one or more numbers.   I wish to split each element in the vector into the character portion and the number portion.  I found a similar question on Stackoverflow.com here:

split a character from a number with multiple digits

However, the answer given above does not seem to work completely in my case or I am doing something wrong.  An example vector is below:

my.data <- c("aaa", "b11", "b21", "b101", "b111", "ccc1", "ddd1", "ccc20", "ddd13")

# I can obtain the number portion using:
gsub("[^[:digit:]]", "", my.data)

# However, I cannot obtaining the character portion using:
gsub("[:digit:]", "", my.data)

How can I obtain the character portion?  I am using R version 2.14.1 on a Windows 7 64-bit machine.

Body:
Late answer, but another option is to use strsplit with a regex pattern which uses lookarounds to find the boundary between numbers and letters:

var <- "ABC123"
strsplit(var, "(?=[A-Za-z])(?<=[0-9])|(?=[0-9])(?<=[A-Za-z])", perl=TRUE)
[[1]]
[1] "ABC" "123"

The above pattern will match (but not consume) when either the previous character is a letter and the following character is a number, or vice-versa.  Note that we use strsplit in Perl mode to access lookarounds.

Demo


问:
How to check divisibility of a number not in base 10 without converting?
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

```<code>class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};
</code>```

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan

答:
Same as in base 10, for your example:
1. Find the multiple of 2 that's <= 1211, that's 1210 (see below how to achieve it)
2. Substract 1210 from 1211, you get 1
3. 1 is < 10, thus 1211 isn't divisible by 2

how to achieve 1210:
1. starts with 2
2. 2 + 2 = 11
3. 11 + 2 = 20
4. 20 + 2 = 22
5. 22 + 2 = 101
6. 101 + 2 = 110
7. 110 + 2 = 112
8. 112 + 2 = 121
9. 121 + 2 = 200
10. 200 + 2 = 202
... // repeat until you get the biggest number <= 1211
it's basically the same as base 10 it's just the round up happens on 3 instead of 10.

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan


问:
How can I insert data one table and update some data in another table in asp.net mvc 5 & Entity Framework
I am using ASP.NET MVC 5 and Entity Framework for my stationery project. my entity models are (I have given the important fields only).

```<code>public partial class Purchase
{
    public int Id { get; set; }
    public string Item { get; set; }
    public int Quantity { get; set; }
    public Nullable<decimal> UnitPrice { get; set; }
    public Nullable<decimal> Amount { get; set; }
    public System.DateTime PurchaseDate { get; set; }
    public string Vendor { get; set; }
    public string ChallanNo { get; set; }
    public string BillNo { get; set; }
}
public partial class Stock
{
    public int MatId { get; set; }
    public string Item { get; set; }
    public Nullable<int> Quantity { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public Nullable<int> UserId { get; set; }
    public string Status { get; set; }
    public Nullable<System.DateTime> SystemDate { get; set; }
}
</code>```

Now the requirement is when I create the purchase order it will insert data to Purchase table. Now I have to update the Stock table for Quantity field automatically.

答:
Update the stock table while saving the purchase. Assume that the purchases you want to save is in object model

```<code>using (var context=new SomeDBContext()){
  context.Purchases.Add(model);
  var itemRow=context.Stocks.FirstOrDefault(o=>o.item==model.item);
  if (itemRow !=null)
  {
     itemRow.Quantity+ =model.Quantity;
     context.Entry(itemRow).State=EntityState.Modified;
  }
  else
  {
     context.Stocks.Add(new stock(){Item=model.Item,Quantity=model.Quantity,.......});
  }
     context.SaveChanges();
}
</code>```

Note:

1. You need to implement another code for update and delete of purchases

2. The best method is to plan your table so that there will be a master detail relationship between stock and purchases so that you can update the stock quantity with the sum of all purchases under its detail. That way, you can update the stock (master) from within the purchase Quantity property setter when the quantity changes

Body:
I am using ASP.NET MVC 5 and Entity Framework for my stationery project. my entity models are (I have given the important fields only).

public partial class Purchase
{
    public int Id { get; set; }
    public string Item { get; set; }
    public int Quantity { get; set; }
    public Nullable<decimal> UnitPrice { get; set; }
    public Nullable<decimal> Amount { get; set; }
    public System.DateTime PurchaseDate { get; set; }
    public string Vendor { get; set; }
    public string ChallanNo { get; set; }
    public string BillNo { get; set; }
}
public partial class Stock
{
    public int MatId { get; set; }
    public string Item { get; set; }
    public Nullable<int> Quantity { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public Nullable<int> UserId { get; set; }
    public string Status { get; set; }
    public Nullable<System.DateTime> SystemDate { get; set; }
}

Now the requirement is when I create the purchase order it will insert data to Purchase table. Now I have to update the Stock table for Quantity field automatically.

Body:
Update the stock table while saving the purchase. Assume that the purchases you want to save is in object model

using (var context=new SomeDBContext()){
  context.Purchases.Add(model);
  var itemRow=context.Stocks.FirstOrDefault(o=>o.item==model.item);
  if (itemRow !=null)
  {
     itemRow.Quantity+ =model.Quantity;
     context.Entry(itemRow).State=EntityState.Modified;
  }
  else
  {
     context.Stocks.Add(new stock(){Item=model.Item,Quantity=model.Quantity,.......});
  }
     context.SaveChanges();
}

Note:

1. You need to implement another code for update and delete of purchases

2. The best method is to plan your table so that there will be a master detail relationship between stock and purchases so that you can update the stock quantity with the sum of all purchases under its detail. That way, you can update the stock (master) from within the purchase Quantity property setter when the quantity changes


问:
How do we create a bigger center UITabBar Item
I am wondering how do we create a bigger center UITabBar like the shot below? Its really beautiful!!!!

答:
Click the tab bar button within the view controller of the particular tab bar item you want to make prominent,

Remove the text, just set the image inset top to -25 of the tab bar button.

Like Below image

After that

goto assets,
select the image you set in tab bar button,
 set the property Rendering As to Original Image (in case if you have a colourful button or else it would render as one colour)

Like below,

Now, You will get it like you wanted,

EDIT: To make upper half clickable, inherit UITabBar

```<code>class ProminentTabBar: UITabBar {
    var prominentButtonCallback: (()->())?

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard let items = items, items.count>0 else {
            return super.hitTest(point, with: event)
        }

        let middleItem = items[items.count/2]
        let middleExtra = middleItem.imageInsets.top
        let middleWidth = bounds.width/CGFloat(items.count)
        let middleRect = CGRect(x: (bounds.width-middleWidth)/2, y: middleExtra, width: middleWidth, height: abs(middleExtra))
        if middleRect.contains(point) {
            prominentButtonCallback?()
            return nil
        }
        return super.hitTest(point, with: event)
    }
}
</code>```

And in TabBarController add this

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let prominentTabBar = self.tabBar as! ProminentTabBar
    prominentTabBar.prominentButtonCallback = prominentTabTaped
}

func prominentTabTaped() {
    selectedIndex = (tabBar.items?.count ?? 0)/2
}
</code>```

And remmber there is no nice solution when it comes to UITabBar :-)

Body:
Click the tab bar button within the view controller of the particular tab bar item you want to make prominent,

Remove the text, just set the image inset top to -25 of the tab bar button.

Like Below image

After that

goto assets,
select the image you set in tab bar button,
 set the property Rendering As to Original Image (in case if you have a colourful button or else it would render as one colour)

Like below,

Now, You will get it like you wanted,

EDIT: To make upper half clickable, inherit UITabBar

class ProminentTabBar: UITabBar {
    var prominentButtonCallback: (()->())?

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        guard let items = items, items.count>0 else {
            return super.hitTest(point, with: event)
        }

        let middleItem = items[items.count/2]
        let middleExtra = middleItem.imageInsets.top
        let middleWidth = bounds.width/CGFloat(items.count)
        let middleRect = CGRect(x: (bounds.width-middleWidth)/2, y: middleExtra, width: middleWidth, height: abs(middleExtra))
        if middleRect.contains(point) {
            prominentButtonCallback?()
            return nil
        }
        return super.hitTest(point, with: event)
    }
}

And in TabBarController add this

override func viewDidLoad() {
    super.viewDidLoad()

    let prominentTabBar = self.tabBar as! ProminentTabBar
    prominentTabBar.prominentButtonCallback = prominentTabTaped
}

func prominentTabTaped() {
    selectedIndex = (tabBar.items?.count ?? 0)/2
}

And remmber there is no nice solution when it comes to UITabBar :-)

ContentLicense: CC BY-SA 4.0


问:
Failed to resolve: com.android.support:appcompat-v7:25.1.0
<img src="https://i.stack.imgur.com/okp2g.png" alt="enter image description here">My Android Studio is full of error android studio cannot identify libraries. </p>

```<code>Error:(27, 13) Failed to resolve: com.android.support:appcompat-v7:25.1.0
</code>```

答:
add below code in your Project level gradle in allprojects{}

```<code> maven {
        url "https://maven.google.com"
    }
</code>```

Body:
My Android Studio is full of error android studio cannot identify libraries.

Error:(27, 13) Failed to resolve: com.android.support:appcompat-v7:25.1.0

Body:
add below code in your Project level gradle in allprojects{}

 maven {
        url "https://maven.google.com"
    }


问:
How to duplicate directory in git, tracking new files?
Is there a simple way to create a copy of a folder in a local repository, keeping track of exactly the same files (do not care about commit history, or untracked files)? </p>

<p>Folder contains a hierarchy of both tracked and untracked (but not ignored) files and directories. I basically want to recursively replicate the tracked structure. Is there a way apart of copying everything, then manually adding only the relevant files (there are a lot of them)? </p>

答:
You can go to your intended directory and clone your git project again.</p>

```<code>$ cd "new_directory"
$ git clone "your_project_git_address"
</code>```

Body:
Is there a simple way to create a copy of a folder in a local repository, keeping track of exactly the same files (do not care about commit history, or untracked files)?

Folder contains a hierarchy of both tracked and untracked (but not ignored) files and directories. I basically want to recursively replicate the tracked structure. Is there a way apart of copying everything, then manually adding only the relevant files (there are a lot of them)?

Body:
You can go to your intended directory and clone your git project again.

$ cd "new_directory"
$ git clone "your_project_git_address"


问:
What language is needed to write applets for e-ink Kindles?
So I want to write a small app for my e-ink Kindle. I know it's possible -- Amazon has released a Kindle Developer's Kit, but I can't figure out how to signup (I followed a signup link on another SO post that redirected to the useless homepage).

I've also seen people doing it on the MobileRead Forums.

The app I want to make is pretty simple, but I can't figure out what language it would need to be in.

What languages are native to the older Kindles (not Kindle Fire)?

答:
Personal Basis Profile 1.1 and Java 1.4

It seams you cannot register as a developer for the old Kindle anymore, so you need to jailbreak it and use a key (that you create yourself) to sign your jars.

You can find instructions what to do and several resources at the URL mentioned below.

There is also a tool to create your own Kindle developer key.

You need to install the public key on your Kindle. To be able to use your jars that you sign with it.

A Hello-World example is also included on the website.

It is also explained how to use retroweaver that makes it possible to use java 1.5 and than convert it to 1.4.

http://cowlark.com/kindle/getting-started.html

P.s.

Please add a comment as soon as you successfully wrote your first app that runs on your kindle.


问:
Main branch rollback and merge child branch missing changes
Lets say i have 2 branches A (main), B(child)

I merge B to A and as a result create changeset 200 in A

Then I move B branch to Retired folder resulting changeset 201

After that I create a new branch C from A resulting changeset 202

Roll back changeset 200 in main branch A resulting changeset 203

Now if i merge Branch C to A as a Reverse Intergration I want to get all the back all the rollback changes in Branch A

But i get the message Nothing to Merge

 note i used only Visual studio not command prompt. Any solution woukd be appreciated

答:
When you try to merge from Branch C to A, there is actually no candidate in Branch C (changesets in the source Branch C that have not yet been merged into the destination Branch A), so you get message Nothing to Merge.

You can try to do some modification in Branch C to get a new changeset in Branch C, then perform a merge to Branch A, or you can use Merge command with /force option to force this merge. /force option will ignore the merge history and merge the specified changes from the source into the destination.


问:
How to add back button to custom toolbar layout on AppCompatActivity?
I'm developing an android app. I'm using AppCompatActivity and would like to add back button to my custom toolbar. Here is the code of the toolbar:

```<code><?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical" >

       <ImageView
           android:id="@+id/imageView"
           android:layout_width="match_parent"
           android:layout_height="54dp"
           android:layout_gravity="center_horizontal"
           android:src="@drawable/logo" />

       <TextView android:id="@+id/title" android:layout_width="wrap_content"
           android:gravity="center_vertical" android:textSize="24px"
           android:textColor="#000000"
           android:layout_height="wrap_content"
           android:padding="9dip"
           android:layout_marginLeft="7dip"
           android:layout_marginRight="7dip"
           android:layout_marginStart="28dp"
           android:layout_centerVertical="true"
           android:layout_alignParentStart="true" />

</RelativeLayout>
</code>```

Here is my activity code:

```<code>    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookmarks);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);

    actionBar.setIcon(R.mipmap.ic_logo);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.setCustomView(R.layout.abs_layout);
    actionBar.setIcon(R.drawable.logo);

    //actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
    ((TextView)findViewById(R.id.title)).setText(R.string.bookmarks);
</code>```

What do I have to add that the back button will be displayed?

Best,
B.

答:
add this code to your layout (activity_main.xml):

```<code><android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/white"
    app:layout_collapseMode="pin"
    app:layout_scrollFlags="scroll"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</code>```

in onCreate method add this code:

```<code>    Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Drawable drawable= ResourcesCompat.getDrawable(this.getResources(), R.drawable.abc_ic_ab_back_material, null);

    //custom color
    //drawable.setColorFilter(ResourcesCompat.getColor(this.getResources(), R.color.colorPrimaryLightText, null), PorterDuff.Mode.SRC_IN);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeAsUpIndicator(drawable);
</code>```

change your root layout to LinearLayout

Body:
I'm developing an android app. I'm using AppCompatActivity and would like to add back button to my custom toolbar. Here is the code of the toolbar:

<?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="vertical" >

       <ImageView
           android:id="@+id/imageView"
           android:layout_width="match_parent"
           android:layout_height="54dp"
           android:layout_gravity="center_horizontal"
           android:src="@drawable/logo" />

       <TextView android:id="@+id/title" android:layout_width="wrap_content"
           android:gravity="center_vertical" android:textSize="24px"
           android:textColor="#000000"
           android:layout_height="wrap_content"
           android:padding="9dip"
           android:layout_marginLeft="7dip"
           android:layout_marginRight="7dip"
           android:layout_marginStart="28dp"
           android:layout_centerVertical="true"
           android:layout_alignParentStart="true" />

</RelativeLayout>

Here is my activity code:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookmarks);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);

    actionBar.setIcon(R.mipmap.ic_logo);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionBar.setCustomView(R.layout.abs_layout);
    actionBar.setIcon(R.drawable.logo);

    //actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
    ((TextView)findViewById(R.id.title)).setText(R.string.bookmarks);

What do I have to add that the back button will be displayed?

Best,
B.

Body:
add this code to your layout (activity_main.xml):

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/white"
    app:layout_collapseMode="pin"
    app:layout_scrollFlags="scroll"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

in onCreate method add this code:

    Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Drawable drawable= ResourcesCompat.getDrawable(this.getResources(), R.drawable.abc_ic_ab_back_material, null);

    //custom color
    //drawable.setColorFilter(ResourcesCompat.getColor(this.getResources(), R.color.colorPrimaryLightText, null), PorterDuff.Mode.SRC_IN);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeAsUpIndicator(drawable);

change your root layout to LinearLayout


问:
Save a random Forest object
I have a randomForest object that I want to save for later use.  I've tried some of the following but with no luck.

```<code>save(topDawg , file="myRFobject.RData")
</code>```

This just saves a string "topDawg"

```<code>> formula(topDawg)
Error in formula.default(topDawg) : invalid formula

> save(getTree(topDawg))
Error in save(getTree(topDawg)) : object ‘getTree(topDawg)’ not found
</code>```

Any suggestions?

答:
Here is a solution if you would like to load the model under another name</p>

```<code>  library(randomForest)

  # 1. Create data set
  set.seed(100)
  df_iris <- randomForest(Species ~ ., data = iris, importance = TRUE,  proximity = TRUE)

  # 2. Save model
  file_name <- "model_iris.rds"
  saveRDS(df_iris, file_name)

  # 2.3. Load model under another name
  df_iris_loaded <- readRDS(file_name)
  df_iris_loaded

  # 2.4. Test two models
  identical(df_iris, df_iris_loaded, ignore.environment = TRUE)
</code>```

Title: Save a random Forest object

Body:
I have a randomForest object that I want to save for later use.  I've tried some of the following but with no luck.

save(topDawg , file="myRFobject.RData")

This just saves a string "topDawg"

> formula(topDawg)
Error in formula.default(topDawg) : invalid formula

> save(getTree(topDawg))
Error in save(getTree(topDawg)) : object ‘getTree(topDawg)’ not found

Any suggestions?

Body:
Here is a solution if you would like to load the model under another name

  library(randomForest)

  # 1. Create data set
  set.seed(100)
  df_iris <- randomForest(Species ~ ., data = iris, importance = TRUE,  proximity = TRUE)

  # 2. Save model
  file_name <- "model_iris.rds"
  saveRDS(df_iris, file_name)

  # 2.3. Load model under another name
  df_iris_loaded <- readRDS(file_name)
  df_iris_loaded

  # 2.4. Test two models
  identical(df_iris, df_iris_loaded, ignore.environment = TRUE)


问:
ASP.NET MVC How to Save multi language in Cookies
I need to store languages in cookies when use changes the language and read language from cookies
The below code works great but i don't know where and how can i store language in cookies and read from cookies

This is Rout:

```<code>    routes.MapRoute(
      name: "DefaultLocalized",
      url: "{language}/{controller}/{action}/{id}",
      defaults: new
      {
          controller = "Home",
          action = "Index",
          id = UrlParameter.Optional,

      }
          );
</code>```

The ActionFilterAttribute:

```<code>    public class EnableMultiLanguage : ActionFilterAttribute
    {

        public EnableMultiLanguage()
        {
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string language = (string)filterContext.RouteData.Values["language"];
            if (!string.IsNullOrEmpty(language))
            {

                var cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(x => x.Name == language);

                if (cultureInfo == null)
                {
                    cultureInfo = new CultureInfo("en-US");
                }

                Thread.CurrentThread.CurrentCulture = cultureInfo;
                Thread.CurrentThread.CurrentUICulture = cultureInfo;
                filterContext.RouteData.Values["language"] = cultureInfo.Name;

            }
            else
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
                filterContext.RouteData.Values["language"] = "en-US";
            }
        }
    }
}
</code>```

And here how the user changes the language:

```<code>   <li>@Html.ActionLink("English", ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), new { language = "en-US" }, null)</li>
   <li>@Html.ActionLink("French", ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(),new { language = "fr-FR" },null)</li>
</code>```

答:
```<code>    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var routes = filterContext.RouteData.Values;

        string culture = (routes["culture"] ?? defaultCulture).ToString();

        if (!filterContext.HttpContext.Request.Cookies.AllKeys.Contains("culture"))
        {
            HttpCookie StudentCookies = new HttpCookie("culture");
            StudentCookies.Value = culture;
            StudentCookies.Expires = DateTime.Now.AddYears(1);
            filterContext.HttpContext.Response.Cookies.Add(StudentCookies);
        }
        else
        {
            if (filterContext.HttpContext.Request.Cookies["culture"].Value != (routes["culture"] ?? "").ToString() && routes["culture"] != null)
            {
                filterContext.HttpContext.Response.Cookies["culture"].Value = (routes["culture"] ?? "").ToString();
            }
            if (routes["culture"] == null || routes["culture"] == UrlParameter.Optional)
            {
                culture = filterContext.HttpContext.Request.Cookies["culture"].Value;
            }
        }

        HelperClass.SetCulture(culture);

        if (!routes.ContainsKey("culture") || routes["culture"] == UrlParameter.Optional)
        {
            filterContext.Result = new RedirectResult("/" + culture + "/" + filterContext.HttpContext.Request.Url.LocalPath);
        }

        CultureInfo info = new CultureInfo(culture);
        Thread.CurrentThread.CurrentCulture = info;
        Thread.CurrentThread.CurrentUICulture = info;
        return;
    }
</code>```

Body:
I need to store languages in cookies when use changes the language and read language from cookies
The below code works great but i don't know where and how can i store language in cookies and read from cookies

This is Rout:

    routes.MapRoute(
      name: "DefaultLocalized",
      url: "{language}/{controller}/{action}/{id}",
      defaults: new
      {
          controller = "Home",
          action = "Index",
          id = UrlParameter.Optional,

      }
          );

The ActionFilterAttribute:

    public class EnableMultiLanguage : ActionFilterAttribute
    {

        public EnableMultiLanguage()
        {
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string language = (string)filterContext.RouteData.Values["language"];
            if (!string.IsNullOrEmpty(language))
            {

                var cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(x => x.Name == language);

                if (cultureInfo == null)
                {
                    cultureInfo = new CultureInfo("en-US");
                }

                Thread.CurrentThread.CurrentCulture = cultureInfo;
                Thread.CurrentThread.CurrentUICulture = cultureInfo;
                filterContext.RouteData.Values["language"] = cultureInfo.Name;

            }
            else
            {
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
                filterContext.RouteData.Values["language"] = "en-US";
            }
        }
    }
}

And here how the user changes the language:

@Html.ActionLink("English", ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), new { language = "en-US" }, null)

@Html.ActionLink("French", ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(),new { language = "fr-FR" },null)


问:
How to access a view from layout specified in headerLayout of NavigationView using Kotlin in Android
I want to access a TextView which is included inside headerLayout of NavigationView. Is it possible to access the view using Kotlin android extension? I did using this method, but the TextView (here txtName) is always null.

Here is my activity_main.xml

```<code><android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="end"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_splash"
    app:menu="@menu/activity_splash_drawer" />
</code>```

nav_header_splash.xml

```<code><TextView
    android:id="@+id/txtName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/txt1"
    android:layout_below="@+id/imageView"
    android:text="@string/name"
    android:textSize="18sp"
    android:textColor="@color/white" />
</code>```

in MainActivity.kt  I have imported

```<code>import kotlinx.android.synthetic.main.nav_header_splash.*
</code>```

in onCreate() of Activity class I set text like

```<code>txtName.text = "Sample Code"
</code>```

build.gradle of app folder

```<code>apply plugin: 'kotlin-android-extensions'
</code>```

build.gradle of my project

```<code> classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
</code>```

Is there any mistake in my code? Please help. I'm new in Kotlin.

答:
Do not  import kotlinx.android.synthetic.main.nav_header_splash.*  it will be available from the main file itself as

instead import kotlinx.android.synthetic.main.nav_header_splash.view.*

and get view by using

```<code>val header = mNavigationView.getHeaderView(0)
header.txtName.text = "Sample Code"
</code>```

Body:
I want to access a TextView which is included inside headerLayout of NavigationView. Is it possible to access the view using Kotlin android extension? I did using this method, but the TextView (here txtName) is always null.

Here is my activity_main.xml

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="end"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_splash"
    app:menu="@menu/activity_splash_drawer" />

nav_header_splash.xml

<TextView
    android:id="@+id/txtName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/txt1"
    android:layout_below="@+id/imageView"
    android:text="@string/name"
    android:textSize="18sp"
    android:textColor="@color/white" />

in MainActivity.kt  I have imported

import kotlinx.android.synthetic.main.nav_header_splash.*

in onCreate() of Activity class I set text like

txtName.text = "Sample Code"

build.gradle of app folder

apply plugin: 'kotlin-android-extensions'

build.gradle of my project

 classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

Is there any mistake in my code? Please help. I'm new in Kotlin.

Body:
Do not  import kotlinx.android.synthetic.main.nav_header_splash.*  it will be available from the main file itself as

instead import kotlinx.android.synthetic.main.nav_header_splash.view.*

and get view by using

val header = mNavigationView.getHeaderView(0)
header.txtName.text = "Sample Code"


问:
Can a User resume the chat on different channels(Facebook messenger or Skype) ? where the session should not be lost
I want to make one bot by joining multiple channels like Facebook messenger , Alexa,Native app , Web chat to have a seamless and friction less experience.

User should be able to open and initiate a chat session in-app and close it but not lose the session So that I can easily instigate a chat session with a bot or agent from within the app.

For an instance If I am a user chatting on Facebook messenger bot and after sometime i close it and open the chat bot on the webpage So I should be able to resume the same chat on that channel means session of the user's chat should not be lost.

答:
First of all, bot application connects to mulitiple channels and each channel has its distinct users from others. So as @christophe-willemsen said, you need to build up your own account system and link to all the channels your bot connect. With which, you need to pair the session data with the user.

Then, you can leverage Manage state data to store and access user data. And leverage Advance the waterfall to manage the waterfall steps inside the dialogs.

For quick reference:

```<code>let savedSession;
var bot = new builder.UniversalBot(connector, [(session) => {
    if (savedSession) {
        var [savedDialog] = savedSession.dialogStack().slice(-2, -1);
        console.log(savedDialog);
        session.replaceDialog(savedDialog.id, savedDialog.state)
    } else {
        savedSession = session;
        session.beginDialog('form');
    }
}]);

bot.dialog('form', [...waterfall steps...])
</code>```

Body:
First of all, bot application connects to mulitiple channels and each channel has its distinct users from others. So as @christophe-willemsen said, you need to build up your own account system and link to all the channels your bot connect. With which, you need to pair the session data with the user.

Then, you can leverage Manage state data to store and access user data. And leverage Advance the waterfall to manage the waterfall steps inside the dialogs.

For quick reference:

let savedSession;
var bot = new builder.UniversalBot(connector, [(session) => {
    if (savedSession) {
        var [savedDialog] = savedSession.dialogStack().slice(-2, -1);
        console.log(savedDialog);
        session.replaceDialog(savedDialog.id, savedDialog.state)
    } else {
        savedSession = session;
        session.beginDialog('form');
    }
}]);

bot.dialog('form', [...waterfall steps...])


问:
Does ASP.NET MVC search in the Root path for a folder named the same as the Controller?
I might have come across a bug in ASP.NET MVC, but I'm not sure (after searching for an explanation) if I am right here.

ASP.NET MVC weighs heavily on "Convention over Configuration", which is nice, if they stick to it.

I created a controller called "ChatController", and I made a Folder in the Root-path of my project called "Chat", to keep my Chat-related ViewModel in.

Then I created a folder called "Chat" in my "Views" folder, because as we all know, ASP.NET MVC will look in the "Views/[ControllerName]"-folder and "Views/[Shared]"-folder for a matching view.

But every time I tried to hit my View, I got "404". I figured. Hell, maybe I messed something simple up. So I copied from something that worked, and just renamed. Nope.. still 404.

Then I figured.. but.. it couldn't be... NOOO, it couldn't be that I have a folder in the root being called the same as in my Views/ folder? could it ?

I renamed... And Bingo.. my View got hit, and everything worked.

Am I wrong when I say that this is against how ASP.NET MVC is supposed to work. Isn't it supposed to look ONLY in Views/[ControllerName] and Views/Shared for a suitable View?

If I'm wrong, please point to some literature on the subject (if you know any)... This really looks like a bug to me.

Thanks in advance!

答:
This is more related to how ASP.NET works rather than ASP.NET MVC. When you had Chat folder in your root and you requested /Chat the web server always prefers serving physical folders before the routing engine. So it looked for a file called Default.aspx (or any default document you've setup) in your /Chat folder, it couldn't find one and it blew with 404.

In ASP.NET 4.0 you can relax it :-)

```<code><httpRuntime relaxedUrlToFileSystemMapping="true" />
</code>```

Body:
This is more related to how ASP.NET works rather than ASP.NET MVC. When you had Chat folder in your root and you requested /Chat the web server always prefers serving physical folders before the routing engine. So it looked for a file called Default.aspx (or any default document you've setup) in your /Chat folder, it couldn't find one and it blew with 404.

In ASP.NET 4.0 you can relax it :-)

<httpRuntime relaxedUrlToFileSystemMapping="true" />


问:
Spring Boot: Automatic property expansion using Maven and specific Maven profiles is not working
I'm trying to use the 72.1.1 Automatic property expansion using Maven as specified in the documentation using different maven profiles, but I'm not able to make it work with specific profiles.

I have the following pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <profiles>
        <profile>
            <id>local</id>

            <activation>
                <property>
                    <name>profileName</name>
                    <value>local</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueA</wildcard.for.customproperty>
            </properties>
        </profile>

        <profile>
            <id>external</id>
            <activation>
                <property>
                    <name>profileName</name>
                    <value>external</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueB</wildcard.for.customproperty>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.RELEASE</version>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.9.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

And this very simple application.properties:

```<code>custom.property=@wildcard.for.customproperty@
</code>```

I run the maven build with Spring Tool Suite with the following goals:

```<code>clean install -DprofileName=local
</code>```

The build SUCCESS, but the application.properties in target folder still contains the unresolved @...@ placeholder.

If I add this simple line in the pom.xml in one of the two profiles:

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

The placeholder is correctly resolved.

What's wrong with this configuration?

答:
I have solved with the following configuration:

pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <profiles>
        <profile>
            <id>local</id>

            <activation>
                <property>
                    <name>profileName</name>
                    <value>local</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueA</wildcard.for.customproperty>
                <activatedProperties>local</activatedProperties>
            </properties>
            <build>
                <finalName>myBuild-local</finalName>
            </build>
        </profile>

        <profile>
            <id>external</id>
            <activation>
                <property>
                    <name>profileName</name>
                    <value>external</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueB</wildcard.for.customproperty>
                <activatedProperties>external</activatedProperties>
            </properties>
            <build>
                <finalName>myBuild-external</finalName>
            </build>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.9.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <delimiters>
                        <delimiter>@{*}</delimiter>
                    </delimiters>
                    <useDefaultDelimiters>false</useDefaultDelimiters>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

application.properties:

```<code>custom.property=@{wildcard.for.customproperty}
spring.profiles.active=@{activatedProperties}
</code>```

Finally, most important step:

In STS you need to right clic on the Project -> Properties ->  Maven tab

There you need to specify the active profile.

For some reasons, even if you put the -PprofileName or the profile directly in the profile field of the Maven build, STS doesn't apply the profile.

Body:
I'm trying to use the 72.1.1 Automatic property expansion using Maven as specified in the documentation using different maven profiles, but I'm not able to make it work with specific profiles.

I have the following pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <profiles>
        <profile>
            <id>local</id>

            <activation>
                <property>
                    <name>profileName</name>
                    <value>local</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueA</wildcard.for.customproperty>
            </properties>
        </profile>

        <profile>
            <id>external</id>
            <activation>
                <property>
                    <name>profileName</name>
                    <value>external</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueB</wildcard.for.customproperty>
            </properties>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.RELEASE</version>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.9.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

And this very simple application.properties:

custom.property=@wildcard.for.customproperty@

I run the maven build with Spring Tool Suite with the following goals:

clean install -DprofileName=local

The build SUCCESS, but the application.properties in target folder still contains the unresolved @...@ placeholder.

If I add this simple line in the pom.xml in one of the two profiles:

<activeByDefault>true</activeByDefault>

The placeholder is correctly resolved.

What's wrong with this configuration?

Body:
I have solved with the following configuration:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <profiles>
        <profile>
            <id>local</id>

            <activation>
                <property>
                    <name>profileName</name>
                    <value>local</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueA</wildcard.for.customproperty>
                <activatedProperties>local</activatedProperties>
            </properties>
            <build>
                <finalName>myBuild-local</finalName>
            </build>
        </profile>

        <profile>
            <id>external</id>
            <activation>
                <property>
                    <name>profileName</name>
                    <value>external</value>
                </property>
            </activation>
            <properties>
                <wildcard.for.customproperty>valueB</wildcard.for.customproperty>
                <activatedProperties>external</activatedProperties>
            </properties>
            <build>
                <finalName>myBuild-external</finalName>
            </build>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.9.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>1.5.9.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <delimiters>
                        <delimiter>@{*}</delimiter>
                    </delimiters>
                    <useDefaultDelimiters>false</useDefaultDelimiters>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.properties:

custom.property=@{wildcard.for.customproperty}
spring.profiles.active=@{activatedProperties}

Finally, most important step:

In STS you need to right clic on the Project -> Properties ->  Maven tab

There you need to specify the active profile.

For some reasons, even if you put the -PprofileName or the profile directly in the profile field of the Maven build, STS doesn't apply the profile.


问:
How can I find dependancies in my data in R? (A + B + C -> D)
I want to reduce my data by sorting out dependent variables. E.g. A + B + C -> D so I can leave out D without loosing any information.

```<code>d <- data.frame(A = c( 1, 2, 3, 4, 5),
                B = c( 2, 4, 6, 4, 2),
                C = c( 3, 4, 2, 1, 0),
                D = c( 6, 10, 11, 9, 9))
</code>```

The last value of D is wrong, that is because the data can be inaccurate.

How can I identify these dependencies with R and how can I influence the accuracy of the correlation? (e.g., use a cutoff of 80 or 90 percent)

Example findCorrelation only considers pair-wise correlations. Is there a function for multiple correlations?

答:
The Question is about how it is possible to detect dependancies in larger sets of data.
For one this is possible by manually checking every possibility, like proposed in other answers with summary(lm(D ~ A + B + C, data =d)) for example. But this means a lot of manual work.

I see a few possibilities. For one Filter Methods like RReliefF or Spearman Correlation for example. they look at the correlation and
measure distance witin the data set.

Possibility two is using Feature Extraction methods lika PCA, LDA or ICA all trying to find the independent compontents (meaning eliminating any correlations...)

Body:
I want to reduce my data by sorting out dependent variables. E.g. A + B + C -> D so I can leave out D without loosing any information.

d <- data.frame(A = c( 1, 2, 3, 4, 5),
                B = c( 2, 4, 6, 4, 2),
                C = c( 3, 4, 2, 1, 0),
                D = c( 6, 10, 11, 9, 9))

The last value of D is wrong, that is because the data can be inaccurate.

How can I identify these dependencies with R and how can I influence the accuracy of the correlation? (e.g., use a cutoff of 80 or 90 percent)

Example findCorrelation only considers pair-wise correlations. Is there a function for multiple correlations?


问:
Issue with HTML email signature in reply
I'm having issues with an email signature I'm creating with HTML. I've linked an image from another topic (dated 2013), with the same issue - to no fix.

When replying to an email, the quoted text appears beside the signature, instead of underneath. I've tried 100% width on numerous elements, to the same issue. Breaks also don't work (trimmed in Outlook?).

I've created the signature with tables. Formatting the html doc in Word (setting table word wrap to none) will fix the issue - but I don't want the mass amounts of fluff associated with the Word created html.

Any help would be greatly appreciated.

Source Topic

Edit: Fixed - I had to nest tables. Surrounded my signature table with a

 ...

答:
To resolve the issue I've selected the full signature in word document:

Right click > Table Properties> Text Wrapping> None.

This moves the original message below the signature as intended.


问:
SELECT Max index for multiple column values in the same table?
I have the following database structure:

```<code>post_id | language | index
</code>```

Data looks like:

```<code>1  |  en  |  1
1  |  en  |  2
1  |  en  |  3

1  |  fr |  1
1  |  fr |  2
</code>```

language is a shortcode like en, fr, etc. index is an incrementing integer. There is at least one language code in the database.

I need to get the max value of index for each language.

Currently i get all languages for a post

```<code>SELECT DISTINCT(language) FROM my_table WHERE post_id = ?
</code>```

and iterate then over the language array to get the Max value for each language

```<code>SELECT MAX(index) FROM my_table WHERE post_id = ? AND language = 'language_code'
</code>```

Is there a way to execute just one query to achieve this result?

The result should look like:

```<code>1  |  en  |  3
1  |  fr  |  2
</code>```

答:
SQL GROUP BY clause is used to group rows according to distinct values of column specified into GROUP BY clause

According to description as mentioned above as a solution to it please try executing following SQL SELECT QUERY

```<code>SELECT post_id,language, max(index)
FROM my_table group by language
</code>```

Body:
I have the following database structure:

post_id | language | index

Data looks like:

1  |  en  |  1
1  |  en  |  2
1  |  en  |  3

1  |  fr |  1
1  |  fr |  2

language is a shortcode like en, fr, etc. index is an incrementing integer. There is at least one language code in the database.

I need to get the max value of index for each language.

Currently i get all languages for a post

SELECT DISTINCT(language) FROM my_table WHERE post_id = ?

and iterate then over the language array to get the Max value for each language

SELECT MAX(index) FROM my_table WHERE post_id = ? AND language = 'language_code'

Is there a way to execute just one query to achieve this result?

The result should look like:

1  |  en  |  3
1  |  fr  |  2

Body:
SQL GROUP BY clause is used to group rows according to distinct values of column specified into GROUP BY clause

According to description as mentioned above as a solution to it please try executing following SQL SELECT QUERY

SELECT post_id,language, max(index)
FROM my_table group by language


问:
What are the thing we need to configure to implement live notification module (using redis and socket.io) in https server?
I have done a successfully live notification module in my local machine. I need to implement this module in live server. Live server is https. I don't know what are the things we need to change for https. Please check my code and help to integrate this on https server. Thanks.

ssl files

```<code>SSLCertificateFile /etc/letsencrypt/live/dev.test.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/dev.test.de/privkey.pem
</code>```

socket.js

```<code>var app   = require('express')();
var http  = require('http').Server(app);
var io    = require('socket.io')(http);
var redis = require('redis');

io.on('connection', function(socket){
    console.log('a user connected');

    var redisClient = redis.createClient();

    /* Realtime message subscribe */
    redisClient.subscribe('message');
    redisClient.on('message', function(channel, message){
        /*console.log('new message in queue', channel, message);*/
        socket.emit(channel, message);
    });

    /* Realtime inquiry subscribe */
    redisClient.subscribe('inquiryCount');
    redisClient.on('inquiryCount', function(channel, message){
        /*console.log('new inquiry in queue', channel, message);*/
        socket.emit(channel, message);
    });

    socket.on('disconnect', function(){
        redisClient.quit();
        console.log('user disconnected');
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});
</code>```

app.blade.php

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
    <script>
        var socket = io('{{env('APP_URL')}}:3000');
        /* Realtime message notification */
        socket.on('message', function(data){
           if(data){
               /* var res = $.parseJSON(data);*/
               $('.messages-menu').empty();
               $('.messages-menu').html(data);
           }
        });
        /* Realtime inquiry notification */
        socket.on('inquiryCount', function(data){
            if(data){
                $('.tasks-menu').empty();
                $('.tasks-menu').html(data);
            }
        });
    </script>
</code>```

DashboardController.php

```<code>public function privateMessageAPICount($id)
{
      $message = 'taking count of data';
      if(count($message) > 0){
           $redis = Redis::connection();
                $redis->publish('message', $message);
                return response()->json(['status' => 'success'], 200);
        }
        else {
            return response()->json(['status' => 'No Result'], 404);
        }
 }

public function inquiryAPIUnreadCount($id)
{
   $inquiryCount .= 'taking count of data';
   if(count($inquiryCount ) > 0){
         $redis = Redis::connection();
          $redis->publish('inquiryCount', $inquiryCount);
          return response()->json(['status' => 'success'], 200);
        }
        else {
            return response()->json(['status' => 'No Result'], 404);
        }
 }
</code>```

答:
When your apache server is already configured using https, you just have to implement https to your ws-server. Since this is a node http server, this modified code should work (based on this post):

```<code>var app   = require('express')();
var fs = require('fs');
var privateKey  = fs.readFileSync('/etc/letsencrypt/live/dev.test.de/privkey.pem', 'utf8');
var certificate = fs.readFileSync('/etc/letsencrypt/live/dev.test.de/fullchain.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var https  = require('https').createServer(credentials, app);
var io    = require('socket.io')(https);
var redis = require('redis');

io.on('connection', function(socket){
    console.log('a user connected');

    var redisClient = redis.createClient();

    /* Realtime message subscribe */
    redisClient.subscribe('message');
    redisClient.on('message', function(channel, message){
        /*console.log('new message in queue', channel, message);*/
        socket.emit(channel, message);
    });

    /* Realtime inquiry subscribe */
    redisClient.subscribe('inquiryCount');
    redisClient.on('inquiryCount', function(channel, message){
        /*console.log('new inquiry in queue', channel, message);*/
        socket.emit(channel, message);
    });

    socket.on('disconnect', function(){
        redisClient.quit();
        console.log('user disconnected');
    });
});

https.listen(3000, function(){
    console.log('listening on *:3000');
});
</code>```

Your APP_URL has to start with https://.

I would recommend to use laravel-echo-server to handle ws-connections, it's much simpler

Body:
I have done a successfully live notification module in my local machine. I need to implement this module in live server. Live server is https. I don't know what are the things we need to change for https. Please check my code and help to integrate this on https server. Thanks.

ssl files

SSLCertificateFile /etc/letsencrypt/live/dev.test.de/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/dev.test.de/privkey.pem

socket.js

var app   = require('express')();
var http  = require('http').Server(app);
var io    = require('socket.io')(http);
var redis = require('redis');

io.on('connection', function(socket){
    console.log('a user connected');

    var redisClient = redis.createClient();

    /* Realtime message subscribe */
    redisClient.subscribe('message');
    redisClient.on('message', function(channel, message){
        /*console.log('new message in queue', channel, message);*/
        socket.emit(channel, message);
    });

    /* Realtime inquiry subscribe */
    redisClient.subscribe('inquiryCount');
    redisClient.on('inquiryCount', function(channel, message){
        /*console.log('new inquiry in queue', channel, message);*/
        socket.emit(channel, message);
    });

    socket.on('disconnect', function(){
        redisClient.quit();
        console.log('user disconnected');
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

app.blade.php

DashboardController.php

public function privateMessageAPICount($id)
{
      $message = 'taking count of data';
      if(count($message) > 0){
           $redis = Redis::connection();
                $redis->publish('message', $message);
                return response()->json(['status' => 'success'], 200);
        }
        else {
            return response()->json(['status' => 'No Result'], 404);
        }
 }

public function inquiryAPIUnreadCount($id)
{
   $inquiryCount .= 'taking count of data';
   if(count($inquiryCount ) > 0){
         $redis = Redis::connection();
          $redis->publish('inquiryCount', $inquiryCount);
          return response()->json(['status' => 'success'], 200);
        }
        else {
            return response()->json(['status' => 'No Result'], 404);
        }
 }

Body:
When your apache server is already configured using https, you just have to implement https to your ws-server. Since this is a node http server, this modified code should work (based on this post):

var app   = require('express')();
var fs = require('fs');
var privateKey  = fs.readFileSync('/etc/letsencrypt/live/dev.test.de/privkey.pem', 'utf8');
var certificate = fs.readFileSync('/etc/letsencrypt/live/dev.test.de/fullchain.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var https  = require('https').createServer(credentials, app);
var io    = require('socket.io')(https);
var redis = require('redis');

io.on('connection', function(socket){
    console.log('a user connected');

    var redisClient = redis.createClient();

    /* Realtime message subscribe */
    redisClient.subscribe('message');
    redisClient.on('message', function(channel, message){
        /*console.log('new message in queue', channel, message);*/
        socket.emit(channel, message);
    });

    /* Realtime inquiry subscribe */
    redisClient.subscribe('inquiryCount');
    redisClient.on('inquiryCount', function(channel, message){
        /*console.log('new inquiry in queue', channel, message);*/
        socket.emit(channel, message);
    });

    socket.on('disconnect', function(){
        redisClient.quit();
        console.log('user disconnected');
    });
});

https.listen(3000, function(){
    console.log('listening on *:3000');
});

Your APP_URL has to start with https://.

I would recommend to use laravel-echo-server to handle ws-connections, it's much simpler


问:
sequelize throwing error Dialect needs to be explicitly defined in express js
Hi I am trying to use sequelize find all query. But it is giving error as :

Error: Dialect needs to be explicitly supplied as of v4.0.0
    at new Sequelize (/home/europa/public_html/wired-rest-apis/node_modules/sequelize/lib/sequelize.js:170:13)

Below is my express js / node js code:-

```<code>  var Sequelize = require('sequelize');

    // db config
    var env = "dev";
    var config = require('./config.json')[env];
    var password = config.password ? config.password : null;

    // initialize database connection
    var sequelize = new Sequelize(
        config.database,
        config.user,
        config.password, {
            logging: console.log,
            define: {
                timestamps: false
            }
        }
    );

    app.get('/list_cars', function(req,res){

        const Image = sequelize.define('add_cars', {/* ... */})
        const Car = sequelize.define('car_images', {/* ... */})
        Car.hasMany(Image, {as: 'Images', foreignKey:'add_car_id'})
        Car.findAll({
         include: [{
         model: Image
         }]
       })  .success(function(cars) {
            console.log(cars);
         });

    });
</code>```

答:
Make sure u are using dialect in config.json,</p>

```<code>{
    "username" : "root",
    "password" : "root",
    "database" :"grijan",
    "host" : "localhost",
    "dialect" : "mysql",
    "name" : "add"
}
</code>```

Body:
Hi I am trying to use sequelize find all query. But it is giving error as :

Error: Dialect needs to be explicitly supplied as of v4.0.0
    at new Sequelize (/home/europa/public_html/wired-rest-apis/node_modules/sequelize/lib/sequelize.js:170:13)

Below is my express js / node js code:-

  var Sequelize = require('sequelize');

    // db config
    var env = "dev";
    var config = require('./config.json')[env];
    var password = config.password ? config.password : null;

    // initialize database connection
    var sequelize = new Sequelize(
        config.database,
        config.user,
        config.password, {
            logging: console.log,
            define: {
                timestamps: false
            }
        }
    );

    app.get('/list_cars', function(req,res){

        const Image = sequelize.define('add_cars', {/* ... */})
        const Car = sequelize.define('car_images', {/* ... */})
        Car.hasMany(Image, {as: 'Images', foreignKey:'add_car_id'})
        Car.findAll({
         include: [{
         model: Image
         }]
       })  .success(function(cars) {
            console.log(cars);
         });

    });

Body:
Make sure u are using dialect in config.json,

{
    "username" : "root",
    "password" : "root",
    "database" :"grijan",
    "host" : "localhost",
    "dialect" : "mysql",
    "name" : "add"
}


答: Problem solved. I revert the darknet version to Nov 22, 2016 version of pjreddie/darknet and it is able to train with GPU</p>

Title: Darknet Yolo v1 GPU training not getting any result

Body:
I am trying to use darknet yolov1 to train a single class object detection. However, when I tried to train, the CPU works but slow, GPU give a result as follow:

layer     filters    size              input                output
    0 conv     64  7 x 7 / 2   448 x 448 x   3   ->   224 x 224 x  64
    1 max          2 x 2 / 2   224 x 224 x  64   ->   112 x 112 x  64
    2 conv    192  3 x 3 / 1   112 x 112 x  64   ->   112 x 112 x 192
    3 max          2 x 2 / 2   112 x 112 x 192   ->    56 x  56 x 192
    4 conv    128  1 x 1 / 1    56 x  56 x 192   ->    56 x  56 x 128
    5 conv    256  3 x 3 / 1    56 x  56 x 128   ->    56 x  56 x 256
    6 conv    256  1 x 1 / 1    56 x  56 x 256   ->    56 x  56 x 256
    7 conv    512  3 x 3 / 1    56 x  56 x 256   ->    56 x  56 x 512
    8 max          2 x 2 / 2    56 x  56 x 512   ->    28 x  28 x 512
    9 conv    256  1 x 1 / 1    28 x  28 x 512   ->    28 x  28 x 256
   10 conv    512  3 x 3 / 1    28 x  28 x 256   ->    28 x  28 x 512
   11 conv    256  1 x 1 / 1    28 x  28 x 512   ->    28 x  28 x 256
   12 conv    512  3 x 3 / 1    28 x  28 x 256   ->    28 x  28 x 512
   13 conv    256  1 x 1 / 1    28 x  28 x 512   ->    28 x  28 x 256
   14 conv    512  3 x 3 / 1    28 x  28 x 256   ->    28 x  28 x 512
   15 conv    256  1 x 1 / 1    28 x  28 x 512   ->    28 x  28 x 256
   16 conv    512  3 x 3 / 1    28 x  28 x 256   ->    28 x  28 x 512
   17 conv    512  1 x 1 / 1    28 x  28 x 512   ->    28 x  28 x 512
   18 conv   1024  3 x 3 / 1    28 x  28 x 512   ->    28 x  28 x1024
   19 max          2 x 2 / 2    28 x  28 x1024   ->    14 x  14 x1024
   20 conv    512  1 x 1 / 1    14 x  14 x1024   ->    14 x  14 x 512
   21 conv   1024  3 x 3 / 1    14 x  14 x 512   ->    14 x  14 x1024
   22 conv    512  1 x 1 / 1    14 x  14 x1024   ->    14 x  14 x 512
   23 conv   1024  3 x 3 / 1    14 x  14 x 512   ->    14 x  14 x1024
   24 conv   1024  3 x 3 / 1    14 x  14 x1024   ->    14 x  14 x1024
   25 conv   1024  3 x 3 / 2    14 x  14 x1024   ->     7 x   7 x1024
   26 conv   1024  3 x 3 / 1     7 x   7 x1024   ->     7 x   7 x1024
   27 conv   1024  3 x 3 / 1     7 x   7 x1024   ->     7 x   7 x1024
   28 Local Layer: 7 x 7 x 1024 image, 256 filters -> 7 x 7 x 256 image
   29 dropout       p = 0.50               12544  ->  12544
   30 connected                            12544  ->   784
   31 Detection Layer
forced: Using default '0'
Loading weights from darknet.conv.weights...Done!
Learning Rate: 0.0005, Momentum: 0.9, Decay: 0.0005
Loaded: 1.446220 seconds
Detection Avg IOU: 0.000000, Pos Cat: 0.000000, All Cat: 0.000000, Pos Obj: 0.000000, Any Obj: 0.000000, count: 18
Detection Avg IOU: 0.000000, Pos Cat: 0.000000, All Cat: 0.000000, Pos Obj: 0.000000, Any Obj: 0.000000, count: 19
Detection Avg IOU: 0.000000, Pos Cat: 0.000000, All Cat: 0.000000, Pos Obj: 0.000000, Any Obj: 0.000000, count: 19
Detection Avg IOU: 0.000000, Pos Cat: 0.000000, All Cat: 0.000000, Pos Obj: 0.000000, Any Obj: 0.000000, count: 18
1: 27.096424, 27.096424 avg, 0.000500 rate, 9.151883 seconds, 64 images
Loaded: 0.000042 seconds

Does anyone know why does this happen?The GPU training does not seems to have any result.


问:
Is there a standardized method to swap two variables in Python?
In Python, I've seen two variable values swapped using this syntax:

```<code>left, right = right, left
</code>```

Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped?

答:
Does not work for multidimensional arrays, because references are used here.

```<code>import numpy as np

# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)

# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)
</code>```

See also Swap slices of Numpy arrays

Body:
In Python, I've seen two variable values swapped using this syntax:

left, right = right, left

Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped?

Body:
Does not work for multidimensional arrays, because references are used here.

import numpy as np

# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)

# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)

See also Swap slices of Numpy arrays